PrintersPage.tsx 410 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { formatPrintName } from '../utils/printName';
  5. import { computePopoverPosition } from '../utils/popoverPosition';
  6. import {
  7. BED_TEMP_DEFAULTS,
  8. CHAMBER_TEMP_DEFAULTS,
  9. FAN_SPEED_DEFAULTS,
  10. NOZZLE_TEMP_DEFAULTS,
  11. buildPresetOptions,
  12. parsePresetTriple,
  13. } from '../utils/temperatureFanPresets';
  14. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  15. // covers header + filament select + temp slider + duration + rotate-tray
  16. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  17. // earlier); under-estimating leaves the popover clipped off the bottom (the
  18. // original bug at #1447).
  19. const DRYING_POPOVER_WIDTH = 240;
  20. const DRYING_POPOVER_ESTIMATED_HEIGHT = 320;
  21. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  22. import { useTranslation } from 'react-i18next';
  23. import { useTheme } from '../contexts/ThemeContext';
  24. import { useAuth } from '../contexts/AuthContext';
  25. import {
  26. Plus,
  27. Link,
  28. Unlink,
  29. Signal,
  30. Clock,
  31. MoreVertical,
  32. Trash2,
  33. RefreshCw,
  34. RotateCw,
  35. Box,
  36. HardDrive,
  37. AlertTriangle,
  38. AlertCircle,
  39. Terminal,
  40. Power,
  41. Zap,
  42. Wrench,
  43. ChevronDown,
  44. Filter,
  45. Pencil,
  46. ArrowLeft,
  47. ArrowRight,
  48. ArrowUp,
  49. ArrowDown,
  50. Layers,
  51. Video,
  52. Search,
  53. Loader2,
  54. Square,
  55. Pause,
  56. Play,
  57. X,
  58. Fan,
  59. Wind,
  60. AirVent,
  61. Download,
  62. ScanSearch,
  63. CheckCircle,
  64. CheckSquare,
  65. XCircle,
  66. User,
  67. Home,
  68. Printer as PrinterIcon,
  69. Info,
  70. Cable,
  71. Flame,
  72. Repeat,
  73. Snowflake,
  74. Gauge,
  75. DoorOpen,
  76. DoorClosed,
  77. Move,
  78. LogIn,
  79. LogOut,
  80. MoreHorizontal,
  81. SlidersHorizontal,
  82. Stethoscope,
  83. LineChart as LineChartIcon,
  84. } from 'lucide-react';
  85. import { useNavigate } from 'react-router-dom';
  86. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  87. import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
  88. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  89. import { Card, CardContent } from '../components/Card';
  90. import { Button } from '../components/Button';
  91. import { ConfirmModal } from '../components/ConfirmModal';
  92. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  93. import { FileManagerModal } from '../components/FileManagerModal';
  94. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  95. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  96. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  97. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  98. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  99. import { AmsBackupModal } from '../components/AmsBackupModal';
  100. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  101. import type { HeaterSensorKind } from '../api/client';
  102. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  103. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  104. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  105. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  106. import { useToast } from '../contexts/ToastContext';
  107. import { ChamberLight } from '../components/icons/ChamberLight';
  108. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  109. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  110. import { FileUploadModal } from '../components/FileUploadModal';
  111. import { PrintModal } from '../components/PrintModal';
  112. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  113. import { getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool } from '../utils/amsHelpers';
  114. import { getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
  115. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  116. import { Collapsible } from '../components/Collapsible';
  117. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  118. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  119. export interface SpoolmanSlotAssignmentRow {
  120. printer_id: number;
  121. ams_id: number;
  122. tray_id: number;
  123. spoolman_spool_id: number;
  124. }
  125. // Color names resolve via getColorName() which reads the backend color_catalog
  126. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  127. // Format K value with 3 decimal places, default to 0.020 if null
  128. function formatKValue(k: number | null | undefined): string {
  129. const value = k ?? 0.020;
  130. return value.toFixed(3);
  131. }
  132. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  133. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  134. const { mode } = useTheme();
  135. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  136. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  137. return (
  138. <span
  139. className="inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded"
  140. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  141. >
  142. {side}
  143. </span>
  144. );
  145. }
  146. // Expand nozzle type codes to material names
  147. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  148. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  149. function nozzleTypeName(type: string, t: (key: string) => string): string {
  150. if (!type) return '';
  151. // Full text names (from main nozzle info)
  152. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  153. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  154. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  155. // 4-char codes (e.g. "HS01"): last 2 digits = material
  156. if (type.length >= 4) {
  157. const material = type.slice(2, 4);
  158. if (material === '00') return t('printers.nozzleStainlessSteel');
  159. if (material === '01') return t('printers.nozzleHardenedSteel');
  160. if (material === '05') return t('printers.nozzleTungstenCarbide');
  161. }
  162. // 2-digit numeric codes
  163. if (type === '00') return t('printers.nozzleStainlessSteel');
  164. if (type === '01') return t('printers.nozzleHardenedSteel');
  165. if (type === '05') return t('printers.nozzleTungstenCarbide');
  166. // 2-char alpha codes: H prefix = hardened steel
  167. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  168. return type;
  169. }
  170. // Parse flow type from nozzle type code
  171. // HH = high flow, HS = standard/normal
  172. function nozzleFlowName(type: string, t: (key: string) => string): string {
  173. if (!type) return '';
  174. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  175. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  176. return '';
  177. }
  178. // Per-slot hover card for nozzle rack
  179. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  180. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  181. slot: import('../api/client').NozzleRackSlot;
  182. index: number;
  183. activeStatus?: boolean;
  184. filamentName?: string;
  185. children: React.ReactNode;
  186. }) {
  187. const { t } = useTranslation();
  188. const [isVisible, setIsVisible] = useState(false);
  189. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  190. const triggerRef = useRef<HTMLDivElement>(null);
  191. const cardRef = useRef<HTMLDivElement>(null);
  192. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  193. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  194. const isMounted = slot.stat === 1;
  195. useEffect(() => {
  196. if (isVisible && triggerRef.current && cardRef.current) {
  197. const triggerRect = triggerRef.current.getBoundingClientRect();
  198. const cardHeight = cardRef.current.offsetHeight;
  199. const headerHeight = 56;
  200. const spaceAbove = triggerRect.top - headerHeight;
  201. const spaceBelow = window.innerHeight - triggerRect.bottom;
  202. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  203. setPosition('bottom');
  204. } else {
  205. setPosition('top');
  206. }
  207. }
  208. }, [isVisible]);
  209. const handleMouseEnter = () => {
  210. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  211. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  212. };
  213. const handleMouseLeave = () => {
  214. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  215. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  216. };
  217. useEffect(() => {
  218. return () => {
  219. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  220. };
  221. }, []);
  222. const filamentCss = parseFilamentColor(slot.filament_color);
  223. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  224. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  225. return (
  226. <div
  227. ref={triggerRef}
  228. className="relative"
  229. onMouseEnter={handleMouseEnter}
  230. onMouseLeave={handleMouseLeave}
  231. >
  232. {children}
  233. {isVisible && (
  234. <div
  235. ref={cardRef}
  236. className={`
  237. absolute left-1/2 -translate-x-1/2 z-50
  238. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  239. animate-in fade-in-0 zoom-in-95 duration-150
  240. `}
  241. style={{ maxWidth: 'calc(100vw - 24px)' }}
  242. >
  243. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  244. {isEmpty ? (
  245. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  246. Slot {index + 1} — Empty
  247. </div>
  248. ) : (
  249. <div className="p-2.5 space-y-1.5">
  250. {/* Diameter */}
  251. <div className="flex items-center justify-between">
  252. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  253. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  254. </div>
  255. {/* Type */}
  256. {typeFull && (
  257. <div className="flex items-center justify-between">
  258. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  259. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  260. </div>
  261. )}
  262. {/* Flow (hide if empty) */}
  263. {flowFull && (
  264. <div className="flex items-center justify-between">
  265. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  266. <span className="text-xs text-white font-semibold">{flowFull}</span>
  267. </div>
  268. )}
  269. {/* Status badge */}
  270. <div className="flex items-center justify-between">
  271. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  272. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  273. activeStatus || isMounted
  274. ? 'bg-green-900/50 text-green-400'
  275. : 'bg-bambu-dark-tertiary text-bambu-gray'
  276. }`}>
  277. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  278. </span>
  279. </div>
  280. {/* Wear (hide if null) */}
  281. {slot.wear != null && (
  282. <div className="flex items-center justify-between">
  283. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  284. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  285. </div>
  286. )}
  287. {/* Max Temp (hide if 0) */}
  288. {slot.max_temp > 0 && (
  289. <div className="flex items-center justify-between">
  290. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  291. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  292. </div>
  293. )}
  294. {/* Serial (hide if empty) */}
  295. {slot.serial_number && (
  296. <div className="flex items-center justify-between">
  297. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  298. <span className="text-[10px] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  299. </div>
  300. )}
  301. {/* Filament: material type + color swatch (hide if no color) */}
  302. {(filamentCss || slot.filament_type) && (
  303. <div className="flex items-center justify-between">
  304. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  305. <div className="flex items-center gap-1">
  306. {filamentCss && (
  307. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  308. )}
  309. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  310. </div>
  311. </div>
  312. )}
  313. </div>
  314. )}
  315. </div>
  316. {/* Arrow pointer */}
  317. <div
  318. className={`
  319. absolute left-1/2 -translate-x-1/2 w-0 h-0
  320. border-l-[6px] border-l-transparent
  321. border-r-[6px] border-r-transparent
  322. ${position === 'top'
  323. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  324. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  325. `}
  326. />
  327. </div>
  328. )}
  329. </div>
  330. );
  331. }
  332. // Dual-nozzle hover card showing L and R nozzle details side by side
  333. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  334. leftSlot?: import('../api/client').NozzleRackSlot;
  335. rightSlot?: import('../api/client').NozzleRackSlot;
  336. activeNozzle: 'L' | 'R';
  337. filamentInfo?: Record<string, { name: string; k: number | null }>;
  338. children: React.ReactNode;
  339. }) {
  340. const { t } = useTranslation();
  341. const [isVisible, setIsVisible] = useState(false);
  342. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  343. const triggerRef = useRef<HTMLDivElement>(null);
  344. const cardRef = useRef<HTMLDivElement>(null);
  345. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  346. useEffect(() => {
  347. if (isVisible && triggerRef.current && cardRef.current) {
  348. const triggerRect = triggerRef.current.getBoundingClientRect();
  349. const cardHeight = cardRef.current.offsetHeight;
  350. const headerHeight = 56;
  351. const spaceAbove = triggerRect.top - headerHeight;
  352. const spaceBelow = window.innerHeight - triggerRect.bottom;
  353. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  354. setPosition('bottom');
  355. } else {
  356. setPosition('top');
  357. }
  358. }
  359. }, [isVisible]);
  360. const handleMouseEnter = () => {
  361. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  362. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  363. };
  364. const handleMouseLeave = () => {
  365. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  366. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  367. };
  368. useEffect(() => {
  369. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  370. }, []);
  371. if (!leftSlot && !rightSlot) return <>{children}</>;
  372. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  373. const isActive = activeNozzle === side;
  374. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  375. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  376. const filamentCss = parseFilamentColor(slot.filament_color);
  377. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  378. return (
  379. <div className="flex-1 space-y-1.5">
  380. <div className={`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-400' : 'text-bambu-gray'}`}>
  381. {side === 'L' ? t('common.left') : t('common.right')}
  382. </div>
  383. {slot.nozzle_diameter && (
  384. <div className="flex items-center justify-between">
  385. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  386. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  387. </div>
  388. )}
  389. {typeFull && (
  390. <div className="flex items-center justify-between">
  391. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleType')}</span>
  392. <span className="text-[10px] text-white font-semibold">{typeFull}</span>
  393. </div>
  394. )}
  395. {flowFull && (
  396. <div className="flex items-center justify-between">
  397. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  398. <span className="text-[10px] text-white font-semibold">{flowFull}</span>
  399. </div>
  400. )}
  401. <div className="flex items-center justify-between">
  402. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  403. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  404. isActive
  405. ? 'bg-green-900/50 text-green-400'
  406. : 'bg-bambu-dark-tertiary text-bambu-gray'
  407. }`}>
  408. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  409. </span>
  410. </div>
  411. {slot.wear != null && (
  412. <div className="flex items-center justify-between">
  413. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleWear')}</span>
  414. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  415. </div>
  416. )}
  417. {/* Serial and max temp only available on the right (removable) nozzle */}
  418. {side === 'R' && slot.max_temp > 0 && (
  419. <div className="flex items-center justify-between">
  420. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  421. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  422. </div>
  423. )}
  424. {side === 'R' && slot.serial_number && (
  425. <div className="flex items-center justify-between">
  426. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  427. <span className="text-[10px] text-white font-mono">{slot.serial_number}</span>
  428. </div>
  429. )}
  430. {(filamentCss || slot.filament_type || slot.filament_id) && (
  431. <div className="flex items-center justify-between">
  432. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  433. <div className="flex items-center gap-1">
  434. {filamentCss && (
  435. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  436. )}
  437. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">
  438. {filamentName || slot.filament_type || slot.filament_id || ''}
  439. </span>
  440. </div>
  441. </div>
  442. )}
  443. </div>
  444. );
  445. };
  446. return (
  447. <div
  448. ref={triggerRef}
  449. className="relative flex-1"
  450. onMouseEnter={handleMouseEnter}
  451. onMouseLeave={handleMouseLeave}
  452. >
  453. {children}
  454. {isVisible && (
  455. <div
  456. ref={cardRef}
  457. className={`
  458. absolute left-1/2 -translate-x-1/2 z-50
  459. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  460. animate-in fade-in-0 zoom-in-95 duration-150
  461. `}
  462. style={{ maxWidth: 'calc(100vw - 24px)' }}
  463. >
  464. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  465. <div className="p-2.5 flex gap-3">
  466. {leftSlot && renderColumn(leftSlot, 'L')}
  467. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  468. {rightSlot && renderColumn(rightSlot, 'R')}
  469. </div>
  470. </div>
  471. {/* Arrow pointer */}
  472. <div
  473. className={`
  474. absolute left-1/2 -translate-x-1/2 w-0 h-0
  475. border-l-[6px] border-l-transparent
  476. border-r-[6px] border-r-transparent
  477. ${position === 'top'
  478. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  479. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  480. `}
  481. />
  482. </div>
  483. )}
  484. </div>
  485. );
  486. }
  487. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  488. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  489. const { t } = useTranslation();
  490. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  491. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  492. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  493. // base — computing it from min(present IDs) shifts everything left when slot 16
  494. // is the one currently mounted (#943).
  495. const rackNozzles = slots.filter(s => s.id >= 2);
  496. const RACK_SIZE = 6;
  497. const RACK_BASE_ID = 16;
  498. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  499. { length: RACK_SIZE },
  500. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  501. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  502. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  503. },
  504. );
  505. return (
  506. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center">
  507. <p className="text-[9px] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  508. <div className="flex gap-[3px] justify-center">
  509. {rackSlots.map((slot, i) => {
  510. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  511. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  512. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  513. return (
  514. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  515. <div
  516. className={`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  517. isEmpty
  518. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  519. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  520. }`}
  521. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  522. >
  523. <span className={`text-[10px] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  524. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  525. >
  526. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  527. </span>
  528. </div>
  529. </NozzleSlotHoverCard>
  530. );
  531. })}
  532. </div>
  533. </div>
  534. );
  535. }
  536. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  537. function WaterDropEmpty({ className }: { className?: string }) {
  538. return (
  539. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  540. <path d="M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z" fill="#C3C2C1"/>
  541. </svg>
  542. );
  543. }
  544. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  545. function WaterDropHalf({ className }: { className?: string }) {
  546. return (
  547. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  548. <path d="M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z" fill="#C3C2C1"/>
  549. <path d="M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z" fill="#1F8FEB"/>
  550. </svg>
  551. );
  552. }
  553. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  554. function WaterDropFull({ className }: { className?: string }) {
  555. return (
  556. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  557. <path d="M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z" fill="#1F8FEB"/>
  558. <path d="M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z" fill="#C3C2C1"/>
  559. </svg>
  560. );
  561. }
  562. // Thermometer SVG - empty outline
  563. function ThermometerEmpty({ className }: { className?: string }) {
  564. return (
  565. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  566. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  567. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  568. </svg>
  569. );
  570. }
  571. // Thermometer SVG - half filled (gold - same as humidity fair)
  572. function ThermometerHalf({ className }: { className?: string }) {
  573. return (
  574. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  575. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  576. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  577. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  578. </svg>
  579. );
  580. }
  581. // Thermometer SVG - fully filled (red - same as humidity bad)
  582. function ThermometerFull({ className }: { className?: string }) {
  583. return (
  584. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  585. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  586. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  587. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  588. </svg>
  589. );
  590. }
  591. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  592. // Added for visual parity with the thermometer icons on the dual-nozzle card
  593. // that previously had no icon at all (#1115, design by @m4rtini2).
  594. function NozzleIcon({ className }: { className?: string }) {
  595. return (
  596. <svg
  597. className={className}
  598. viewBox="0 0 24 24"
  599. fill="none"
  600. xmlns="http://www.w3.org/2000/svg"
  601. stroke="currentColor"
  602. strokeWidth="1.5"
  603. strokeLinecap="round"
  604. strokeLinejoin="round"
  605. >
  606. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  607. <rect x="6" y="11.5" width="12.1" height="3.7" />
  608. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  609. </svg>
  610. );
  611. }
  612. // Heater thermometer icon - filled when heating, outline when off
  613. interface HeaterThermometerProps {
  614. className?: string;
  615. color: string; // The color class (e.g., "text-orange-400")
  616. isHeating: boolean;
  617. }
  618. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  619. // Extract the actual color from Tailwind class for SVG fill
  620. const colorMap: Record<string, string> = {
  621. 'text-orange-400': '#fb923c',
  622. 'text-blue-400': '#60a5fa',
  623. 'text-green-400': '#4ade80',
  624. };
  625. const fillColor = colorMap[color] || '#888';
  626. // Glow style when heating
  627. const glowStyle = isHeating ? {
  628. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  629. } : {};
  630. if (isHeating) {
  631. // Filled thermometer with glow - heater is ON
  632. return (
  633. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  634. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  635. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  636. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke={fillColor} strokeWidth="1" fill="none"/>
  637. </svg>
  638. );
  639. }
  640. // Empty thermometer - heater is OFF
  641. return (
  642. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  643. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke={fillColor} strokeWidth="1" fill="none"/>
  644. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  645. </svg>
  646. );
  647. }
  648. // AMS Filament Backup tri-state indicator + toggle.
  649. // state=true → ON, click to disable
  650. // state=false → OFF, click opens modal
  651. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  652. interface AmsBackupBadgeProps {
  653. state: boolean | null;
  654. onClick: () => void;
  655. }
  656. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  657. const { t } = useTranslation();
  658. const known = state !== null;
  659. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors ';
  660. let title: string;
  661. if (state === true) {
  662. className += known
  663. ? 'bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  664. : 'bg-blue-500/20 text-blue-400 cursor-default';
  665. title = t('printers.amsBackup.titleOn');
  666. } else if (state === false) {
  667. className += known
  668. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  669. : 'bg-bambu-dark text-bambu-gray cursor-default';
  670. title = t('printers.amsBackup.titleOff');
  671. } else {
  672. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  673. title = t('printers.amsBackup.titleUnknown');
  674. }
  675. return (
  676. <button
  677. type="button"
  678. disabled={!known}
  679. onClick={() => known && onClick()}
  680. className={className}
  681. title={title}
  682. aria-label={title}
  683. >
  684. {known ? <Repeat className="w-3 h-3" /> : <span>?</span>}
  685. </button>
  686. );
  687. }
  688. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  689. // Reference: https://github.com/theicedmango/bambu-humidity
  690. interface HumidityIndicatorProps {
  691. humidity: number | string;
  692. goodThreshold?: number; // <= this is green
  693. fairThreshold?: number; // <= this is orange, > is red
  694. onClick?: () => void;
  695. compact?: boolean; // Smaller version for grid layout
  696. }
  697. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  698. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  699. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  700. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  701. // Status thresholds (configurable via settings)
  702. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  703. let textColor: string;
  704. let statusText: string;
  705. if (isNaN(humidityValue)) {
  706. textColor = '#C3C2C1';
  707. statusText = 'Unknown';
  708. } else if (humidityValue <= good) {
  709. textColor = '#22a352'; // Green - Good
  710. statusText = 'Good';
  711. } else if (humidityValue <= fair) {
  712. textColor = '#d4a017'; // Gold - Fair
  713. statusText = 'Fair';
  714. } else {
  715. textColor = '#c62828'; // Red - Bad
  716. statusText = 'Bad';
  717. }
  718. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  719. let DropComponent: React.FC<{ className?: string }>;
  720. if (isNaN(humidityValue)) {
  721. DropComponent = WaterDropEmpty;
  722. } else if (humidityValue <= good) {
  723. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  724. } else if (humidityValue <= fair) {
  725. DropComponent = WaterDropHalf; // Fair - half filled
  726. } else {
  727. DropComponent = WaterDropFull; // Bad - full (too humid)
  728. }
  729. return (
  730. <button
  731. type="button"
  732. onClick={onClick}
  733. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  734. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  735. >
  736. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  737. <span className={`font-medium tabular-nums ${compact ? 'text-[10px]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  738. </button>
  739. );
  740. }
  741. // Temperature indicator with dynamic icon and coloring
  742. interface TemperatureIndicatorProps {
  743. temp: number;
  744. goodThreshold?: number; // <= this is blue
  745. fairThreshold?: number; // <= this is orange, > is red
  746. onClick?: () => void;
  747. compact?: boolean; // Smaller version for grid layout
  748. }
  749. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  750. // Ensure thresholds are numbers
  751. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  752. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  753. let textColor: string;
  754. let statusText: string;
  755. let ThermoComponent: React.FC<{ className?: string }>;
  756. if (temp <= good) {
  757. textColor = '#22a352'; // Green - good (same as humidity)
  758. statusText = 'Good';
  759. ThermoComponent = ThermometerEmpty;
  760. } else if (temp <= fair) {
  761. textColor = '#d4a017'; // Gold - fair (same as humidity)
  762. statusText = 'Fair';
  763. ThermoComponent = ThermometerHalf;
  764. } else {
  765. textColor = '#c62828'; // Red - bad (same as humidity)
  766. statusText = 'Bad';
  767. ThermoComponent = ThermometerFull;
  768. }
  769. return (
  770. <button
  771. type="button"
  772. onClick={onClick}
  773. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  774. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  775. >
  776. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  777. <span className={`tabular-nums text-right ${compact ? 'text-[10px] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  778. </button>
  779. );
  780. }
  781. function getAmsLabel(amsId: number | string, trayCount: number): string {
  782. // Ensure amsId is a number (backend might send string)
  783. const id = typeof amsId === 'string' ? parseInt(amsId, 10) : amsId;
  784. const safeId = isNaN(id) ? 0 : id;
  785. const isHt = trayCount === 1;
  786. // AMS-HT uses IDs starting at 128, regular AMS uses 0-3
  787. const normalizedId = safeId >= 128 ? safeId - 128 : safeId;
  788. const letter = String.fromCharCode(65 + normalizedId); // 0=A, 1=B, 2=C, 3=D
  789. return isHt ? `HT-${letter}` : `AMS-${letter}`;
  790. }
  791. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  792. *
  793. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  794. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  795. * every empty-by-bitmask slot lands here regardless of firmware payload
  796. * shape.
  797. *
  798. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  799. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  800. * the user cleared with "Reset Slot" where a physical spool may still be
  801. * loaded but unassigned.
  802. *
  803. * Returns null when the slot is loaded (tray_type is present).
  804. */
  805. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null } | null | undefined): 'physical' | 'reset' | null {
  806. if (tray?.tray_type) return null;
  807. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  808. }
  809. function CoverImage({
  810. url,
  811. printName,
  812. className = 'w-20 h-20',
  813. radiusClass = 'rounded-lg',
  814. }: {
  815. url: string | null;
  816. printName?: string;
  817. className?: string;
  818. radiusClass?: string;
  819. }) {
  820. const { t } = useTranslation();
  821. const [loaded, setLoaded] = useState(false);
  822. const [error, setError] = useState(false);
  823. const [showOverlay, setShowOverlay] = useState(false);
  824. // Cache-bust the image URL when the print name changes so the browser
  825. // fetches the new cover instead of serving the stale cached image.
  826. const cacheBustedUrl = useMemo(() => {
  827. if (!url) return null;
  828. const sep = url.includes('?') ? '&' : '?';
  829. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  830. }, [url, printName]);
  831. // Reset loaded/error state when the image URL changes
  832. useEffect(() => {
  833. setLoaded(false);
  834. setError(false);
  835. }, [cacheBustedUrl]);
  836. return (
  837. <>
  838. <div
  839. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  840. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  841. >
  842. {cacheBustedUrl && !error ? (
  843. <>
  844. <img
  845. src={cacheBustedUrl}
  846. alt={t('printers.printPreview')}
  847. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  848. onLoad={() => setLoaded(true)}
  849. onError={() => setError(true)}
  850. />
  851. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  852. </>
  853. ) : (
  854. <Box className="w-8 h-8 text-bambu-gray" />
  855. )}
  856. </div>
  857. {/* Cover Image Overlay */}
  858. {showOverlay && cacheBustedUrl && (
  859. <div
  860. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  861. onClick={() => setShowOverlay(false)}
  862. >
  863. <div className="relative max-w-2xl max-h-full">
  864. <img
  865. src={cacheBustedUrl}
  866. alt={t('printers.printPreview')}
  867. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  868. />
  869. {printName && (
  870. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  871. )}
  872. </div>
  873. </div>
  874. )}
  875. </>
  876. );
  877. }
  878. interface PrinterMaintenanceInfo {
  879. due_count: number;
  880. warning_count: number;
  881. total_print_hours: number;
  882. }
  883. // Status summary bar component - uses queryClient to read cached statuses
  884. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  885. const { t } = useTranslation();
  886. const queryClient = useQueryClient();
  887. // Subscribe to query cache changes to re-render when status updates
  888. // Throttled to prevent rapid re-renders from causing tab crashes
  889. const [cacheTick, setCacheTick] = useState(0);
  890. useEffect(() => {
  891. let pending = false;
  892. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  893. if (!pending) {
  894. pending = true;
  895. requestAnimationFrame(() => {
  896. setCacheTick(t => t + 1);
  897. pending = false;
  898. });
  899. }
  900. });
  901. return () => unsubscribe();
  902. }, [queryClient]);
  903. const { counts, nextFinish } = useMemo(() => {
  904. let printing = 0;
  905. let paused = 0;
  906. let finished = 0;
  907. let idle = 0;
  908. let offline = 0;
  909. let loading = 0;
  910. let error = 0;
  911. let nextPrinterName: string | null = null;
  912. let nextRemainingMin: number | null = null;
  913. let nextProgress: number = 0;
  914. printers?.forEach((printer) => {
  915. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  916. if (status === undefined) {
  917. // Status not yet loaded - don't count as offline yet
  918. loading++;
  919. } else if (!status.connected) {
  920. offline++;
  921. } else {
  922. // Count printers with active HMS errors as problems
  923. const knownHmsCount =
  924. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  925. if (knownHmsCount > 0) {
  926. error++;
  927. }
  928. switch (status.state) {
  929. case 'RUNNING':
  930. printing++;
  931. if (status.remaining_time != null && status.remaining_time > 0) {
  932. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  933. nextRemainingMin = status.remaining_time;
  934. nextPrinterName = printer.name;
  935. nextProgress = status.progress || 0;
  936. }
  937. }
  938. break;
  939. case 'PAUSE':
  940. paused++;
  941. break;
  942. case 'FINISH':
  943. finished++;
  944. break;
  945. case 'FAILED':
  946. // FAILED is the printer's terminal gcode_state after a print stops —
  947. // including user cancellations, where there's no actual fault. Only
  948. // count it as a "problem" when an HMS error is also active; otherwise
  949. // it's just a print that ended unsuccessfully and the plate needs
  950. // clearing (same as FINISH from the operator's perspective).
  951. if (knownHmsCount > 0) {
  952. // Already counted above
  953. } else {
  954. finished++;
  955. }
  956. break;
  957. default:
  958. idle++;
  959. break;
  960. }
  961. }
  962. });
  963. return {
  964. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  965. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  966. };
  967. // eslint-disable-next-line react-hooks/exhaustive-deps
  968. }, [printers, queryClient, cacheTick]);
  969. if (!printers?.length) return null;
  970. const badges: { count: number; dot: string; label: string }[] = [
  971. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  972. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  973. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  974. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  975. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  976. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  977. ];
  978. return (
  979. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  980. {badges.map(({ count, dot, label }) => count > 0 && (
  981. <div key={label} className="flex items-center gap-1.5">
  982. <div className={`w-2 h-2 rounded-full ${dot}`} />
  983. <span className="text-bambu-gray">
  984. <span className="text-white font-medium">{count}</span> {label}
  985. </span>
  986. </div>
  987. ))}
  988. {nextFinish && (
  989. <>
  990. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  991. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  992. <div className="flex items-center gap-2">
  993. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  994. <span className="text-white font-medium">{nextFinish.name}</span>
  995. </div>
  996. <div className="flex items-center gap-2 w-full sm:w-auto">
  997. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  998. <div
  999. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1000. style={{ width: `${nextFinish.progress}%` }}
  1001. />
  1002. </div>
  1003. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1004. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1005. </div>
  1006. </div>
  1007. </>
  1008. )}
  1009. </div>
  1010. );
  1011. }
  1012. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1013. type ViewMode = 'expanded' | 'compact';
  1014. type ToolbarDropdownOption<T extends string> = {
  1015. value: T;
  1016. label: string;
  1017. };
  1018. function ToolbarDropdown<T extends string>({
  1019. value,
  1020. options,
  1021. onChange,
  1022. fullWidth = false,
  1023. }: {
  1024. value: T;
  1025. options: ToolbarDropdownOption<T>[];
  1026. onChange: (value: T) => void;
  1027. fullWidth?: boolean;
  1028. }) {
  1029. const [isOpen, setIsOpen] = useState(false);
  1030. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1031. return (
  1032. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1033. <button
  1034. type="button"
  1035. onClick={() => setIsOpen(open => !open)}
  1036. className={`h-8 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white text-sm font-medium transition-colors hover:bg-bambu-dark-tertiary focus:outline-none focus:border-bambu-green flex items-center justify-between gap-2 ${fullWidth ? 'w-full' : 'min-w-28'}`}
  1037. >
  1038. <span className="truncate">{selectedOption?.label}</span>
  1039. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1040. </button>
  1041. {isOpen && (
  1042. <>
  1043. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1044. <div className="absolute left-0 top-full z-20 mt-1 min-w-full rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary py-1 shadow-xl">
  1045. {options.map(option => (
  1046. <button
  1047. key={option.value}
  1048. type="button"
  1049. onClick={() => {
  1050. onChange(option.value);
  1051. setIsOpen(false);
  1052. }}
  1053. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1054. option.value === value ? 'text-bambu-green' : 'text-white'
  1055. }`}
  1056. >
  1057. {option.label}
  1058. </button>
  1059. ))}
  1060. </div>
  1061. </>
  1062. )}
  1063. </div>
  1064. );
  1065. }
  1066. function ToolbarMenu({
  1067. label,
  1068. icon,
  1069. children,
  1070. }: {
  1071. label: string;
  1072. icon: React.ReactNode;
  1073. children: React.ReactNode;
  1074. }) {
  1075. const [isOpen, setIsOpen] = useState(false);
  1076. return (
  1077. <div className="relative">
  1078. <button
  1079. type="button"
  1080. onClick={() => setIsOpen(open => !open)}
  1081. className="h-8 w-8 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center"
  1082. aria-label={label}
  1083. title={label}
  1084. >
  1085. {icon}
  1086. </button>
  1087. {isOpen && (
  1088. <>
  1089. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1090. <div className="absolute right-0 top-full z-20 mt-1 min-w-40 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary p-2 shadow-xl">
  1091. {children}
  1092. </div>
  1093. </>
  1094. )}
  1095. </div>
  1096. );
  1097. }
  1098. function IndicatorControlPopover({
  1099. title,
  1100. options = [],
  1101. unit,
  1102. customMin,
  1103. customMax,
  1104. customStep = 1,
  1105. widthClass = 'w-[240px]',
  1106. popoverWidth = 240,
  1107. popoverHeight = 280,
  1108. isPending,
  1109. onClose,
  1110. onSubmit,
  1111. children,
  1112. }: {
  1113. title: string;
  1114. options?: Array<{ label: string; value: number }>;
  1115. unit?: string;
  1116. customMin?: number;
  1117. customMax?: number;
  1118. customStep?: number;
  1119. widthClass?: string;
  1120. popoverWidth?: number;
  1121. popoverHeight?: number;
  1122. isPending?: boolean;
  1123. onClose: () => void;
  1124. onSubmit?: (value: number) => void;
  1125. children?: React.ReactNode;
  1126. }) {
  1127. const anchorRef = useRef<HTMLSpanElement>(null);
  1128. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1129. const [customValue, setCustomValue] = useState('');
  1130. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1131. // can position via fixed coords. Portaling to document.body escapes
  1132. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1133. // own contexts and would otherwise cover the popover even at z-[60].
  1134. useLayoutEffect(() => {
  1135. const trigger = anchorRef.current?.parentElement;
  1136. if (!trigger) return;
  1137. const measure = () => {
  1138. const rect = trigger.getBoundingClientRect();
  1139. setCoords(computePopoverPosition({
  1140. triggerRect: rect,
  1141. popoverWidth,
  1142. estimatedHeight: popoverHeight,
  1143. horizontalAlign: 'center',
  1144. }));
  1145. };
  1146. measure();
  1147. window.addEventListener('resize', measure);
  1148. window.addEventListener('scroll', measure, true);
  1149. return () => {
  1150. window.removeEventListener('resize', measure);
  1151. window.removeEventListener('scroll', measure, true);
  1152. };
  1153. }, [popoverWidth, popoverHeight]);
  1154. const showCustomInput = unit !== undefined;
  1155. const submitCustom = () => {
  1156. const value = Number(customValue);
  1157. if (!Number.isFinite(value)) return;
  1158. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1159. onSubmit?.(Math.round(bounded));
  1160. };
  1161. return (
  1162. <>
  1163. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1164. {createPortal(
  1165. <>
  1166. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1167. <div
  1168. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1169. style={{
  1170. top: coords?.top ?? -9999,
  1171. left: coords?.left ?? -9999,
  1172. visibility: coords ? 'visible' : 'hidden',
  1173. }}
  1174. onClick={e => e.stopPropagation()}
  1175. >
  1176. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1177. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1178. {options.length > 0 && (
  1179. <div className="px-3 py-2.5">
  1180. <div className="grid grid-cols-2 gap-1.5">
  1181. {options.map(option => (
  1182. <button
  1183. key={`${option.label}-${option.value}`}
  1184. type="button"
  1185. disabled={isPending}
  1186. onClick={() => onSubmit?.(option.value)}
  1187. className="h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1188. >
  1189. {option.label}
  1190. </button>
  1191. ))}
  1192. </div>
  1193. </div>
  1194. )}
  1195. {children}
  1196. {showCustomInput && (
  1197. <>
  1198. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1199. <form
  1200. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1201. onSubmit={(e) => {
  1202. e.preventDefault();
  1203. submitCustom();
  1204. }}
  1205. >
  1206. <input
  1207. type="number"
  1208. min={customMin}
  1209. max={customMax}
  1210. step={customStep}
  1211. value={customValue}
  1212. onChange={e => setCustomValue(e.target.value)}
  1213. placeholder="Custom"
  1214. className="h-8 min-w-0 flex-1 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none"
  1215. />
  1216. <button
  1217. type="submit"
  1218. disabled={isPending || customValue.trim() === ''}
  1219. className="h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1220. >
  1221. Set
  1222. </button>
  1223. </form>
  1224. </>
  1225. )}
  1226. </div>
  1227. </>,
  1228. document.body
  1229. )}
  1230. </>
  1231. );
  1232. }
  1233. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1234. function NozzleTemperatureControlBox({
  1235. label,
  1236. current,
  1237. target,
  1238. isActive,
  1239. isPending,
  1240. onSubmit,
  1241. options = NOZZLE_TEMPERATURE_OPTIONS,
  1242. }: {
  1243. label: string;
  1244. current?: number;
  1245. target?: number;
  1246. isActive: boolean;
  1247. isPending?: boolean;
  1248. onSubmit: (value: number) => void;
  1249. options?: Array<{ label: string; value: number }>;
  1250. }) {
  1251. const [customValue, setCustomValue] = useState('');
  1252. const submitCustom = () => {
  1253. const value = Number(customValue);
  1254. if (!Number.isFinite(value)) return;
  1255. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1256. };
  1257. return (
  1258. <div className={`rounded-lg border p-2 ${isActive ? 'border-amber-400/60 bg-amber-400/10' : 'border-bambu-dark-tertiary bg-bambu-dark'}`}>
  1259. <div className="mb-1.5 flex items-center justify-between gap-2">
  1260. <span className={`text-xs font-medium ${isActive ? 'text-amber-300' : 'text-white'}`}>{label}</span>
  1261. <span className="text-[10px] text-bambu-gray">
  1262. {Math.round(current ?? 0)}°C
  1263. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1264. </span>
  1265. </div>
  1266. <div className="grid grid-cols-2 gap-1">
  1267. {options.map(option => (
  1268. <button
  1269. key={`${label}-${option.value}`}
  1270. type="button"
  1271. disabled={isPending}
  1272. onClick={() => onSubmit(option.value)}
  1273. className="h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1274. >
  1275. {option.label}
  1276. </button>
  1277. ))}
  1278. </div>
  1279. <form
  1280. className="mt-1.5 flex gap-1"
  1281. onSubmit={(e) => {
  1282. e.preventDefault();
  1283. submitCustom();
  1284. }}
  1285. >
  1286. <input
  1287. type="number"
  1288. min={0}
  1289. max={320}
  1290. step={1}
  1291. value={customValue}
  1292. onChange={e => setCustomValue(e.target.value)}
  1293. placeholder="Custom"
  1294. className="h-7 min-w-0 flex-1 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none"
  1295. />
  1296. <button
  1297. type="submit"
  1298. disabled={isPending || customValue.trim() === ''}
  1299. className="h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-2 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1300. >
  1301. Set
  1302. </button>
  1303. </form>
  1304. </div>
  1305. );
  1306. }
  1307. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1308. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1309. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1310. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1311. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1312. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1313. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1314. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1315. };
  1316. /** Classify a printer into one of the UI status buckets. */
  1317. function classifyPrinterStatus(
  1318. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1319. ): PrinterState {
  1320. if (!status?.connected) return 'offline';
  1321. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1322. if (hmsErrors.length > 0) return 'error';
  1323. switch (status.state) {
  1324. case 'RUNNING': return 'printing';
  1325. case 'PAUSE': return 'paused';
  1326. case 'FINISH': return 'finished';
  1327. // FAILED without an active HMS error is the printer's terminal state after
  1328. // any unsuccessful end — including user-cancellations. Treat the same as
  1329. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1330. // HMS code is actually attached (handled by the early-return above).
  1331. case 'FAILED': return 'finished';
  1332. default: return 'idle';
  1333. }
  1334. }
  1335. /**
  1336. * Get human-readable status display text for a printer.
  1337. * Uses stg_cur_name for detailed calibration/preparation stages,
  1338. * otherwise formats the gcode_state nicely.
  1339. */
  1340. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1341. // If we have a specific stage name (calibration, heating, etc.), use it
  1342. if (stg_cur_name) {
  1343. return stg_cur_name;
  1344. }
  1345. // Format the gcode_state nicely
  1346. switch (state) {
  1347. case 'RUNNING':
  1348. return 'Printing';
  1349. case 'PAUSE':
  1350. return 'Paused';
  1351. case 'FINISH':
  1352. return 'Finished';
  1353. case 'FAILED':
  1354. return 'Failed';
  1355. case 'IDLE':
  1356. return 'Idle';
  1357. default:
  1358. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1359. }
  1360. }
  1361. // Bambu models that ship with an enclosure chamber fan (firmware field
  1362. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1363. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1364. // widget is hidden in fanItems instead of rendered greyed-out.
  1365. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1366. 'X1C',
  1367. 'X1',
  1368. 'X1E',
  1369. 'X2D',
  1370. 'P1S',
  1371. 'P2S',
  1372. 'H2D',
  1373. 'H2D Pro',
  1374. 'H2C',
  1375. 'H2S',
  1376. ]);
  1377. // Map SSDP model codes to display names
  1378. function mapModelCode(ssdpModel: string | null): string {
  1379. if (!ssdpModel) return '';
  1380. const modelMap: Record<string, string> = {
  1381. // H2 Series
  1382. 'O1D': 'H2D',
  1383. 'O1E': 'H2D Pro',
  1384. 'O2D': 'H2D Pro',
  1385. 'O1C': 'H2C',
  1386. 'O1C2': 'H2C',
  1387. 'O1S': 'H2S',
  1388. // X1 Series
  1389. 'BL-P001': 'X1C',
  1390. 'BL-P002': 'X1',
  1391. 'BL-P003': 'X1E',
  1392. // X2 Series
  1393. 'N6': 'X2D',
  1394. // A2 Series
  1395. 'N9': 'A2L',
  1396. // P Series
  1397. 'C11': 'P1S',
  1398. 'C12': 'P1P',
  1399. 'C13': 'P2S',
  1400. // A1 Series
  1401. 'N2S': 'A1',
  1402. 'N1': 'A1 Mini',
  1403. // Direct matches
  1404. 'X1C': 'X1C',
  1405. 'X1': 'X1',
  1406. 'X1E': 'X1E',
  1407. 'X2D': 'X2D',
  1408. 'P1S': 'P1S',
  1409. 'P1P': 'P1P',
  1410. 'P2S': 'P2S',
  1411. 'A1': 'A1',
  1412. 'A1 Mini': 'A1 Mini',
  1413. 'A2L': 'A2L',
  1414. 'H2D': 'H2D',
  1415. 'H2D Pro': 'H2D Pro',
  1416. 'H2C': 'H2C',
  1417. 'H2S': 'H2S',
  1418. };
  1419. return modelMap[ssdpModel] || ssdpModel;
  1420. }
  1421. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1422. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1423. // • User-defined friendly name (editable, protected by printers:update)
  1424. // • AMS serial number
  1425. // • AMS firmware version
  1426. export function AmsNameHoverCard({
  1427. ams,
  1428. printerId,
  1429. label,
  1430. amsLabels,
  1431. canEdit,
  1432. onSaved,
  1433. children,
  1434. }: {
  1435. ams: import('../api/client').AMSUnit;
  1436. printerId: number;
  1437. label: string; // auto-generated label, e.g. "AMS-A"
  1438. amsLabels?: Record<number, string>;
  1439. canEdit: boolean;
  1440. onSaved: () => void;
  1441. children: React.ReactNode;
  1442. }) {
  1443. const { t } = useTranslation();
  1444. const [isVisible, setIsVisible] = useState(false);
  1445. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1446. const [editValue, setEditValue] = useState('');
  1447. const [isSaving, setIsSaving] = useState(false);
  1448. const [saveError, setSaveError] = useState<string | null>(null);
  1449. const [isInputFocused, setIsInputFocused] = useState(false);
  1450. const triggerRef = useRef<HTMLDivElement>(null);
  1451. const cardRef = useRef<HTMLDivElement>(null);
  1452. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1453. useEffect(() => {
  1454. if (isVisible) {
  1455. setEditValue(amsLabels?.[ams.id] ?? '');
  1456. setSaveError(null);
  1457. requestAnimationFrame(() => {
  1458. if (triggerRef.current && cardRef.current) {
  1459. const rect = triggerRef.current.getBoundingClientRect();
  1460. const spaceAbove = rect.top - 56;
  1461. const spaceBelow = window.innerHeight - rect.bottom;
  1462. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1463. }
  1464. });
  1465. }
  1466. }, [isVisible, amsLabels, ams.id]);
  1467. const handleMouseEnter = () => {
  1468. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1469. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1470. };
  1471. const handleMouseLeave = () => {
  1472. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1473. if (!isInputFocused) {
  1474. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1475. }
  1476. };
  1477. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1478. const handleSave = async () => {
  1479. if (!canEdit) return;
  1480. setIsSaving(true);
  1481. setSaveError(null);
  1482. try {
  1483. const trimmed = editValue.trim();
  1484. if (trimmed) {
  1485. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1486. } else {
  1487. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1488. }
  1489. onSaved();
  1490. setIsVisible(false);
  1491. } catch (err) {
  1492. setSaveError(err instanceof Error ? err.message : String(err));
  1493. } finally {
  1494. setIsSaving(false);
  1495. }
  1496. };
  1497. const handleClear = async () => {
  1498. if (!canEdit) return;
  1499. setIsSaving(true);
  1500. setSaveError(null);
  1501. try {
  1502. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1503. onSaved();
  1504. setIsVisible(false);
  1505. } catch (err) {
  1506. setSaveError(err instanceof Error ? err.message : String(err));
  1507. } finally {
  1508. setIsSaving(false);
  1509. }
  1510. };
  1511. return (
  1512. <div
  1513. ref={triggerRef}
  1514. className="relative inline-block"
  1515. onMouseEnter={handleMouseEnter}
  1516. onMouseLeave={handleMouseLeave}
  1517. >
  1518. {children}
  1519. {isVisible && (
  1520. <div
  1521. ref={cardRef}
  1522. className={`
  1523. absolute left-0 z-50
  1524. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1525. animate-in fade-in-0 zoom-in-95 duration-150
  1526. `}
  1527. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1528. onMouseEnter={handleMouseEnter}
  1529. onMouseLeave={handleMouseLeave}
  1530. >
  1531. <div className="w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm p-2.5 space-y-2">
  1532. {/* AMS auto-label */}
  1533. <div className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1534. {/* Serial number */}
  1535. <div className="flex items-center justify-between gap-2">
  1536. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1537. {t('printers.amsPopup.serialNumber')}
  1538. </span>
  1539. <span className="text-[10px] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1540. </div>
  1541. {/* Firmware version */}
  1542. <div className="flex items-center justify-between gap-2">
  1543. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1544. {t('printers.amsPopup.firmwareVersion')}
  1545. </span>
  1546. <span className="text-[10px] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1547. </div>
  1548. {/* Friendly name editor */}
  1549. <div className="space-y-1">
  1550. <div className="flex items-center gap-2">
  1551. <span className="text-[10px] text-bambu-gray font-medium shrink-0">
  1552. {t('printers.amsPopup.friendlyName')}
  1553. </span>
  1554. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1555. </div>
  1556. <input
  1557. type="text"
  1558. value={editValue}
  1559. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1560. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1561. onFocus={() => setIsInputFocused(true)}
  1562. onBlur={() => {
  1563. setIsInputFocused(false);
  1564. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1565. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1566. }}
  1567. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1568. disabled={!canEdit}
  1569. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1570. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-xs text-white placeholder-bambu-gray/60 focus:outline-none focus:border-bambu-green disabled:opacity-50 disabled:cursor-not-allowed"
  1571. maxLength={100}
  1572. />
  1573. {canEdit && (
  1574. <div className="space-y-1">
  1575. {saveError && (
  1576. <p className="text-[10px] text-red-400 break-words">{saveError}</p>
  1577. )}
  1578. <div className="flex gap-1 justify-end">
  1579. <button
  1580. onClick={handleSave}
  1581. disabled={isSaving}
  1582. className="px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1583. >
  1584. {t('printers.amsPopup.save')}
  1585. </button>
  1586. {amsLabels?.[ams.id] && (
  1587. <button
  1588. onClick={handleClear}
  1589. disabled={isSaving}
  1590. className="px-2 py-0.5 text-[10px] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1591. >
  1592. {t('printers.amsPopup.clear')}
  1593. </button>
  1594. )}
  1595. </div>
  1596. </div>
  1597. )}
  1598. </div>
  1599. </div>
  1600. </div>
  1601. )}
  1602. </div>
  1603. );
  1604. }
  1605. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1606. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1607. const DRYING_PRESETS: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }> = {
  1608. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1609. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1610. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1611. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1612. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1613. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1614. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1615. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1616. };
  1617. function PrinterCard({
  1618. printer,
  1619. hideIfDisconnected,
  1620. maintenanceInfo,
  1621. viewMode = 'expanded',
  1622. cardSize = 2,
  1623. amsThresholds,
  1624. spoolmanEnabled = false,
  1625. linkedSpools,
  1626. spoolmanUrl,
  1627. spoolmanSyncMode,
  1628. onGetAssignment,
  1629. onUnassignSpool,
  1630. spoolmanSpools,
  1631. spoolmanSlotAssignments,
  1632. spoolmanLoading = false,
  1633. onUnassignSpoolmanSpool,
  1634. timeFormat = 'system',
  1635. cameraViewMode = 'window',
  1636. onOpenEmbeddedCamera,
  1637. checkPrinterFirmware = true,
  1638. dryingPresets = DRYING_PRESETS,
  1639. requirePlateClear = false,
  1640. selectionMode = false,
  1641. isSelected = false,
  1642. onToggleSelect,
  1643. onOpenCompactCard,
  1644. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1645. bedTempPresets = BED_TEMP_DEFAULTS,
  1646. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1647. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1648. }: {
  1649. printer: Printer;
  1650. hideIfDisconnected?: boolean;
  1651. maintenanceInfo?: PrinterMaintenanceInfo;
  1652. viewMode?: ViewMode;
  1653. cardSize?: number;
  1654. amsThresholds?: {
  1655. humidityGood: number;
  1656. humidityFair: number;
  1657. tempGood: number;
  1658. tempFair: number;
  1659. };
  1660. spoolmanEnabled?: boolean;
  1661. hasUnlinkedSpools?: boolean;
  1662. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1663. spoolmanUrl?: string | null;
  1664. spoolmanSyncMode?: string | null;
  1665. spoolAssignments?: SpoolAssignment[];
  1666. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1667. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1668. spoolmanSpools?: InventorySpool[];
  1669. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1670. spoolmanLoading?: boolean;
  1671. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1672. timeFormat?: 'system' | '12h' | '24h';
  1673. cameraViewMode?: 'window' | 'embedded';
  1674. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1675. checkPrinterFirmware?: boolean;
  1676. dryingPresets?: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }>;
  1677. requirePlateClear?: boolean;
  1678. selectionMode?: boolean;
  1679. isSelected?: boolean;
  1680. onToggleSelect?: (id: number) => void;
  1681. onOpenCompactCard?: (id: number) => void;
  1682. nozzleTempPresets?: readonly [number, number, number];
  1683. bedTempPresets?: readonly [number, number, number];
  1684. chamberTempPresets?: readonly [number, number, number];
  1685. fanSpeedPresets?: readonly [number, number, number];
  1686. }) {
  1687. const { t } = useTranslation();
  1688. const queryClient = useQueryClient();
  1689. const navigate = useNavigate();
  1690. const { showToast } = useToast();
  1691. const { hasPermission } = useAuth();
  1692. const [showMenu, setShowMenu] = useState(false);
  1693. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1694. const [deleteArchives, setDeleteArchives] = useState(true);
  1695. const [showEditModal, setShowEditModal] = useState(false);
  1696. const [showFileManager, setShowFileManager] = useState(false);
  1697. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1698. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1699. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1700. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1701. const [showHMSModal, setShowHMSModal] = useState(false);
  1702. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1703. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1704. const [showStopConfirm, setShowStopConfirm] = useState(false);
  1705. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  1706. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  1707. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  1708. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  1709. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  1710. const [bedJogStep, setBedJogStep] = useState<number>(10);
  1711. const [showNotHomedModal, setShowNotHomedModal] = useState<null | { distance: number }>(null);
  1712. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  1713. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  1714. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  1715. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  1716. const [showDiagnostic, setShowDiagnostic] = useState(false);
  1717. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  1718. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  1719. // AMS drying popover state: which AMS unit has the popover open
  1720. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  1721. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  1722. const [dryingFilament, setDryingFilament] = useState('PLA');
  1723. const [dryingTemp, setDryingTemp] = useState(50);
  1724. const [dryingDuration, setDryingDuration] = useState(4);
  1725. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  1726. const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
  1727. const [isDraggingFile, setIsDraggingFile] = useState(false);
  1728. const [isDropUploading, setIsDropUploading] = useState(false);
  1729. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  1730. const dragCounterRef = useRef(0);
  1731. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  1732. amsId: number;
  1733. amsLabel: string;
  1734. mode: 'humidity' | 'temperature';
  1735. } | null>(null);
  1736. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  1737. initialKind: HeaterSensorKind;
  1738. availableKinds: HeaterSensorKind[];
  1739. } | null>(null);
  1740. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  1741. tagUid: string;
  1742. trayUuid: string;
  1743. printerId: number;
  1744. amsId: number;
  1745. trayId: number;
  1746. } | null>(null);
  1747. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  1748. printerId: number;
  1749. amsId: number;
  1750. trayId: number;
  1751. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  1752. } | null>(null);
  1753. const [configureSlotModal, setConfigureSlotModal] = useState<{
  1754. amsId: number;
  1755. trayId: number;
  1756. trayCount: number;
  1757. trayType?: string;
  1758. trayColor?: string;
  1759. traySubBrands?: string;
  1760. trayInfoIdx?: string;
  1761. extruderId?: number;
  1762. caliIdx?: number | null;
  1763. savedPresetId?: string;
  1764. } | null>(null);
  1765. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  1766. const [plateCheckResult, setPlateCheckResult] = useState<{
  1767. is_empty: boolean;
  1768. confidence: number;
  1769. difference_percent: number;
  1770. message: string;
  1771. debug_image_url?: string;
  1772. needs_calibration: boolean;
  1773. light_warning?: boolean;
  1774. reference_count?: number;
  1775. max_references?: number;
  1776. roi?: { x: number; y: number; w: number; h: number };
  1777. } | null>(null);
  1778. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  1779. const [isCalibrating, setIsCalibrating] = useState(false);
  1780. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  1781. const [isSavingRoi, setIsSavingRoi] = useState(false);
  1782. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  1783. const { data: status } = useQuery({
  1784. queryKey: ['printerStatus', printer.id],
  1785. queryFn: () => api.getPrinterStatus(printer.id),
  1786. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  1787. });
  1788. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  1789. const { data: firmwareInfo } = useQuery({
  1790. queryKey: ['firmwareUpdate', printer.id],
  1791. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  1792. staleTime: 5 * 60 * 1000,
  1793. refetchInterval: 5 * 60 * 1000,
  1794. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  1795. });
  1796. // Collect unique tray_info_idx values for cloud filament info lookup
  1797. const trayInfoIds = useMemo(() => {
  1798. const ids = new Set<string>();
  1799. if (status?.ams) {
  1800. for (const ams of status.ams) {
  1801. for (const tray of ams.tray || []) {
  1802. if (tray.tray_info_idx) {
  1803. ids.add(tray.tray_info_idx);
  1804. }
  1805. }
  1806. }
  1807. }
  1808. for (const vt of status?.vt_tray ?? []) {
  1809. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  1810. }
  1811. if (status?.nozzle_rack) {
  1812. for (const slot of status.nozzle_rack) {
  1813. if (slot.filament_id) {
  1814. ids.add(slot.filament_id);
  1815. }
  1816. }
  1817. }
  1818. return Array.from(ids);
  1819. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  1820. // Collect loaded filament types for queue widget filtering
  1821. const loadedFilamentTypes = useMemo(() => {
  1822. const types = new Set<string>();
  1823. if (status?.ams) {
  1824. for (const ams of status.ams) {
  1825. for (const tray of ams.tray || []) {
  1826. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  1827. }
  1828. }
  1829. }
  1830. for (const vt of status?.vt_tray ?? []) {
  1831. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  1832. }
  1833. return types;
  1834. }, [status?.ams, status?.vt_tray]);
  1835. // Collect loaded filament type+color pairs for queue widget override matching
  1836. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  1837. const loadedFilaments = useMemo(() => {
  1838. const filaments = new Set<string>();
  1839. if (status?.ams) {
  1840. for (const ams of status.ams) {
  1841. for (const tray of ams.tray || []) {
  1842. if (tray.tray_type && tray.tray_color) {
  1843. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1844. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  1845. }
  1846. }
  1847. }
  1848. }
  1849. for (const vt of status?.vt_tray ?? []) {
  1850. if (vt.tray_type && vt.tray_color) {
  1851. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1852. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  1853. }
  1854. }
  1855. return filaments;
  1856. }, [status?.ams, status?.vt_tray]);
  1857. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  1858. const { data: filamentInfo } = useQuery({
  1859. queryKey: ['filamentInfo', trayInfoIds],
  1860. queryFn: () => api.getFilamentInfo(trayInfoIds),
  1861. enabled: trayInfoIds.length > 0,
  1862. staleTime: 5 * 60 * 1000, // 5 minutes
  1863. });
  1864. // Fetch slot preset mappings (stores preset name for user-configured slots)
  1865. const { data: slotPresets } = useQuery({
  1866. queryKey: ['slotPresets', printer.id],
  1867. queryFn: () => api.getSlotPresets(printer.id),
  1868. staleTime: 2 * 60 * 1000, // 2 minutes
  1869. });
  1870. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  1871. // Only queried when there's a running print backed by an archive; shared
  1872. // React Query cache with the Queue / Archives pages keeps it cheap.
  1873. const activeArchiveId =
  1874. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  1875. const { data: activeArchivePlates } = useQuery({
  1876. queryKey: ['archive-plates', activeArchiveId],
  1877. queryFn: () => api.getArchivePlates(activeArchiveId!),
  1878. enabled: activeArchiveId != null,
  1879. staleTime: 5 * 60 * 1000,
  1880. });
  1881. const activePlateLabel = (() => {
  1882. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  1883. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  1884. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  1885. })();
  1886. // Fetch user-defined AMS friendly names from the database
  1887. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  1888. queryKey: ['amsLabels', printer.id],
  1889. queryFn: () => api.getAmsLabels(printer.id),
  1890. staleTime: 5 * 60 * 1000, // 5 minutes
  1891. });
  1892. // Cache WiFi signal to prevent it disappearing on updates
  1893. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  1894. useEffect(() => {
  1895. if (status?.wifi_signal != null) {
  1896. setCachedWifiSignal(status.wifi_signal);
  1897. }
  1898. }, [status?.wifi_signal]);
  1899. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  1900. // Cache connected state to prevent flicker when status briefly becomes undefined
  1901. const cachedConnected = useRef<boolean | undefined>(undefined);
  1902. useEffect(() => {
  1903. if (status?.connected !== undefined) {
  1904. cachedConnected.current = status.connected;
  1905. }
  1906. }, [status?.connected]);
  1907. const isConnected = status?.connected ?? cachedConnected.current;
  1908. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  1909. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  1910. useEffect(() => {
  1911. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  1912. cachedAmsExtruderMap.current = status.ams_extruder_map;
  1913. }
  1914. }, [status?.ams_extruder_map]);
  1915. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  1916. ? status.ams_extruder_map
  1917. : cachedAmsExtruderMap.current;
  1918. // Cache AMS data to prevent it disappearing on idle/offline printers
  1919. const cachedAmsData = useRef<AMSUnit[]>([]);
  1920. useEffect(() => {
  1921. if (status?.ams && status.ams.length > 0) {
  1922. cachedAmsData.current = status.ams;
  1923. }
  1924. }, [status?.ams]);
  1925. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  1926. // Cache tray_now to prevent flickering when undefined values come in
  1927. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  1928. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  1929. const cachedTrayNow = useRef<number | undefined>(undefined);
  1930. const currentTrayNow = status?.tray_now;
  1931. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  1932. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  1933. cachedTrayNow.current = currentTrayNow;
  1934. } else if (currentTrayNow === 255) {
  1935. cachedTrayNow.current = undefined;
  1936. }
  1937. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  1938. ? currentTrayNow
  1939. : cachedTrayNow.current;
  1940. // Fetch smart plug for this printer
  1941. const { data: smartPlug } = useQuery({
  1942. queryKey: ['smartPlugByPrinter', printer.id],
  1943. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  1944. });
  1945. // Fetch script plugs for this printer (for multi-device control)
  1946. const { data: scriptPlugs } = useQuery({
  1947. queryKey: ['scriptPlugsByPrinter', printer.id],
  1948. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  1949. });
  1950. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  1951. const { data: plugStatus } = useQuery({
  1952. queryKey: ['smartPlugStatus', smartPlug?.id],
  1953. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  1954. enabled: !!smartPlug,
  1955. refetchInterval: 10000, // 10 seconds for real-time power display
  1956. });
  1957. // Fetch queue count for this printer
  1958. const { data: queueItems } = useQuery({
  1959. queryKey: ['queue', printer.id, 'pending'],
  1960. queryFn: () => api.getQueue(printer.id, 'pending'),
  1961. });
  1962. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  1963. // so the badge only shows on printers that can actually run the queued jobs.
  1964. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  1965. const queueCount = useMemo(() => {
  1966. if (!queueItems?.length) return 0;
  1967. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments).length;
  1968. }, [queueItems, loadedFilamentTypes, loadedFilaments]);
  1969. // Fetch currently printing queue item to show who started it (Issue #206)
  1970. const { data: printingQueueItems } = useQuery({
  1971. queryKey: ['queue', printer.id, 'printing'],
  1972. queryFn: () => api.getQueue(printer.id, 'printing'),
  1973. enabled: status?.state === 'RUNNING',
  1974. });
  1975. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  1976. const { data: reprintUser } = useQuery({
  1977. queryKey: ['currentPrintUser', printer.id],
  1978. queryFn: () => api.getCurrentPrintUser(printer.id),
  1979. enabled: status?.state === 'RUNNING',
  1980. });
  1981. // Combine both sources: queue item user takes precedence, then reprint user
  1982. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  1983. // Fetch last completed print for this printer
  1984. const { data: lastPrints } = useQuery({
  1985. queryKey: ['archives', printer.id, 'last'],
  1986. queryFn: () => api.getArchives(printer.id, 1, 0),
  1987. enabled: status?.connected && status?.state !== 'RUNNING',
  1988. });
  1989. const lastPrint = lastPrints?.[0];
  1990. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  1991. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  1992. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  1993. const activePrintName = status?.current_print && isPrintingOrPaused
  1994. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  1995. : null;
  1996. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  1997. useEffect(() => {
  1998. if (activePrintName) {
  1999. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2000. } else if (!needsPlateClear) {
  2001. setRetainedPrintJob(null);
  2002. }
  2003. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2004. const plateStatus = (() => {
  2005. if (!requirePlateClear || !status?.connected) return null;
  2006. if (isPrintingOrPaused) {
  2007. return {
  2008. label: t('printers.plateStatus.inUse'),
  2009. className: 'bg-blue-500/20 text-blue-400',
  2010. };
  2011. }
  2012. if (status.awaiting_plate_clear) {
  2013. return {
  2014. label: t('printers.plateStatus.notCleared'),
  2015. className: 'bg-yellow-500/20 text-yellow-400',
  2016. };
  2017. }
  2018. return {
  2019. label: t('printers.plateStatus.cleared'),
  2020. className: 'bg-status-ok/20 text-status-ok',
  2021. };
  2022. })();
  2023. const plateStatusPill = plateStatus ? (
  2024. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${plateStatus.className}`}>
  2025. {plateStatus.label}
  2026. </span>
  2027. ) : null;
  2028. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2029. const shouldHide = hideIfDisconnected && isConnected === false;
  2030. const deleteMutation = useMutation({
  2031. mutationFn: (options: { deleteArchives: boolean }) =>
  2032. api.deletePrinter(printer.id, options.deleteArchives),
  2033. onSuccess: () => {
  2034. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2035. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2036. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2037. },
  2038. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2039. });
  2040. const connectMutation = useMutation({
  2041. mutationFn: () => api.connectPrinter(printer.id),
  2042. onSuccess: () => {
  2043. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2044. },
  2045. });
  2046. const forceRefreshMutation = useMutation({
  2047. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2048. onSuccess: () => {
  2049. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2050. showToast(t('printers.forceRefreshSuccess'), 'success');
  2051. },
  2052. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2053. });
  2054. const unlinkSpoolMutation = useMutation({
  2055. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2056. onSuccess: (result) => {
  2057. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2058. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2059. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2060. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2061. },
  2062. onError: (error: Error) => {
  2063. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2064. },
  2065. });
  2066. // AMS drying mutations
  2067. const startDryingMutation = useMutation({
  2068. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2069. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2070. onSuccess: () => {
  2071. setDryingPopoverAmsId(null);
  2072. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2073. },
  2074. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2075. });
  2076. const stopDryingMutation = useMutation({
  2077. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2078. onSuccess: () => {
  2079. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2080. },
  2081. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2082. });
  2083. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2084. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2085. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2086. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2087. // showing the old backup state until the user reopens it.
  2088. const setAmsBackupMutation = useMutation({
  2089. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2090. onSuccess: (_data, enabled) => {
  2091. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2092. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2093. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2094. },
  2095. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2096. });
  2097. // Smart plug control mutations
  2098. const powerControlMutation = useMutation({
  2099. mutationFn: (action: 'on' | 'off') =>
  2100. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2101. onSuccess: () => {
  2102. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2103. },
  2104. });
  2105. const toggleAutoOffMutation = useMutation({
  2106. mutationFn: (enabled: boolean) =>
  2107. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2108. onSuccess: () => {
  2109. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2110. // Also invalidate the smart-plugs list to keep Settings page in sync
  2111. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2112. },
  2113. });
  2114. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2115. const runScriptMutation = useMutation({
  2116. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2117. onSuccess: () => {
  2118. showToast(t('printers.toast.scriptTriggered'));
  2119. },
  2120. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2121. });
  2122. // Print control mutations
  2123. const stopPrintMutation = useMutation({
  2124. mutationFn: () => api.stopPrint(printer.id),
  2125. onSuccess: () => {
  2126. showToast(t('printers.toast.printStopped'));
  2127. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2128. },
  2129. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2130. });
  2131. const pausePrintMutation = useMutation({
  2132. mutationFn: () => api.pausePrint(printer.id),
  2133. onSuccess: () => {
  2134. showToast(t('printers.toast.printPaused'));
  2135. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2136. },
  2137. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2138. });
  2139. const resumePrintMutation = useMutation({
  2140. mutationFn: () => api.resumePrint(printer.id),
  2141. onSuccess: () => {
  2142. showToast(t('printers.toast.printResumed'));
  2143. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2144. },
  2145. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2146. });
  2147. const clearPlateMutation = useMutation({
  2148. mutationFn: () => api.clearPlate(printer.id),
  2149. onSuccess: () => {
  2150. showToast(t('queue.clearPlateSuccess'));
  2151. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2152. old ? { ...old, awaiting_plate_clear: false } : old
  2153. );
  2154. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2155. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2156. },
  2157. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2158. });
  2159. const nozzleTemperatureMutation = useMutation({
  2160. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2161. api.setNozzleTemperature(printer.id, target, nozzle),
  2162. onSuccess: (result) => {
  2163. setStatusControlMenu(null);
  2164. showToast(result.message);
  2165. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2166. },
  2167. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2168. });
  2169. const bedTemperatureMutation = useMutation({
  2170. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2171. onSuccess: (result) => {
  2172. setStatusControlMenu(null);
  2173. showToast(result.message);
  2174. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2175. },
  2176. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2177. });
  2178. const chamberTemperatureMutation = useMutation({
  2179. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2180. onSuccess: (result) => {
  2181. setStatusControlMenu(null);
  2182. showToast(result.message);
  2183. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2184. },
  2185. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2186. });
  2187. const fanSpeedMutation = useMutation({
  2188. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'chamber'; speed: number }) =>
  2189. api.setFanSpeed(printer.id, fan, speed),
  2190. onMutate: async ({ fan, speed }) => {
  2191. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2192. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2193. const fanField = {
  2194. part: 'cooling_fan_speed',
  2195. aux: 'big_fan1_speed',
  2196. chamber: 'big_fan2_speed',
  2197. }[fan];
  2198. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2199. old ? { ...old, [fanField]: speed } : old
  2200. );
  2201. return { previousStatus };
  2202. },
  2203. onSuccess: (result) => {
  2204. setStatusControlMenu(null);
  2205. showToast(result.message);
  2206. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2207. },
  2208. onError: (error: Error, _variables, context) => {
  2209. if (context?.previousStatus) {
  2210. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2211. }
  2212. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2213. },
  2214. });
  2215. const selectExtruderMutation = useMutation({
  2216. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2217. onMutate: async (extruder) => {
  2218. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2219. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2220. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2221. old ? { ...old, active_extruder: extruder } : old
  2222. );
  2223. return { previousStatus };
  2224. },
  2225. onSuccess: (result) => {
  2226. setStatusControlMenu(null);
  2227. showToast(result.message);
  2228. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2229. },
  2230. onError: (error: Error, _extruder, context) => {
  2231. if (context?.previousStatus) {
  2232. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2233. }
  2234. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2235. },
  2236. });
  2237. // Chamber light mutation with optimistic update
  2238. const chamberLightMutation = useMutation({
  2239. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2240. onMutate: async (on) => {
  2241. // Cancel any outgoing refetches
  2242. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2243. // Snapshot the previous value
  2244. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2245. // Optimistically update
  2246. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2247. ...old,
  2248. chamber_light: on,
  2249. }));
  2250. return { previousStatus };
  2251. },
  2252. onSuccess: (_, on) => {
  2253. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2254. },
  2255. onError: (error: Error, _, context) => {
  2256. // Rollback on error
  2257. if (context?.previousStatus) {
  2258. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2259. }
  2260. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2261. },
  2262. });
  2263. // Print speed mutation with optimistic update
  2264. const printSpeedMutation = useMutation({
  2265. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2266. onMutate: async (mode) => {
  2267. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2268. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2269. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2270. ...old,
  2271. speed_level: mode,
  2272. }));
  2273. return { previousStatus };
  2274. },
  2275. onError: (error: Error, _, context) => {
  2276. if (context?.previousStatus) {
  2277. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2278. }
  2279. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2280. },
  2281. });
  2282. const airductMutation = useMutation({
  2283. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2284. onMutate: async (mode) => {
  2285. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2286. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2287. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2288. ...old,
  2289. airduct_mode: mode === 'cooling' ? 0 : 1,
  2290. }));
  2291. return { previousStatus };
  2292. },
  2293. onError: (error: Error, _, context) => {
  2294. if (context?.previousStatus) {
  2295. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2296. }
  2297. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2298. },
  2299. });
  2300. const bedJogMutation = useMutation({
  2301. mutationFn: ({ distance, force }: { distance: number; force?: boolean }) =>
  2302. api.bedJog(printer.id, distance, force ?? false),
  2303. onError: (error: Error) =>
  2304. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2305. });
  2306. const xyJogMutation = useMutation({
  2307. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2308. api.xyJog(printer.id, x, y),
  2309. onError: (error: Error) =>
  2310. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2311. });
  2312. const extruderJogMutation = useMutation({
  2313. mutationFn: (distance: number) =>
  2314. api.extruderJog(printer.id, distance),
  2315. onError: (error: Error) =>
  2316. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2317. });
  2318. const homeAxesMutation = useMutation({
  2319. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2320. onSuccess: () => {
  2321. // Flip the session-scoped "warned" flag so the next bed-jog click doesn't re-prompt
  2322. // the not-homed modal. The flag is the same one "Move anyway" sets; after a successful
  2323. // auto-home request the printer is (or will shortly be) in a known-homed state, so
  2324. // prompting again in the same session is noise — #1052 follow-up.
  2325. try { sessionStorage.setItem(`bambuddy.bedJog.warned.${printer.id}`, '1'); } catch { /* ignore */ }
  2326. showToast(t('printers.bedJog.homingStarted'));
  2327. },
  2328. onError: (error: Error) =>
  2329. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2330. });
  2331. // Plate detection setting mutation
  2332. const plateDetectionMutation = useMutation({
  2333. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2334. onSuccess: () => {
  2335. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2336. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2337. },
  2338. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2339. });
  2340. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2341. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2342. // metrics, and the print picker — so flipping this flag puts the printer
  2343. // out of service across every consumer in one place. Used from the
  2344. // overflow menu and EditPrinterModal.
  2345. const maintenanceMutation = useMutation({
  2346. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2347. onSuccess: (_data, isActive) => {
  2348. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2349. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2350. showToast(
  2351. isActive
  2352. ? t('printers.maintenance.toastExited', { name: printer.name })
  2353. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2354. 'success',
  2355. );
  2356. },
  2357. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2358. });
  2359. // Confirm before entering maintenance on a printing printer (entering mode
  2360. // disconnects MQTT, which stops progress tracking + completion notifications
  2361. // for the in-flight job).
  2362. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2363. const handleEnterMaintenance = () => {
  2364. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2365. setConfirmMaintenanceEnter(true);
  2366. } else {
  2367. maintenanceMutation.mutate(false);
  2368. }
  2369. };
  2370. // Query for printable objects (for skip functionality)
  2371. // Fetch when printing with 2+ objects OR when modal is open
  2372. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2373. const { data: objectsData } = useQuery({
  2374. queryKey: ['printableObjects', printer.id],
  2375. queryFn: () => api.getPrintableObjects(printer.id),
  2376. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2377. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2378. });
  2379. // State for tracking which AMS slot is being refreshed
  2380. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2381. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2382. const seenBusyStateRef = useRef<boolean>(false);
  2383. // Fallback timeout ref
  2384. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2385. // Minimum display time passed
  2386. const minTimePassedRef = useRef<boolean>(false);
  2387. // AMS slot refresh mutation
  2388. const refreshAmsSlotMutation = useMutation({
  2389. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2390. api.refreshAmsSlot(printer.id, amsId, slotId),
  2391. onMutate: ({ amsId, slotId }) => {
  2392. // Clear any existing timeout
  2393. if (refreshTimeoutRef.current) {
  2394. clearTimeout(refreshTimeoutRef.current);
  2395. }
  2396. // Reset state
  2397. seenBusyStateRef.current = false;
  2398. minTimePassedRef.current = false;
  2399. setRefreshingSlot({ amsId, slotId });
  2400. // Minimum display time (2 seconds)
  2401. setTimeout(() => {
  2402. minTimePassedRef.current = true;
  2403. }, 2000);
  2404. // Fallback timeout (30 seconds max)
  2405. refreshTimeoutRef.current = setTimeout(() => {
  2406. setRefreshingSlot(null);
  2407. }, 30000);
  2408. },
  2409. onSuccess: (data) => {
  2410. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2411. },
  2412. onError: (error: Error) => {
  2413. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2414. if (refreshTimeoutRef.current) {
  2415. clearTimeout(refreshTimeoutRef.current);
  2416. }
  2417. setRefreshingSlot(null);
  2418. },
  2419. });
  2420. // AMS load/unload mutations (#891)
  2421. const loadAmsTrayMutation = useMutation({
  2422. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2423. onSuccess: (data) => {
  2424. showToast(data.message || t('printers.toast.loadInitiated'));
  2425. },
  2426. onError: (error: Error) => {
  2427. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2428. },
  2429. });
  2430. const unloadAmsMutation = useMutation({
  2431. mutationFn: () => api.unloadAms(printer.id),
  2432. onSuccess: (data) => {
  2433. showToast(data.message || t('printers.toast.unloadInitiated'));
  2434. },
  2435. onError: (error: Error) => {
  2436. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2437. },
  2438. });
  2439. // Plate references state
  2440. const [plateReferences, setPlateReferences] = useState<{
  2441. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2442. max_references: number;
  2443. } | null>(null);
  2444. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2445. // Fetch plate references
  2446. const fetchPlateReferences = async () => {
  2447. try {
  2448. const data = await api.getPlateReferences(printer.id);
  2449. setPlateReferences(data);
  2450. } catch {
  2451. // Ignore errors - references will show as empty
  2452. }
  2453. };
  2454. // Toggle plate detection enabled/disabled
  2455. const handleTogglePlateDetection = () => {
  2456. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2457. };
  2458. // Open plate detection management modal (for calibration/references)
  2459. const handleOpenPlateManagement = async () => {
  2460. setIsCheckingPlate(true);
  2461. setPlateCheckResult(null);
  2462. // Auto-turn on light if it's off
  2463. const lightWasOff = status?.chamber_light === false;
  2464. setPlateCheckLightWasOff(lightWasOff);
  2465. if (lightWasOff) {
  2466. await api.setChamberLight(printer.id, true);
  2467. // Wait for light to physically turn on and camera to adjust exposure
  2468. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2469. await new Promise(resolve => setTimeout(resolve, 2500));
  2470. }
  2471. try {
  2472. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2473. setPlateCheckResult(result);
  2474. fetchPlateReferences();
  2475. } catch (error) {
  2476. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2477. // Restore light if check failed
  2478. if (lightWasOff) {
  2479. await api.setChamberLight(printer.id, false);
  2480. setPlateCheckLightWasOff(false);
  2481. }
  2482. } finally {
  2483. setIsCheckingPlate(false);
  2484. }
  2485. };
  2486. // Close plate check modal and restore light state
  2487. const closePlateCheckModal = useCallback(async () => {
  2488. setPlateCheckResult(null);
  2489. // Restore light to original state if we turned it on
  2490. if (plateCheckLightWasOff) {
  2491. await api.setChamberLight(printer.id, false);
  2492. setPlateCheckLightWasOff(false);
  2493. }
  2494. }, [plateCheckLightWasOff, printer.id]);
  2495. // Calibrate plate detection handler
  2496. const handleCalibratePlate = async (label?: string) => {
  2497. setIsCalibrating(true);
  2498. try {
  2499. const result = await api.calibratePlateDetection(printer.id, { label });
  2500. if (result.success) {
  2501. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2502. // Refresh references and re-check
  2503. fetchPlateReferences();
  2504. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2505. setPlateCheckResult(checkResult);
  2506. } else {
  2507. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2508. }
  2509. } catch (error) {
  2510. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2511. } finally {
  2512. setIsCalibrating(false);
  2513. }
  2514. };
  2515. // Update reference label
  2516. const handleUpdateRefLabel = async (index: number, label: string) => {
  2517. try {
  2518. await api.updatePlateReferenceLabel(printer.id, index, label);
  2519. setEditingRefLabel(null);
  2520. fetchPlateReferences();
  2521. } catch (error) {
  2522. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  2523. }
  2524. };
  2525. // Delete reference
  2526. const handleDeleteRef = async (index: number) => {
  2527. try {
  2528. await api.deletePlateReference(printer.id, index);
  2529. showToast(t('printers.toast.referenceDeleted'), 'success');
  2530. fetchPlateReferences();
  2531. // Re-check to update counts
  2532. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2533. setPlateCheckResult(checkResult);
  2534. } catch (error) {
  2535. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  2536. }
  2537. };
  2538. // Save ROI settings
  2539. const handleSaveRoi = async () => {
  2540. if (!editingRoi) return;
  2541. setIsSavingRoi(true);
  2542. try {
  2543. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  2544. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  2545. setEditingRoi(null);
  2546. // Re-check to see new ROI in action
  2547. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2548. setPlateCheckResult(checkResult);
  2549. } catch (error) {
  2550. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  2551. } finally {
  2552. setIsSavingRoi(false);
  2553. }
  2554. };
  2555. // Close plate check modal on Escape key
  2556. useEffect(() => {
  2557. const handleEscape = (e: KeyboardEvent) => {
  2558. if (e.key === 'Escape' && plateCheckResult) {
  2559. closePlateCheckModal();
  2560. }
  2561. };
  2562. window.addEventListener('keydown', handleEscape);
  2563. return () => window.removeEventListener('keydown', handleEscape);
  2564. }, [plateCheckResult, closePlateCheckModal]);
  2565. // Watch ams_status_main to detect when RFID read completes
  2566. // ams_status_main: 0=idle, 2=rfid_identifying
  2567. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2568. useEffect(() => {
  2569. if (!refreshingSlot) return;
  2570. const amsStatus = status?.ams_status_main ?? 0;
  2571. // Track when we see non-idle state (printer is working)
  2572. if (amsStatus !== 0) {
  2573. seenBusyStateRef.current = true;
  2574. // Cancel any deferred clear since we're back to busy
  2575. if (deferredClearRef.current) {
  2576. clearTimeout(deferredClearRef.current);
  2577. deferredClearRef.current = null;
  2578. }
  2579. }
  2580. // When we've seen busy and now idle, clear (with min time check)
  2581. if (seenBusyStateRef.current && amsStatus === 0) {
  2582. if (minTimePassedRef.current) {
  2583. // Min time passed - clear now
  2584. if (refreshTimeoutRef.current) {
  2585. clearTimeout(refreshTimeoutRef.current);
  2586. }
  2587. setRefreshingSlot(null);
  2588. } else {
  2589. // Schedule clear after min time (2 seconds from start)
  2590. if (!deferredClearRef.current) {
  2591. deferredClearRef.current = setTimeout(() => {
  2592. if (refreshTimeoutRef.current) {
  2593. clearTimeout(refreshTimeoutRef.current);
  2594. }
  2595. setRefreshingSlot(null);
  2596. }, 2000);
  2597. }
  2598. }
  2599. }
  2600. return () => {
  2601. if (deferredClearRef.current) {
  2602. clearTimeout(deferredClearRef.current);
  2603. }
  2604. };
  2605. }, [status?.ams_status_main, refreshingSlot]);
  2606. useEffect(() => {
  2607. if (!showMenu) return;
  2608. const handleClickOutside = (event: MouseEvent) => {
  2609. const target = event.target as Node;
  2610. if (!printerActionsMenuRef.current?.contains(target)) {
  2611. setShowMenu(false);
  2612. }
  2613. };
  2614. document.addEventListener('mousedown', handleClickOutside);
  2615. return () => document.removeEventListener('mousedown', handleClickOutside);
  2616. }, [showMenu]);
  2617. if (shouldHide) {
  2618. return null;
  2619. }
  2620. // Size-based styling helpers
  2621. const getImageSize = () => {
  2622. switch (cardSize) {
  2623. case 1: return 'w-10 h-10';
  2624. case 2: return 'w-14 h-14';
  2625. case 3: return 'w-16 h-16';
  2626. case 4: return 'w-20 h-20';
  2627. default: return 'w-14 h-14';
  2628. }
  2629. };
  2630. const getTitleSize = () => {
  2631. switch (cardSize) {
  2632. case 1: return 'text-base truncate';
  2633. case 2: return 'text-lg';
  2634. case 3: return 'text-xl';
  2635. case 4: return 'text-2xl';
  2636. default: return 'text-lg';
  2637. }
  2638. };
  2639. const getSpacing = () => {
  2640. switch (cardSize) {
  2641. case 1: return 'mb-2';
  2642. case 2: return 'mb-4';
  2643. case 3: return 'mb-5';
  2644. case 4: return 'mb-6';
  2645. default: return 'mb-4';
  2646. }
  2647. };
  2648. const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
  2649. const handleCardDragEnter = (e: React.DragEvent) => {
  2650. e.preventDefault();
  2651. dragCounterRef.current++;
  2652. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  2653. };
  2654. const handleCardDragOver = (e: React.DragEvent) => {
  2655. e.preventDefault();
  2656. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  2657. };
  2658. const handleCardDragLeave = (e: React.DragEvent) => {
  2659. e.preventDefault();
  2660. dragCounterRef.current--;
  2661. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  2662. };
  2663. const handleCardDrop = async (e: React.DragEvent) => {
  2664. e.preventDefault();
  2665. dragCounterRef.current = 0;
  2666. setIsDraggingFile(false);
  2667. if (!canDrop) return;
  2668. const droppedFiles = Array.from(e.dataTransfer.files);
  2669. const file = droppedFiles[0];
  2670. if (!file) return;
  2671. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  2672. const lower = file.name.toLowerCase();
  2673. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  2674. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  2675. return;
  2676. }
  2677. setIsDropUploading(true);
  2678. try {
  2679. const result = await api.uploadLibraryFile(file, null);
  2680. // Check printer compatibility if sliced_for_model is available in metadata
  2681. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  2682. const printerModel = mapModelCode(printer.model);
  2683. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  2684. await api.deleteLibraryFile(result.id).catch(() => {});
  2685. showToast(
  2686. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  2687. 'error'
  2688. );
  2689. return;
  2690. }
  2691. setPrintAfterUpload({ id: result.id, filename: result.filename });
  2692. } catch {
  2693. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  2694. } finally {
  2695. setIsDropUploading(false);
  2696. }
  2697. };
  2698. const handleCardClick = (e: React.MouseEvent) => {
  2699. if (viewMode !== 'compact' || selectionMode) return;
  2700. const target = e.target as HTMLElement;
  2701. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  2702. onOpenCompactCard?.(printer.id);
  2703. };
  2704. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  2705. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  2706. const renderAmsSlotActions = ({
  2707. amsId,
  2708. slotId,
  2709. loadTrayId,
  2710. isRefreshing,
  2711. includeRfid = true,
  2712. }: {
  2713. amsId: number;
  2714. slotId: number;
  2715. loadTrayId: number;
  2716. isRefreshing?: boolean;
  2717. includeRfid?: boolean;
  2718. }) => {
  2719. const printerBusy = status?.state === 'RUNNING';
  2720. return (
  2721. <>
  2722. {includeRfid && (
  2723. <button
  2724. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2725. hasPermission('printers:ams_rfid')
  2726. ? 'text-white hover:bg-bambu-dark-tertiary'
  2727. : 'text-bambu-gray/50 cursor-not-allowed'
  2728. }`}
  2729. onClick={(e) => {
  2730. e.stopPropagation();
  2731. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  2732. refreshAmsSlotMutation.mutate({ amsId, slotId });
  2733. }}
  2734. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  2735. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  2736. >
  2737. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  2738. {t('printers.rfid.reread')}
  2739. </button>
  2740. )}
  2741. <button
  2742. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2743. hasPermission('printers:control')
  2744. ? 'text-white hover:bg-bambu-dark-tertiary'
  2745. : 'text-bambu-gray/50 cursor-not-allowed'
  2746. }`}
  2747. onClick={(e) => {
  2748. e.stopPropagation();
  2749. if (printerBusy || !hasPermission('printers:control')) return;
  2750. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  2751. }}
  2752. disabled={printerBusy || !hasPermission('printers:control')}
  2753. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2754. >
  2755. <LogIn className="w-3 h-3" />
  2756. {t('printers.ams.load')}
  2757. </button>
  2758. <button
  2759. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2760. hasPermission('printers:control')
  2761. ? 'text-white hover:bg-bambu-dark-tertiary'
  2762. : 'text-bambu-gray/50 cursor-not-allowed'
  2763. }`}
  2764. onClick={(e) => {
  2765. e.stopPropagation();
  2766. if (printerBusy || !hasPermission('printers:control')) return;
  2767. unloadAmsMutation.mutate();
  2768. }}
  2769. disabled={printerBusy || !hasPermission('printers:control')}
  2770. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2771. >
  2772. <LogOut className="w-3 h-3" />
  2773. {t('printers.ams.unload')}
  2774. </button>
  2775. </>
  2776. );
  2777. };
  2778. const printerActionsMenu = (
  2779. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  2780. <Button
  2781. variant="secondary"
  2782. size="sm"
  2783. onClick={() => setShowMenu(!showMenu)}
  2784. title={t('common.more', 'More')}
  2785. className={footerIconButtonClass}
  2786. >
  2787. <MoreVertical className="w-4 h-4" />
  2788. </Button>
  2789. {showMenu && (
  2790. <div className="absolute left-0 bottom-full mb-2 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20">
  2791. <button
  2792. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2793. hasPermission('printers:update')
  2794. ? 'hover:bg-bambu-dark-tertiary'
  2795. : 'opacity-50 cursor-not-allowed'
  2796. }`}
  2797. onClick={() => {
  2798. if (!hasPermission('printers:update')) return;
  2799. setShowEditModal(true);
  2800. setShowMenu(false);
  2801. }}
  2802. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2803. >
  2804. <Pencil className="w-4 h-4" />
  2805. {t('common.edit')}
  2806. </button>
  2807. <button
  2808. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2809. onClick={() => {
  2810. setShowPrinterInfo(true);
  2811. setShowMenu(false);
  2812. }}
  2813. >
  2814. <Info className="w-4 h-4" />
  2815. {t('printers.printerInformation')}
  2816. </button>
  2817. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  2818. <button
  2819. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2820. hasPermission('printers:update')
  2821. ? 'hover:bg-bambu-dark-tertiary'
  2822. : 'opacity-50 cursor-not-allowed'
  2823. }`}
  2824. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  2825. onClick={() => {
  2826. if (!hasPermission('printers:update')) return;
  2827. setShowMenu(false);
  2828. if (printer.is_active !== false) {
  2829. handleEnterMaintenance();
  2830. } else {
  2831. maintenanceMutation.mutate(true);
  2832. }
  2833. }}
  2834. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2835. >
  2836. <Wrench className="w-4 h-4" />
  2837. {printer.is_active !== false
  2838. ? t('printers.maintenance.menuEnter')
  2839. : t('printers.maintenance.menuExit')}
  2840. </button>
  2841. <button
  2842. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2843. onClick={() => {
  2844. connectMutation.mutate();
  2845. setShowMenu(false);
  2846. }}
  2847. >
  2848. <RefreshCw className="w-4 h-4" />
  2849. {t('printers.reconnect')}
  2850. </button>
  2851. <button
  2852. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  2853. disabled={forceRefreshMutation.isPending}
  2854. onClick={() => {
  2855. forceRefreshMutation.mutate();
  2856. setShowMenu(false);
  2857. }}
  2858. >
  2859. <RotateCw className={`w-4 h-4 ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  2860. {t('printers.forceRefresh')}
  2861. </button>
  2862. <button
  2863. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2864. onClick={() => {
  2865. setShowMQTTDebug(true);
  2866. setShowMenu(false);
  2867. }}
  2868. >
  2869. <Terminal className="w-4 h-4" />
  2870. {t('printers.mqttDebug')}
  2871. </button>
  2872. <button
  2873. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2874. onClick={() => {
  2875. setShowDiagnostic(true);
  2876. setShowMenu(false);
  2877. }}
  2878. >
  2879. <Stethoscope className="w-4 h-4" />
  2880. {t('diagnostic.runButton')}
  2881. </button>
  2882. <button
  2883. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2884. hasPermission('printers:delete')
  2885. ? 'text-red-400 hover:bg-bambu-dark-tertiary'
  2886. : 'text-red-400/50 cursor-not-allowed'
  2887. }`}
  2888. onClick={() => {
  2889. if (!hasPermission('printers:delete')) return;
  2890. setShowDeleteConfirm(true);
  2891. setShowMenu(false);
  2892. }}
  2893. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  2894. >
  2895. <Trash2 className="w-4 h-4" />
  2896. {t('common.delete')}
  2897. </button>
  2898. </div>
  2899. )}
  2900. </div>
  2901. );
  2902. return (
  2903. <Card
  2904. id={`printer-card-${printer.id}`}
  2905. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  2906. onClick={handleCardClick}
  2907. onDragEnter={handleCardDragEnter}
  2908. onDragOver={handleCardDragOver}
  2909. onDragLeave={handleCardDragLeave}
  2910. onDrop={handleCardDrop}
  2911. >
  2912. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  2913. {selectionMode && (
  2914. <div
  2915. className="absolute inset-0 z-20 flex items-start p-2"
  2916. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  2917. >
  2918. {isSelected ? (
  2919. <CheckSquare className="w-5 h-5 text-bambu-green" />
  2920. ) : (
  2921. <Square className="w-5 h-5 text-bambu-gray" />
  2922. )}
  2923. </div>
  2924. )}
  2925. {/* Drop zone overlay */}
  2926. {(isDraggingFile || isDropUploading) && (
  2927. <div
  2928. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  2929. isDropUploading
  2930. ? 'bg-bambu-green/10 border-bambu-green/50'
  2931. : canDrop
  2932. ? 'bg-bambu-green/10 border-bambu-green'
  2933. : 'bg-red-500/10 border-red-500/50'
  2934. }`}
  2935. >
  2936. <div className="text-center">
  2937. {isDropUploading ? (
  2938. <>
  2939. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  2940. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  2941. </>
  2942. ) : canDrop ? (
  2943. <>
  2944. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  2945. <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
  2946. </>
  2947. ) : (
  2948. <>
  2949. <X className="w-8 h-8 mx-auto mb-2 text-red-400" />
  2950. <p className="text-sm font-medium text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
  2951. </>
  2952. )}
  2953. </div>
  2954. </div>
  2955. )}
  2956. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  2957. {/* Header */}
  2958. <div className={getSpacing()}>
  2959. {/* Top row: Image, Name, Menu */}
  2960. <div className="flex items-start justify-between gap-2">
  2961. <div className="flex items-center gap-3 min-w-0 flex-1">
  2962. {/* Printer Model Image */}
  2963. <img
  2964. src={getPrinterImage(printer.model)}
  2965. alt={printer.model || t('common.printer')}
  2966. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  2967. />
  2968. <div className="min-w-0 flex-1">
  2969. <div className="flex items-center justify-between gap-2">
  2970. <div className="flex min-w-0 items-center gap-2">
  2971. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  2972. {/* Connection indicator dot for compact mode */}
  2973. {viewMode === 'compact' && (() => {
  2974. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  2975. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  2976. const hasWarning = hmsErrors.length > 0;
  2977. const pipColor = !status?.connected
  2978. ? 'bg-status-error'
  2979. : hasSevere
  2980. ? 'bg-status-error'
  2981. : hasWarning
  2982. ? 'bg-status-warning'
  2983. : 'bg-status-ok';
  2984. const pipTitle = !status?.connected
  2985. ? t('printers.connection.offline')
  2986. : hasWarning
  2987. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  2988. : t('printers.connection.connected');
  2989. return (
  2990. <div
  2991. className={`w-2 h-2 rounded-full flex-shrink-0 ${pipColor}`}
  2992. title={pipTitle}
  2993. />
  2994. );
  2995. })()}
  2996. </div>
  2997. {viewMode === 'compact' && showClearPlateButton && (
  2998. <button
  2999. type="button"
  3000. onClick={() => clearPlateMutation.mutate()}
  3001. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3002. aria-label={t('printers.plateStatus.markCleared')}
  3003. className="inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-md bg-yellow-500/20 border border-yellow-400/40 text-yellow-400 hover:bg-yellow-500/30 transition-colors disabled:opacity-50"
  3004. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3005. >
  3006. {clearPlateMutation.isPending ? (
  3007. <Loader2 className="w-3 h-3 animate-spin" />
  3008. ) : (
  3009. <PlateClearedIcon className="w-3 h-3" />
  3010. )}
  3011. </button>
  3012. )}
  3013. </div>
  3014. <p className="text-sm text-bambu-gray">
  3015. {printer.model || 'Unknown Model'}
  3016. {/* Nozzle Info - only in expanded */}
  3017. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3018. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3019. • {status.nozzles[0].nozzle_diameter}mm
  3020. </span>
  3021. )}
  3022. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3023. <span className="ml-2 text-bambu-gray">
  3024. <Clock className="w-3 h-3 inline-block mr-1" />
  3025. {Math.round(maintenanceInfo.total_print_hours)}h
  3026. </span>
  3027. )}
  3028. </p>
  3029. </div>
  3030. </div>
  3031. </div>
  3032. {/* Badges row - only in expanded mode */}
  3033. {viewMode === 'expanded' && (
  3034. <div className="mt-2">
  3035. <div className="flex flex-wrap items-center gap-2">
  3036. {/* Connection status badge (or Maintenance pill when out of service).
  3037. Defensive: only swap when is_active is EXPLICITLY false. An
  3038. undefined / missing field defaults to "active" so the regular
  3039. pill renders — matches the backend default and prevents test
  3040. fixtures (or stale clients) from accidentally tripping the
  3041. maintenance UI. */}
  3042. {printer.is_active === false ? (
  3043. <span
  3044. className="flex items-center gap-1.5 px-2 py-1 rounded-full text-xs bg-amber-500/20 text-amber-400"
  3045. title={t('printers.maintenance.subtitle')}
  3046. >
  3047. <Wrench className="w-3 h-3" />
  3048. {t('printers.maintenance.pillLabel')}
  3049. </span>
  3050. ) : (
  3051. <span
  3052. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3053. status?.connected
  3054. ? 'bg-status-ok/20 text-status-ok'
  3055. : 'bg-status-error/20 text-status-error'
  3056. }`}
  3057. >
  3058. {status?.connected ? (
  3059. <Link className="w-3 h-3" />
  3060. ) : (
  3061. <Unlink className="w-3 h-3" />
  3062. )}
  3063. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3064. </span>
  3065. )}
  3066. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3067. {printer.is_active !== false && !status?.connected && (
  3068. <button
  3069. onClick={() => setShowDiagnostic(true)}
  3070. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors"
  3071. title={t('diagnostic.runButton')}
  3072. >
  3073. <Stethoscope className="w-3 h-3" />
  3074. {t('diagnostic.runButton')}
  3075. </button>
  3076. )}
  3077. {/* Network connection indicator */}
  3078. {status?.connected && status?.wired_network && (
  3079. <span
  3080. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3081. title={t('printers.connection.ethernet', 'Ethernet')}
  3082. >
  3083. <Cable className="w-3 h-3" />
  3084. {t('printers.connection.ethernet', 'Ethernet')}
  3085. </span>
  3086. )}
  3087. {/* WiFi signal indicator */}
  3088. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3089. <span
  3090. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3091. wifiSignal >= -50
  3092. ? 'bg-status-ok/20 text-status-ok'
  3093. : wifiSignal >= -60
  3094. ? 'bg-status-ok/20 text-status-ok'
  3095. : wifiSignal >= -70
  3096. ? 'bg-status-warning/20 text-status-warning'
  3097. : wifiSignal >= -80
  3098. ? 'bg-orange-500/20 text-orange-600'
  3099. : 'bg-status-error/20 text-status-error'
  3100. }`}
  3101. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3102. >
  3103. <Signal className="w-3 h-3" />
  3104. {wifiSignal}dBm
  3105. </span>
  3106. )}
  3107. {/* HMS Status Indicator */}
  3108. {status?.connected && (() => {
  3109. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3110. return (
  3111. <button
  3112. onClick={() => setShowHMSModal(true)}
  3113. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3114. knownErrors.length > 0
  3115. ? knownErrors.some(e => e.severity <= 2)
  3116. ? 'bg-status-error/20 text-status-error'
  3117. : 'bg-status-warning/20 text-status-warning'
  3118. : 'bg-status-ok/20 text-status-ok'
  3119. }`}
  3120. title={t('printers.clickToViewHmsErrors')}
  3121. >
  3122. <AlertTriangle className="w-3 h-3" />
  3123. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3124. </button>
  3125. );
  3126. })()}
  3127. {/* Maintenance Status Indicator */}
  3128. {maintenanceInfo && (
  3129. <button
  3130. onClick={() => navigate('/maintenance')}
  3131. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3132. maintenanceInfo.due_count > 0
  3133. ? 'bg-status-error/20 text-status-error'
  3134. : maintenanceInfo.warning_count > 0
  3135. ? 'bg-status-warning/20 text-status-warning'
  3136. : 'bg-status-ok/20 text-status-ok'
  3137. }`}
  3138. title={
  3139. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3140. ? `${maintenanceInfo.due_count > 0 ? `${maintenanceInfo.due_count} maintenance due` : ''}${maintenanceInfo.due_count > 0 && maintenanceInfo.warning_count > 0 ? ', ' : ''}${maintenanceInfo.warning_count > 0 ? `${maintenanceInfo.warning_count} due soon` : ''} - Click to view`
  3141. : t('printers.maintenanceUpToDate')
  3142. }
  3143. >
  3144. <Wrench className="w-3 h-3" />
  3145. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3146. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3147. : 'OK'}
  3148. </button>
  3149. )}
  3150. {/* Queue Count Badge */}
  3151. {queueCount > 0 && (
  3152. <button
  3153. onClick={() => navigate('/queue')}
  3154. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-indigo-500/20 text-indigo-400 hover:opacity-80 transition-opacity"
  3155. title={t('printers.queue.inQueue', { count: queueCount })}
  3156. >
  3157. <Layers className="w-3 h-3" />
  3158. {queueCount}
  3159. </button>
  3160. )}
  3161. {/* Firmware Version Badge */}
  3162. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3163. <button
  3164. onClick={() => setShowFirmwareModal(true)}
  3165. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3166. firmwareInfo.update_available
  3167. ? 'bg-orange-500/20 text-orange-400'
  3168. : 'bg-status-ok/20 text-status-ok'
  3169. }`}
  3170. title={
  3171. firmwareInfo.update_available
  3172. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3173. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3174. }
  3175. >
  3176. {firmwareInfo.update_available ? <Download className="w-3 h-3" /> : <CheckCircle className="w-3 h-3" />}
  3177. {firmwareInfo.current_version}
  3178. </button>
  3179. ) : status?.firmware_version ? (
  3180. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3181. {status.firmware_version}
  3182. </span>
  3183. ) : null}
  3184. {/* Enclosure Door Badge (X1/X2D/P1S/P2S/H2*) */}
  3185. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P1S', 'P1P', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3186. <span
  3187. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3188. status.door_open
  3189. ? 'bg-yellow-500/20 text-yellow-400'
  3190. : 'bg-status-ok/20 text-status-ok'
  3191. }`}
  3192. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3193. >
  3194. {status.door_open ? <DoorOpen className="w-3 h-3" /> : <DoorClosed className="w-3 h-3" />}
  3195. </span>
  3196. )}
  3197. </div>
  3198. </div>
  3199. )}
  3200. </div>
  3201. {/* Delete Confirmation */}
  3202. {showDeleteConfirm && (
  3203. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3204. <Card className="w-full max-w-md mx-4">
  3205. <CardContent>
  3206. <div className="flex items-start gap-3 mb-4">
  3207. <div className="p-2 rounded-full bg-red-500/20">
  3208. <AlertTriangle className="w-5 h-5 text-red-400" />
  3209. </div>
  3210. <div>
  3211. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3212. <p className="text-sm text-bambu-gray mt-1">
  3213. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3214. </p>
  3215. </div>
  3216. </div>
  3217. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3218. <label className="flex items-start gap-3 cursor-pointer">
  3219. <input
  3220. type="checkbox"
  3221. checked={deleteArchives}
  3222. onChange={(e) => setDeleteArchives(e.target.checked)}
  3223. className="mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  3224. />
  3225. <div>
  3226. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3227. <p className="text-xs text-bambu-gray mt-0.5">
  3228. {deleteArchives
  3229. ? t('printers.confirm.deleteArchivesNote')
  3230. : t('printers.confirm.keepArchivesNote')}
  3231. </p>
  3232. </div>
  3233. </label>
  3234. </div>
  3235. <div className="flex justify-end gap-2">
  3236. <Button
  3237. variant="secondary"
  3238. onClick={() => {
  3239. setShowDeleteConfirm(false);
  3240. setDeleteArchives(true);
  3241. }}
  3242. >
  3243. {t('common.cancel')}
  3244. </Button>
  3245. <Button
  3246. variant="danger"
  3247. onClick={() => {
  3248. deleteMutation.mutate({ deleteArchives });
  3249. setShowDeleteConfirm(false);
  3250. setDeleteArchives(true);
  3251. }}
  3252. >
  3253. Delete
  3254. </Button>
  3255. </div>
  3256. </CardContent>
  3257. </Card>
  3258. </div>
  3259. )}
  3260. {/* Status — see the equivalent defensive `=== false` check on the
  3261. header pill above for why this is not `!printer.is_active`. */}
  3262. {printer.is_active === false ? (
  3263. // Maintenance mode (#1476) — replaces the cover/progress container
  3264. // so the card keeps the same height. Renders for both compact and
  3265. // expanded view modes so the printer stays visible but plainly
  3266. // out-of-service.
  3267. <>
  3268. {viewMode === 'compact' ? (
  3269. <div className="mt-2 flex items-center gap-2 px-2 py-1.5 rounded-full bg-amber-500/15 border border-amber-500/30">
  3270. <Wrench className="w-3 h-3 text-amber-400 shrink-0" />
  3271. <span className="text-[11px] text-amber-400 font-medium truncate">
  3272. {t('printers.maintenance.pillLabel')}
  3273. </span>
  3274. </div>
  3275. ) : (
  3276. <>
  3277. <div className="flex items-center gap-2 mb-2">
  3278. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3279. {t('printers.status.title', 'Status')}
  3280. </span>
  3281. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3282. </div>
  3283. <div className="p-3 bg-amber-500/10 border border-amber-500/30 rounded-[10px] flex items-center gap-3">
  3284. <Wrench className="w-6 h-6 text-amber-400 shrink-0" />
  3285. <div className="flex-1 min-w-0">
  3286. <p className="text-sm text-amber-400 font-medium">
  3287. {t('printers.maintenance.title')}
  3288. </p>
  3289. <p className="text-xs text-bambu-gray mt-0.5">
  3290. {t('printers.maintenance.subtitle')}
  3291. </p>
  3292. </div>
  3293. <Button
  3294. variant="secondary"
  3295. size="sm"
  3296. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3297. onClick={() => maintenanceMutation.mutate(true)}
  3298. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3299. >
  3300. {t('printers.maintenance.exitButton')}
  3301. </Button>
  3302. </div>
  3303. </>
  3304. )}
  3305. </>
  3306. ) : status?.connected && (
  3307. <>
  3308. {/* Compact: Simple status bar */}
  3309. {viewMode === 'compact' ? (
  3310. (() => {
  3311. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3312. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3313. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3314. ? Math.max(0, Math.min(100, status.progress || 0))
  3315. : showClearPlateButton
  3316. ? 100
  3317. : hasProblem
  3318. ? 100
  3319. : 0;
  3320. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3321. const compactProgressClass = hasProblem
  3322. ? 'bg-status-error'
  3323. : status.state === 'PAUSE'
  3324. ? 'bg-status-warning'
  3325. : 'bg-bambu-green';
  3326. return (
  3327. <div className="relative mt-2 flex items-center gap-2">
  3328. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3329. <div
  3330. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3331. style={{ width: `${compactProgress}%` }}
  3332. />
  3333. </div>
  3334. <span className={`w-9 shrink-0 text-right text-[11px] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3335. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3336. </span>
  3337. </div>
  3338. );
  3339. })()
  3340. ) : (
  3341. /* Expanded: Full status section */
  3342. <>
  3343. <div className="flex items-center gap-2 mb-2">
  3344. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3345. {t('printers.status.title', 'Status')}
  3346. </span>
  3347. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3348. </div>
  3349. {/* Current Print or Idle Placeholder */}
  3350. {(() => {
  3351. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3352. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3353. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3354. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3355. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3356. return (
  3357. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3358. <button
  3359. onClick={() => setShowSkipObjectsModal(true)}
  3360. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3361. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3362. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3363. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3364. : 'text-bambu-gray/30 cursor-not-allowed'
  3365. }`}
  3366. title={
  3367. !hasPermission('printers:control')
  3368. ? t('printers.permission.noControl')
  3369. : !isActivePrint
  3370. ? t('printers.skipObjects.onlyWhilePrinting')
  3371. : (status.printable_objects_count ?? 0) >= 2
  3372. ? t('printers.skipObjects.tooltip')
  3373. : t('printers.skipObjects.requiresMultiple')
  3374. }
  3375. >
  3376. <SkipObjectsIcon className="w-4 h-4" />
  3377. {objectsData && objectsData.skipped_count > 0 && (
  3378. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full">
  3379. {objectsData.skipped_count}
  3380. </span>
  3381. )}
  3382. </button>
  3383. <div className="flex items-stretch gap-2">
  3384. <CoverImage
  3385. url={coverUrl}
  3386. printName={printName || undefined}
  3387. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  3388. />
  3389. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  3390. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  3391. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  3392. {plateStatusPill}
  3393. </div>
  3394. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  3395. {printName || t('printers.noActiveJob', 'No active job')}
  3396. </p>
  3397. <div className="flex h-3 items-center gap-2 text-sm">
  3398. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  3399. <div
  3400. className={`${isActivePrint ? (status.state === 'PAUSE' ? 'bg-status-warning' : 'bg-bambu-green') : showRetainedPrint ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'} h-1.5 rounded-full transition-all`}
  3401. style={{ width: `${progress}%` }}
  3402. />
  3403. </div>
  3404. <span className={`w-9 shrink-0 pr-1 text-right text-[11px] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  3405. </div>
  3406. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  3407. {isActivePrint ? (
  3408. <>
  3409. {status.remaining_time != null && status.remaining_time > 0 && (
  3410. <>
  3411. <span className="flex items-center gap-1">
  3412. <Clock className="w-3 h-3" />
  3413. {formatDuration(status.remaining_time * 60)}
  3414. </span>
  3415. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  3416. ETA {formatETA(status.remaining_time, timeFormat, t)}
  3417. </span>
  3418. </>
  3419. )}
  3420. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  3421. <span className="flex items-center gap-1">
  3422. <Layers className="w-3 h-3" />
  3423. {status.layer_num}/{status.total_layers}
  3424. </span>
  3425. )}
  3426. {currentPrintUser && (
  3427. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  3428. <User className="w-3 h-3" />
  3429. {currentPrintUser}
  3430. </span>
  3431. )}
  3432. </>
  3433. ) : lastPrint ? (
  3434. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  3435. Last: {lastPrint.print_name || lastPrint.filename}
  3436. {lastPrint.completed_at && (
  3437. <span className="ml-1 text-bambu-gray/60">
  3438. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  3439. </span>
  3440. )}
  3441. </p>
  3442. ) : (
  3443. <span>{t('printers.readyToPrint')}</span>
  3444. )}
  3445. </div>
  3446. </div>
  3447. </div>
  3448. <PrinterQueueWidget
  3449. printerId={printer.id}
  3450. printerModel={printer.model}
  3451. loadedFilamentTypes={loadedFilamentTypes}
  3452. loadedFilaments={loadedFilaments}
  3453. variant="panelExtension"
  3454. />
  3455. </div>
  3456. );
  3457. })()}
  3458. </>
  3459. )}
  3460. {/* Temperatures */}
  3461. {status.temperatures && viewMode === 'expanded' && (() => {
  3462. // Use actual heater states from MQTT stream
  3463. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  3464. const bedHeating = status.temperatures.bed_heating || false;
  3465. const chamberHeating = status.temperatures.chamber_heating || false;
  3466. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  3467. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  3468. const kinds: HeaterSensorKind[] = ['nozzle'];
  3469. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  3470. kinds.push('bed');
  3471. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  3472. return kinds;
  3473. })();
  3474. // active_extruder: 0=right, 1=left
  3475. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  3476. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  3477. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  3478. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  3479. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  3480. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  3481. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  3482. const canUseStatusControls = status.connected && hasPermission('printers:control');
  3483. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  3484. const statusControlClass = `relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center transition-colors ${
  3485. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3486. }`;
  3487. // Chamber fan only exists on enclosed Bambu models. Open-frame
  3488. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  3489. // the widget there is at best dead UI and at worst suggests a
  3490. // control that does nothing. Mirrors the enclosure-door badge
  3491. // gate above.
  3492. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  3493. const fanItems = [
  3494. {
  3495. key: 'part',
  3496. label: t('printers.fans.partCooling'),
  3497. value: status.cooling_fan_speed ?? 0,
  3498. Icon: Fan,
  3499. activeClass: 'text-cyan-400',
  3500. },
  3501. {
  3502. key: 'aux',
  3503. label: t('printers.fans.auxiliary'),
  3504. value: status.big_fan1_speed ?? 0,
  3505. Icon: Wind,
  3506. activeClass: 'text-blue-400',
  3507. },
  3508. ...(hasChamberFan
  3509. ? [
  3510. {
  3511. key: 'chamber',
  3512. label: t('printers.fans.chamber'),
  3513. value: status.big_fan2_speed ?? 0,
  3514. Icon: AirVent,
  3515. activeClass: 'text-green-400',
  3516. },
  3517. ]
  3518. : []),
  3519. ];
  3520. return (
  3521. <>
  3522. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  3523. {/* Nozzle temp - combined for dual nozzle */}
  3524. <div
  3525. className={statusControlClass}
  3526. title={statusControlTitle}
  3527. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  3528. >
  3529. <button
  3530. type="button"
  3531. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3532. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3533. onClick={(e) => {
  3534. e.stopPropagation();
  3535. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  3536. }}
  3537. >
  3538. <LineChartIcon className="w-2.5 h-2.5" />
  3539. </button>
  3540. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  3541. {status.temperatures.nozzle_2 !== undefined ? (
  3542. <>
  3543. <p className="text-[9px] text-bambu-gray">L / R</p>
  3544. <p className="text-[11px] text-white">
  3545. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  3546. </p>
  3547. </>
  3548. ) : singleNozzleSlot ? (
  3549. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  3550. <div className="cursor-default">
  3551. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3552. <p className="text-[11px] text-white">
  3553. {Math.round(status.temperatures.nozzle || 0)}°C
  3554. </p>
  3555. </div>
  3556. </NozzleSlotHoverCard>
  3557. ) : (
  3558. <>
  3559. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3560. <p className="text-[11px] text-white">
  3561. {Math.round(status.temperatures.nozzle || 0)}°C
  3562. </p>
  3563. </>
  3564. )}
  3565. {statusControlMenu === 'nozzle-temp' && (
  3566. isDualNozzle ? (
  3567. <IndicatorControlPopover
  3568. title="Set Nozzle Temperatures"
  3569. widthClass="w-[300px]"
  3570. popoverWidth={300}
  3571. popoverHeight={260}
  3572. isPending={nozzleTemperatureMutation.isPending}
  3573. onClose={() => setStatusControlMenu(null)}
  3574. >
  3575. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  3576. <NozzleTemperatureControlBox
  3577. label="Left Temp"
  3578. current={status.temperatures.nozzle}
  3579. target={status.temperatures.nozzle_target}
  3580. isActive={activeNozzle === 'L'}
  3581. isPending={nozzleTemperatureMutation.isPending}
  3582. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  3583. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3584. />
  3585. <NozzleTemperatureControlBox
  3586. label="Right Temp"
  3587. current={status.temperatures.nozzle_2}
  3588. target={status.temperatures.nozzle_2_target}
  3589. isActive={activeNozzle === 'R'}
  3590. isPending={nozzleTemperatureMutation.isPending}
  3591. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  3592. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3593. />
  3594. </div>
  3595. </IndicatorControlPopover>
  3596. ) : (
  3597. <IndicatorControlPopover
  3598. title="Set Nozzle Temperature"
  3599. unit="°C"
  3600. customMin={0}
  3601. customMax={320}
  3602. isPending={nozzleTemperatureMutation.isPending}
  3603. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3604. onClose={() => setStatusControlMenu(null)}
  3605. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  3606. />
  3607. )
  3608. )}
  3609. </div>
  3610. <div
  3611. className={statusControlClass}
  3612. title={statusControlTitle}
  3613. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  3614. >
  3615. <button
  3616. type="button"
  3617. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3618. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3619. onClick={(e) => {
  3620. e.stopPropagation();
  3621. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  3622. }}
  3623. >
  3624. <LineChartIcon className="w-2.5 h-2.5" />
  3625. </button>
  3626. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  3627. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  3628. <p className="text-[11px] text-white">
  3629. {Math.round(status.temperatures.bed || 0)}°C
  3630. </p>
  3631. {statusControlMenu === 'bed-temp' && (
  3632. <IndicatorControlPopover
  3633. title="Set Bed Temperature"
  3634. unit="°C"
  3635. customMin={0}
  3636. customMax={140}
  3637. isPending={bedTemperatureMutation.isPending}
  3638. options={buildPresetOptions(bedTempPresets, 'C')}
  3639. onClose={() => setStatusControlMenu(null)}
  3640. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  3641. />
  3642. )}
  3643. </div>
  3644. {status.temperatures.chamber !== undefined && (() => {
  3645. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  3646. // but can't act on M141, so we keep the card read-only there.
  3647. const hasChamberHeater = status.supports_chamber_heater === true;
  3648. return (
  3649. <div
  3650. className={hasChamberHeater
  3651. ? statusControlClass
  3652. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  3653. title={hasChamberHeater ? statusControlTitle : undefined}
  3654. onClick={hasChamberHeater
  3655. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  3656. : undefined}
  3657. >
  3658. <button
  3659. type="button"
  3660. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3661. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3662. onClick={(e) => {
  3663. e.stopPropagation();
  3664. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  3665. }}
  3666. >
  3667. <LineChartIcon className="w-2.5 h-2.5" />
  3668. </button>
  3669. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  3670. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  3671. <p className="text-[11px] text-white">
  3672. {Math.round(status.temperatures.chamber || 0)}°C
  3673. </p>
  3674. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  3675. <IndicatorControlPopover
  3676. title="Set Chamber Temperature"
  3677. unit="°C"
  3678. customMin={0}
  3679. customMax={60}
  3680. isPending={chamberTemperatureMutation.isPending}
  3681. options={buildPresetOptions(chamberTempPresets, 'C')}
  3682. onClose={() => setStatusControlMenu(null)}
  3683. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  3684. />
  3685. )}
  3686. </div>
  3687. );
  3688. })()}
  3689. {/* Active nozzle indicator for dual-nozzle printers */}
  3690. {isDualNozzle && (
  3691. <DualNozzleHoverCard
  3692. leftSlot={leftNozzleSlot}
  3693. rightSlot={rightNozzleSlot}
  3694. activeNozzle={activeNozzle}
  3695. filamentInfo={filamentInfo}
  3696. >
  3697. <div
  3698. className={`relative text-center px-3 py-1.5 bg-bambu-dark rounded-lg h-full flex flex-col justify-center items-center transition-colors ${
  3699. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3700. }`}
  3701. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  3702. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  3703. >
  3704. <NozzleIcon className="w-3.5 h-3.5 mb-0.5 text-amber-400" />
  3705. <div className="flex items-center gap-2">
  3706. <span className={`text-[11px] font-bold ${activeNozzle === 'L' ? 'text-amber-400' : 'text-gray-500'}`}>
  3707. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  3708. </span>
  3709. <span className="text-[9px] text-bambu-gray/40">·</span>
  3710. <span className={`text-[11px] font-bold ${activeNozzle === 'R' ? 'text-amber-400' : 'text-gray-500'}`}>
  3711. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  3712. </span>
  3713. </div>
  3714. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3715. {statusControlMenu === 'nozzle-select' && (
  3716. <IndicatorControlPopover
  3717. title="Set Nozzle Selection"
  3718. widthClass="w-[300px]"
  3719. popoverWidth={300}
  3720. popoverHeight={140}
  3721. isPending={selectExtruderMutation.isPending}
  3722. options={[
  3723. { label: 'Left', value: 1 },
  3724. { label: 'Right', value: 0 },
  3725. ]}
  3726. onClose={() => setStatusControlMenu(null)}
  3727. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  3728. />
  3729. )}
  3730. </div>
  3731. </DualNozzleHoverCard>
  3732. )}
  3733. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  3734. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  3735. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  3736. )}
  3737. </div>
  3738. <div className="mt-2 flex items-center gap-1.5">
  3739. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  3740. const active = value > 0;
  3741. return (
  3742. <div
  3743. key={key}
  3744. className={`relative px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 min-w-0 flex items-center justify-center gap-1 transition-colors ${
  3745. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3746. }`}
  3747. title={canUseStatusControls ? label : statusControlTitle}
  3748. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  3749. >
  3750. <Icon className={`w-3 h-3 shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  3751. <span className={`text-[10px] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  3752. {value}%
  3753. </span>
  3754. {statusControlMenu === `fan-${key}` && (
  3755. <IndicatorControlPopover
  3756. title={`Set ${label} Speed`}
  3757. unit="%"
  3758. customMin={0}
  3759. customMax={100}
  3760. isPending={fanSpeedMutation.isPending}
  3761. options={buildPresetOptions(fanSpeedPresets, '%')}
  3762. onClose={() => setStatusControlMenu(null)}
  3763. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'chamber', speed })}
  3764. />
  3765. )}
  3766. </div>
  3767. );
  3768. })}
  3769. </div>
  3770. </>
  3771. );
  3772. })()}
  3773. {viewMode === 'expanded' && showClearPlateButton && (
  3774. <button
  3775. type="button"
  3776. onClick={() => clearPlateMutation.mutate()}
  3777. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3778. className="mt-2 w-full inline-flex items-center justify-center gap-2 px-3 py-1.5 rounded-lg bg-yellow-500/20 border border-yellow-400/40 text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs font-medium disabled:opacity-50"
  3779. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3780. >
  3781. {clearPlateMutation.isPending ? (
  3782. <Loader2 className="w-3 h-3 animate-spin" />
  3783. ) : (
  3784. <PlateClearedIcon className="w-4 h-4" />
  3785. )}
  3786. {t('printers.plateStatus.markCleared')}
  3787. </button>
  3788. )}
  3789. {/* Controls */}
  3790. {viewMode === 'expanded' && (() => {
  3791. // Determine print state for control buttons
  3792. const isRunning = status.state === 'RUNNING';
  3793. const isPaused = status.state === 'PAUSE';
  3794. const isPrinting = isRunning || isPaused;
  3795. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  3796. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  3797. const iconControlClass = 'flex h-8 w-8 items-center justify-center rounded-lg text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
  3798. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  3799. return (
  3800. <div className="mt-3">
  3801. {/* Section Header */}
  3802. <div className="flex items-center gap-2 mb-2">
  3803. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3804. {t('printers.controls')}
  3805. </span>
  3806. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3807. </div>
  3808. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  3809. {/* Left: Secondary controls */}
  3810. <div className="flex flex-wrap items-center gap-2 min-w-0">
  3811. <button
  3812. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  3813. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  3814. className={`${iconControlClass} ${
  3815. status.chamber_light
  3816. ? 'bg-yellow-500/10 text-yellow-400 hover:bg-yellow-500/20'
  3817. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  3818. }`}
  3819. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  3820. >
  3821. <ChamberLight on={status.chamber_light ?? false} className="w-4 h-4" />
  3822. </button>
  3823. {/* Airduct Mode (P2S / X2D / H2*) */}
  3824. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  3825. const isHeating = status.airduct_mode === 1;
  3826. const Icon = isHeating ? Flame : Snowflake;
  3827. const color = isHeating ? 'text-orange-400' : 'text-sky-400';
  3828. const bg = isHeating ? 'bg-orange-500/10 text-orange-400 hover:bg-orange-500/20' : 'bg-sky-500/10 text-sky-400 hover:bg-sky-500/20';
  3829. return (
  3830. <div className="relative">
  3831. <button
  3832. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  3833. disabled={!hasPermission('printers:control')}
  3834. className={`${iconControlClass} ${bg}`}
  3835. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  3836. >
  3837. <Icon className={`w-4 h-4 ${color}`} />
  3838. </button>
  3839. {showAirductMenu === printer.id && (
  3840. <>
  3841. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  3842. <div className="absolute bottom-full left-0 mb-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg py-1 min-w-[130px]">
  3843. {([
  3844. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  3845. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  3846. ] as const).map(({ mode, label, modeId }) => (
  3847. <button
  3848. key={mode}
  3849. onClick={() => {
  3850. airductMutation.mutate(mode);
  3851. setShowAirductMenu(null);
  3852. }}
  3853. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  3854. status.airduct_mode === modeId
  3855. ? 'text-bambu-green bg-bambu-green/10'
  3856. : 'text-white hover:bg-bambu-dark-tertiary'
  3857. }`}
  3858. >
  3859. {mode === 'heating' ? <Flame className="w-3 h-3" /> : <Snowflake className="w-3 h-3" />}
  3860. {label}
  3861. </button>
  3862. ))}
  3863. </div>
  3864. </>
  3865. )}
  3866. </div>
  3867. );
  3868. })()}
  3869. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  3870. {(() => {
  3871. const canControl = hasPermission('printers:control');
  3872. const disabled = isPrinting || !canControl;
  3873. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  3874. const jogButtonClass = 'flex h-8 w-8 items-center justify-center rounded bg-indigo-500/15 text-indigo-300 transition-colors hover:bg-indigo-500/30 disabled:cursor-not-allowed disabled:opacity-50';
  3875. const requestZJog = (direction: 1 | -1) => {
  3876. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  3877. const warnedKey = `bambuddy.bedJog.warned.${printer.id}`;
  3878. const warned = (() => {
  3879. try { return sessionStorage.getItem(warnedKey) === '1'; }
  3880. catch { return false; }
  3881. })();
  3882. if (warned) {
  3883. bedJogMutation.mutate({ distance: signed, force: true });
  3884. } else {
  3885. setShowNotHomedModal({ distance: signed });
  3886. }
  3887. };
  3888. const requestXyJog = (x: number, y: number) => {
  3889. xyJogMutation.mutate({ x, y });
  3890. };
  3891. const requestExtruderJog = (distance: number) => {
  3892. extruderJogMutation.mutate(distance);
  3893. };
  3894. return (
  3895. <div className="relative">
  3896. <button
  3897. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  3898. disabled={disabled}
  3899. className={`${iconControlClass} ${
  3900. disabled
  3901. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  3902. : 'bg-indigo-500/10 text-indigo-400 hover:bg-indigo-500/20'
  3903. }`}
  3904. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  3905. >
  3906. <Move className="w-4 h-4" />
  3907. </button>
  3908. {showBedJogMenu === printer.id && (
  3909. <>
  3910. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  3911. <div className="absolute bottom-full left-0 mb-1 z-50 flex w-[216px] flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl">
  3912. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  3913. {t('printers.bedJog.title')}
  3914. </div>
  3915. <div className="h-px bg-bambu-dark-tertiary" />
  3916. <div className="flex justify-center px-3 py-2.5">
  3917. <div className="flex items-center justify-center gap-3">
  3918. <div className="grid grid-cols-3 gap-1">
  3919. <div />
  3920. <button
  3921. onClick={() => requestXyJog(0, bedJogStep)}
  3922. disabled={xyJogMutation.isPending}
  3923. className={jogButtonClass}
  3924. aria-label="Move Y forward"
  3925. >
  3926. <ArrowUp className="w-4 h-4" />
  3927. </button>
  3928. <div />
  3929. <button
  3930. onClick={() => requestXyJog(-bedJogStep, 0)}
  3931. disabled={xyJogMutation.isPending}
  3932. className={jogButtonClass}
  3933. aria-label="Move X left"
  3934. >
  3935. <ArrowLeft className="w-4 h-4" />
  3936. </button>
  3937. <button
  3938. onClick={() => {
  3939. setShowBedJogMenu(null);
  3940. homeAxesMutation.mutate('all');
  3941. }}
  3942. disabled={homeAxesMutation.isPending}
  3943. className={jogButtonClass}
  3944. aria-label={t('printers.bedJog.homeZ')}
  3945. >
  3946. <Home className="w-4 h-4" />
  3947. </button>
  3948. <button
  3949. onClick={() => requestXyJog(bedJogStep, 0)}
  3950. disabled={xyJogMutation.isPending}
  3951. className={jogButtonClass}
  3952. aria-label="Move X right"
  3953. >
  3954. <ArrowRight className="w-4 h-4" />
  3955. </button>
  3956. <div />
  3957. <button
  3958. onClick={() => requestXyJog(0, -bedJogStep)}
  3959. disabled={xyJogMutation.isPending}
  3960. className={jogButtonClass}
  3961. aria-label="Move Y back"
  3962. >
  3963. <ArrowDown className="w-4 h-4" />
  3964. </button>
  3965. <div />
  3966. </div>
  3967. <div className="flex flex-col items-center gap-1">
  3968. <button
  3969. onClick={() => requestZJog(-1)}
  3970. disabled={bedJogMutation.isPending}
  3971. className={jogButtonClass}
  3972. aria-label={t('printers.bedJog.up')}
  3973. >
  3974. <ArrowUp className="w-4 h-4" />
  3975. </button>
  3976. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  3977. <Layers className="w-4 h-4" />
  3978. </div>
  3979. <button
  3980. onClick={() => requestZJog(1)}
  3981. disabled={bedJogMutation.isPending}
  3982. className={jogButtonClass}
  3983. aria-label={t('printers.bedJog.down')}
  3984. >
  3985. <ArrowDown className="w-4 h-4" />
  3986. </button>
  3987. </div>
  3988. <div className="flex flex-col items-center gap-1">
  3989. <button
  3990. onClick={() => requestExtruderJog(-bedJogStep)}
  3991. disabled={extruderJogMutation.isPending}
  3992. className={jogButtonClass}
  3993. aria-label="Retract filament"
  3994. >
  3995. <ArrowUp className="w-4 h-4" />
  3996. </button>
  3997. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  3998. <span className="text-sm font-semibold leading-none">E</span>
  3999. </div>
  4000. <button
  4001. onClick={() => requestExtruderJog(bedJogStep)}
  4002. disabled={extruderJogMutation.isPending}
  4003. className={jogButtonClass}
  4004. aria-label="Extrude filament"
  4005. >
  4006. <ArrowDown className="w-4 h-4" />
  4007. </button>
  4008. </div>
  4009. </div>
  4010. </div>
  4011. <div className="h-px bg-bambu-dark-tertiary" />
  4012. <div className="px-3 pt-2.5 pb-3">
  4013. <div className="mb-1 text-[9px] uppercase tracking-wider text-bambu-gray/70">
  4014. {t('printers.bedJog.step')}
  4015. </div>
  4016. <div className="flex gap-1">
  4017. {[1, 10, 50].map((step) => (
  4018. <button
  4019. key={step}
  4020. onClick={() => setBedJogStep(step)}
  4021. className={`flex-1 px-1 py-1 rounded text-[10px] transition-colors ${
  4022. bedJogStep === step
  4023. ? 'bg-bambu-green/20 text-bambu-green'
  4024. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4025. }`}
  4026. >
  4027. {step}
  4028. </button>
  4029. ))}
  4030. </div>
  4031. </div>
  4032. </div>
  4033. </>
  4034. )}
  4035. </div>
  4036. );
  4037. })()}
  4038. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4039. <button
  4040. onClick={handleTogglePlateDetection}
  4041. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4042. className={`${iconControlClass} rounded-r-none ${
  4043. printer.plate_detection_enabled
  4044. ? 'bg-green-500/10 text-green-400 hover:bg-green-500/20'
  4045. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4046. }`}
  4047. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4048. >
  4049. {plateDetectionMutation.isPending ? (
  4050. <Loader2 className="w-4 h-4 animate-spin" />
  4051. ) : (
  4052. <ScanSearch className="w-4 h-4" />
  4053. )}
  4054. </button>
  4055. <button
  4056. onClick={handleOpenPlateManagement}
  4057. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4058. className={`flex h-8 w-8 items-center justify-center rounded-r-lg border-l border-bambu-dark-tertiary transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
  4059. printer.plate_detection_enabled
  4060. ? 'bg-green-500/10 text-green-400 hover:bg-green-500/20'
  4061. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4062. }`}
  4063. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4064. >
  4065. {isCheckingPlate ? (
  4066. <Loader2 className="w-4 h-4 animate-spin" />
  4067. ) : (
  4068. <ChevronDown className="w-4 h-4" />
  4069. )}
  4070. </button>
  4071. </div>
  4072. {/* Print Speed */}
  4073. {(() => (
  4074. <div className="relative">
  4075. <button
  4076. data-testid="speed-control"
  4077. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4078. disabled={!isPrinting || !hasPermission('printers:control')}
  4079. className={`${iconControlClass} ${
  4080. isPrinting
  4081. ? 'bg-amber-500/10 text-amber-400 hover:bg-amber-500/20'
  4082. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4083. }`}
  4084. title={isPrinting ? t('printers.speed.title') : undefined}
  4085. >
  4086. <Gauge className="w-4 h-4" />
  4087. </button>
  4088. {showSpeedMenu === printer.id && (
  4089. <>
  4090. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4091. <div className="absolute bottom-full left-0 mb-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg py-1 min-w-[130px]">
  4092. {([
  4093. { mode: 1, label: t('printers.speed.silent') },
  4094. { mode: 2, label: t('printers.speed.standard') },
  4095. { mode: 3, label: t('printers.speed.sport') },
  4096. { mode: 4, label: t('printers.speed.ludicrous') },
  4097. ] as const).map(({ mode, label }) => (
  4098. <button
  4099. key={mode}
  4100. onClick={() => {
  4101. printSpeedMutation.mutate(mode);
  4102. setShowSpeedMenu(null);
  4103. }}
  4104. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4105. status.speed_level === mode
  4106. ? 'text-bambu-green bg-bambu-green/10'
  4107. : 'text-white hover:bg-bambu-dark-tertiary'
  4108. }`}
  4109. >
  4110. {label}
  4111. </button>
  4112. ))}
  4113. </div>
  4114. </>
  4115. )}
  4116. </div>
  4117. ))()}
  4118. </div>
  4119. {/* Right: Print Control Buttons */}
  4120. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4121. {/* Pause/Resume button */}
  4122. {(() => {
  4123. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4124. return (
  4125. <button
  4126. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4127. disabled={pauseUnavailable}
  4128. className={`
  4129. ${printControlClass}
  4130. ${pauseUnavailable
  4131. ? unavailablePrintActionClass
  4132. : isPaused
  4133. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4134. : 'bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30'
  4135. }
  4136. `}
  4137. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4138. >
  4139. {isPaused ? <Play className="w-3 h-3" /> : <Pause className="w-3 h-3" />}
  4140. {isPaused ? t('printers.resume') : t('printers.pause')}
  4141. </button>
  4142. );
  4143. })()}
  4144. {/* Stop button */}
  4145. {(() => {
  4146. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4147. return (
  4148. <button
  4149. onClick={() => setShowStopConfirm(true)}
  4150. disabled={stopUnavailable}
  4151. className={`
  4152. ${printControlClass}
  4153. ${stopUnavailable
  4154. ? unavailablePrintActionClass
  4155. : 'bg-red-500/20 text-red-400 hover:bg-red-500/30'
  4156. }
  4157. `}
  4158. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4159. >
  4160. <Square className="w-3 h-3" />
  4161. {t('printers.stop')}
  4162. </button>
  4163. );
  4164. })()}
  4165. </div>
  4166. </div>
  4167. </div>
  4168. );
  4169. })()}
  4170. {/* AMS Units - 2-Column Grid Layout */}
  4171. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4172. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4173. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4174. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4175. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4176. const filamentSlotClass = 'min-w-14';
  4177. // #1762 (comment 2): while a print is running/paused, overlay a small
  4178. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4179. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4180. // staged to a printer with mismatched filament: the wrong-slot pill
  4181. // is visible the instant printing starts.
  4182. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4183. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4184. ? status.ams_mapping
  4185. : [];
  4186. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4187. const boundedSlotCount = Math.max(1, slotCount);
  4188. const gapCount = Math.max(0, boundedSlotCount - 1);
  4189. const minWidth = `calc(${boundedSlotCount} * 3.5rem + ${gapCount} * 0.25rem + 1rem)`;
  4190. return {
  4191. flex: `1 1 ${minWidth}`,
  4192. minWidth,
  4193. };
  4194. };
  4195. return (
  4196. <div className="mt-3">
  4197. {/* Section Header */}
  4198. <div className="flex items-center gap-2 mb-2">
  4199. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  4200. {t('printers.filaments')}
  4201. </span>
  4202. <AmsBackupBadge
  4203. state={status.ams_filament_backup}
  4204. onClick={() => setAmsBackupModalOpen(true)}
  4205. />
  4206. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4207. </div>
  4208. {/* AMS Content */}
  4209. <div className="flex flex-wrap gap-2">
  4210. {/* Regular AMS units */}
  4211. {regularAms.map((ams) => {
  4212. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4213. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4214. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4215. const isLeftNozzle = extruderId === 1;
  4216. const isRightNozzle = extruderId === 0;
  4217. return (
  4218. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4219. {/* Header: Label + Stats (no icon) */}
  4220. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4221. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4222. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4223. <AmsNameHoverCard
  4224. ams={ams}
  4225. printerId={printer.id}
  4226. label={getAmsLabel(ams.id, ams.tray.length)}
  4227. amsLabels={amsLabels}
  4228. canEdit={hasPermission('printers:update')}
  4229. onSaved={refetchAmsLabels}
  4230. >
  4231. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4232. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4233. </span>
  4234. </AmsNameHoverCard>
  4235. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4236. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4237. )}
  4238. </div>
  4239. {(ams.humidity != null || ams.temp != null) && (
  4240. <div className="flex shrink-0 items-center gap-1.5">
  4241. {ams.humidity != null && (
  4242. <HumidityIndicator
  4243. humidity={ams.humidity}
  4244. goodThreshold={amsThresholds?.humidityGood}
  4245. fairThreshold={amsThresholds?.humidityFair}
  4246. onClick={() => setAmsHistoryModal({
  4247. amsId: ams.id,
  4248. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4249. mode: 'humidity',
  4250. })}
  4251. compact
  4252. />
  4253. )}
  4254. {ams.temp != null && (
  4255. <div className="mr-1">
  4256. <TemperatureIndicator
  4257. temp={ams.temp}
  4258. goodThreshold={amsThresholds?.tempGood}
  4259. fairThreshold={amsThresholds?.tempFair}
  4260. onClick={() => setAmsHistoryModal({
  4261. amsId: ams.id,
  4262. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4263. mode: 'temperature',
  4264. })}
  4265. compact
  4266. />
  4267. </div>
  4268. )}
  4269. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s) */}
  4270. {status.supports_drying && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4271. <button
  4272. disabled={!!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4273. onClick={(e) => {
  4274. if (ams.dry_time > 0) {
  4275. stopDryingMutation.mutate(ams.id);
  4276. } else if (dryingPopoverAmsId === ams.id) {
  4277. setDryingPopoverAmsId(null);
  4278. } else {
  4279. const firstTray = ams.tray.find(t => t.tray_type);
  4280. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4281. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4282. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4283. setDryingFilament(filType);
  4284. setDryingTemp(preset[moduleType] || preset.n3f);
  4285. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4286. setDryingRotateTray(false);
  4287. setDryingPopoverModuleType(ams.module_type);
  4288. setDryingPopoverAmsId(ams.id);
  4289. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4290. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4291. }
  4292. }}
  4293. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4294. ams.dry_time > 0
  4295. ? 'bg-amber-500/20 text-amber-400'
  4296. : ams.dry_sf_reason?.length
  4297. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4298. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4299. }`}
  4300. title={ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t('printers.drying.powerRequired') : t('printers.drying.start')}
  4301. >
  4302. <Flame className="w-3 h-3" />
  4303. </button>
  4304. )}
  4305. </div>
  4306. )}
  4307. </div>
  4308. {/* Drying status bar */}
  4309. {ams.dry_time > 0 && (
  4310. <div className="flex items-center gap-2 rounded-lg bg-amber-500/10 px-2 py-1 text-[9px]">
  4311. <Flame className="w-3 h-3 text-amber-400 shrink-0" />
  4312. <span className="text-amber-400 font-medium">{t('printers.drying.active')}</span>
  4313. <span className="text-amber-300/70">
  4314. {t('printers.drying.timeRemaining', {
  4315. time: ams.dry_time >= 60
  4316. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4317. : `${ams.dry_time}m`
  4318. })}
  4319. </span>
  4320. <button
  4321. onClick={() => stopDryingMutation.mutate(ams.id)}
  4322. disabled={stopDryingMutation.isPending}
  4323. className="ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50"
  4324. title={t('printers.drying.stop')}
  4325. >
  4326. <X className="w-3 h-3" />
  4327. </button>
  4328. </div>
  4329. )}
  4330. {/* Slots grid: 4 columns - always render 4 slots */}
  4331. <div className="grid w-full grid-cols-[repeat(4,minmax(3.5rem,1fr))] gap-1">
  4332. {[0, 1, 2, 3].map((slotIdx) => {
  4333. // Find tray data for this slot (may be undefined if data incomplete)
  4334. // Use array index if available, as tray.id may not always be set
  4335. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  4336. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4337. const isEmpty = !tray?.tray_type;
  4338. const emptyKind = getEmptySlotKind(tray);
  4339. // Check if this is the currently loaded tray
  4340. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  4341. const globalTrayId = ams.id * 4 + slotIdx;
  4342. const isActive = effectiveTrayNow === globalTrayId;
  4343. // Get cloud preset info if available
  4344. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4345. // Get saved slot preset mapping (for user-configured slots)
  4346. const slotPreset = slotPresets?.[globalTrayId];
  4347. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4348. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  4349. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  4350. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  4351. // Slot-assigned-only spool fill (no tag link required)
  4352. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4353. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  4354. : undefined;
  4355. const slotSpoolForFill = slotAssignmentForFill
  4356. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  4357. : undefined;
  4358. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  4359. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  4360. : null;
  4361. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4362. const inventoryFill = (() => {
  4363. const sp = inventoryAssignment?.spool;
  4364. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4365. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4366. }
  4367. return null;
  4368. })();
  4369. // If inventory says 0% but AMS reports positive remain, prefer AMS
  4370. // (inventory weight_used may be stale or over-counted — #676)
  4371. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4372. ? null : inventoryFill;
  4373. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4374. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  4375. : resolvedInventoryFill !== null ? 'inventory' as const
  4376. : hasFillLevel ? 'ams' as const
  4377. : undefined;
  4378. // Build filament data for hover card
  4379. const filamentData = tray?.tray_type ? {
  4380. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4381. // Spoolman spool name wins over cloud lookup so a slot bound to
  4382. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  4383. // Design PLA") instead of whatever the printer's filament_id
  4384. // resolves to in the cloud catalog (often "Generic PLA" for
  4385. // P-prefix local presets). Spoolman's filament.name is just the
  4386. // material+subtype ("PLA Basic"); prepend the spool's brand so
  4387. // the hover card shows "Devil Design PLA Basic" rather than the
  4388. // vendor-less form. Strip the "@<printer>..." suffix that
  4389. // BambuStudio appends to user-preset names.
  4390. profile: slotPreset?.preset_name || (slotSpoolForFill ? [slotSpoolForFill.brand, slotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || slotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || inventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  4391. colorName: getColorName(tray.tray_color || ''),
  4392. colorHex: tray.tray_color || null,
  4393. kFactor: formatKValue(tray.k),
  4394. fillLevel: effectiveFill,
  4395. trayUuid: tray.tray_uuid || null,
  4396. tagUid: tray.tag_uid || null,
  4397. fillSource,
  4398. } : null;
  4399. // Check if this specific slot is being refreshed
  4400. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  4401. refreshingSlot?.slotId === slotIdx;
  4402. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  4403. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4404. const activePrintSlotLabel = activePrintSlotIdx >= 0
  4405. ? `P${activePrintSlotIdx + 1}`
  4406. : null;
  4407. // Slot visual content (goes inside hover card)
  4408. const slotVisual = (
  4409. <div
  4410. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  4411. >
  4412. {activePrintSlotLabel && (
  4413. <span
  4414. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  4415. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  4416. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4417. >
  4418. {activePrintSlotLabel}
  4419. </span>
  4420. )}
  4421. {/* Filament color circle with 1-based slot number centered inside */}
  4422. <FilamentSlotCircle
  4423. trayColor={tray?.tray_color}
  4424. trayType={tray?.tray_type}
  4425. isEmpty={isEmpty}
  4426. emptyKind={emptyKind}
  4427. slotNumber={slotIdx + 1}
  4428. />
  4429. <div className="text-[9px] text-white font-bold truncate">
  4430. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4431. </div>
  4432. {/* Fill bar */}
  4433. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4434. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  4435. <div
  4436. className="h-full rounded-full transition-all"
  4437. style={{
  4438. width: `${effectiveFill}%`,
  4439. backgroundColor: getFillBarColor(effectiveFill),
  4440. }}
  4441. />
  4442. )}
  4443. </div>
  4444. </div>
  4445. );
  4446. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  4447. return (
  4448. <div key={slotIdx} className={`relative group w-full ${filamentSlotClass}`}>
  4449. {/* Loading overlay during RFID re-read */}
  4450. {isRefreshing && (
  4451. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4452. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4453. </div>
  4454. )}
  4455. {/* Hover card wraps only the visual content */}
  4456. {filamentData ? (
  4457. <FilamentHoverCard
  4458. data={filamentData}
  4459. actions={renderAmsSlotActions({
  4460. amsId: ams.id,
  4461. slotId: slotIdx,
  4462. loadTrayId: ams.id * 4 + slotIdx,
  4463. isRefreshing,
  4464. })}
  4465. spoolman={{
  4466. enabled: spoolmanEnabled,
  4467. // #1457: slot assignment is the user's most explicit action — it must
  4468. // outrank the tag-link, which can be stale when a non-RFID slot's
  4469. // fallback tag is still attached to a previous spool in Spoolman.
  4470. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  4471. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  4472. spoolmanUrl,
  4473. syncMode: spoolmanSyncMode,
  4474. // Suppress Link button when slot is already occupied by ANY assignment
  4475. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  4476. // suppressed for Spoolman; the maintainer screenshot shows the badge
  4477. // still appearing on slots with a local Devil Design PLA assigned.
  4478. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  4479. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  4480. setLinkSpoolModal({
  4481. tagUid: filamentData.tagUid || linkTag,
  4482. trayUuid: filamentData.trayUuid || '',
  4483. printerId: printer.id,
  4484. amsId: ams.id,
  4485. trayId: slotIdx,
  4486. });
  4487. } : undefined,
  4488. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  4489. }}
  4490. inventory={(() => {
  4491. if (spoolmanEnabled) {
  4492. if (spoolmanLoading) return undefined;
  4493. const slotAssignment = slotAssignmentForFill;
  4494. const spoolmanSpool = slotSpoolForFill;
  4495. return {
  4496. assignedSpool: spoolmanSpool ? {
  4497. id: spoolmanSpool.id,
  4498. material: spoolmanSpool.material,
  4499. brand: spoolmanSpool.brand ?? null,
  4500. color_name: spoolmanSpool.color_name ?? null,
  4501. remainingWeightGrams: spoolmanSpool.label_weight
  4502. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4503. : undefined,
  4504. } : null,
  4505. onAssignSpool: () => setAssignSpoolModal({
  4506. printerId: printer.id,
  4507. amsId: ams.id,
  4508. trayId: slotIdx,
  4509. trayInfo: {
  4510. type: tray?.tray_type || filamentData.profile,
  4511. material: tray?.tray_type ?? undefined,
  4512. profile: filamentData.profile,
  4513. color: filamentData.colorHex || '',
  4514. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4515. },
  4516. }),
  4517. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4518. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4519. };
  4520. }
  4521. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4522. return {
  4523. assignedSpool: assignment?.spool ? {
  4524. id: assignment.spool.id,
  4525. material: assignment.spool.material,
  4526. brand: assignment.spool.brand,
  4527. color_name: assignment.spool.color_name,
  4528. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4529. } : null,
  4530. onAssignSpool: () => setAssignSpoolModal({
  4531. printerId: printer.id,
  4532. amsId: ams.id,
  4533. trayId: slotIdx,
  4534. trayInfo: {
  4535. type: tray?.tray_type || filamentData.profile,
  4536. material: tray?.tray_type ?? undefined,
  4537. profile: filamentData.profile,
  4538. color: filamentData.colorHex || '',
  4539. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4540. },
  4541. }),
  4542. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  4543. isAssigned: !!assignment || isBambuLabSpool(tray),
  4544. };
  4545. })()}
  4546. configureSlot={{
  4547. enabled: hasPermission('printers:control'),
  4548. onConfigure: () => setConfigureSlotModal({
  4549. amsId: ams.id,
  4550. trayId: slotIdx,
  4551. trayCount: ams.tray.length,
  4552. trayType: tray?.tray_type || undefined,
  4553. trayColor: tray?.tray_color || undefined,
  4554. traySubBrands: tray?.tray_sub_brands || undefined,
  4555. trayInfoIdx: tray?.tray_info_idx || undefined,
  4556. extruderId: mappedExtruderId,
  4557. caliIdx: tray?.cali_idx,
  4558. savedPresetId: slotPreset?.preset_id,
  4559. }),
  4560. }}
  4561. >
  4562. {slotVisual}
  4563. </FilamentHoverCard>
  4564. ) : (
  4565. <EmptySlotHoverCard
  4566. kind={emptyKind ?? undefined}
  4567. actions={renderAmsSlotActions({
  4568. amsId: ams.id,
  4569. slotId: slotIdx,
  4570. loadTrayId: ams.id * 4 + slotIdx,
  4571. isRefreshing,
  4572. })}
  4573. configureSlot={{
  4574. enabled: hasPermission('printers:control'),
  4575. onConfigure: () => setConfigureSlotModal({
  4576. amsId: ams.id,
  4577. trayId: slotIdx,
  4578. trayCount: ams.tray.length,
  4579. extruderId: mappedExtruderId,
  4580. }),
  4581. }}
  4582. onAssignSpool={() => setAssignSpoolModal({
  4583. printerId: printer.id,
  4584. amsId: ams.id,
  4585. trayId: slotIdx,
  4586. trayInfo: {
  4587. type: '',
  4588. material: undefined,
  4589. profile: '',
  4590. color: '',
  4591. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4592. },
  4593. })}
  4594. >
  4595. {slotVisual}
  4596. </EmptySlotHoverCard>
  4597. )}
  4598. </div>
  4599. );
  4600. })}
  4601. </div>
  4602. </div>
  4603. );
  4604. })}
  4605. {/* HT AMS units */}
  4606. {htAms.map((ams) => {
  4607. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4608. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4609. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4610. const isLeftNozzle = extruderId === 1;
  4611. const isRightNozzle = extruderId === 0;
  4612. const tray = ams.tray[0];
  4613. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4614. const isEmpty = !tray?.tray_type;
  4615. const emptyKind = getEmptySlotKind(tray);
  4616. // Check if this is the currently loaded tray
  4617. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  4618. const isActive = effectiveTrayNow === globalTrayId;
  4619. // Get cloud preset info if available
  4620. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4621. // Get saved slot preset mapping (for user-configured slots)
  4622. const slotPreset = slotPresets?.[globalTrayId];
  4623. const htSlotId = tray?.id ?? 0;
  4624. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4625. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  4626. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  4627. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  4628. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4629. const htInventoryFill = (() => {
  4630. const sp = htInventoryAssignment?.spool;
  4631. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4632. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4633. }
  4634. return null;
  4635. })();
  4636. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  4637. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4638. ? null : htInventoryFill;
  4639. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  4640. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4641. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  4642. : undefined;
  4643. const htSlotSpoolForFill = htSlotAssignmentForFill
  4644. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  4645. : undefined;
  4646. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  4647. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  4648. : null;
  4649. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4650. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  4651. : htResolvedInventoryFill !== null ? 'inventory' as const
  4652. : hasFillLevel ? 'ams' as const
  4653. : undefined;
  4654. // Build filament data for hover card
  4655. const filamentData = tray?.tray_type ? {
  4656. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4657. profile: slotPreset?.preset_name || (htSlotSpoolForFill ? [htSlotSpoolForFill.brand, htSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || htSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || htInventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  4658. colorName: getColorName(tray.tray_color || ''),
  4659. colorHex: tray.tray_color || null,
  4660. kFactor: formatKValue(tray.k),
  4661. fillLevel: htEffectiveFill,
  4662. trayUuid: tray.tray_uuid || null,
  4663. tagUid: tray.tag_uid || null,
  4664. fillSource: htFillSource,
  4665. } : null;
  4666. // Check if this specific slot is being refreshed
  4667. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  4668. refreshingSlot?.slotId === htSlotId;
  4669. // #1762 (comment 2): active print-slot index for this HT slot.
  4670. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4671. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  4672. ? `P${htActivePrintSlotIdx + 1}`
  4673. : null;
  4674. // Slot visual content (goes inside hover card)
  4675. const slotVisual = (
  4676. <div
  4677. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  4678. >
  4679. {htActivePrintSlotLabel && (
  4680. <span
  4681. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  4682. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  4683. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4684. >
  4685. {htActivePrintSlotLabel}
  4686. </span>
  4687. )}
  4688. {/* Filament color circle with 1-based slot number centered inside */}
  4689. <FilamentSlotCircle
  4690. trayColor={tray?.tray_color}
  4691. trayType={tray?.tray_type}
  4692. isEmpty={isEmpty}
  4693. emptyKind={emptyKind}
  4694. slotNumber={1}
  4695. />
  4696. <div className="text-[9px] text-white font-bold truncate">
  4697. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4698. </div>
  4699. {/* Fill bar */}
  4700. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4701. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  4702. <div
  4703. className="h-full rounded-full transition-all"
  4704. style={{
  4705. width: `${htEffectiveFill}%`,
  4706. backgroundColor: getFillBarColor(htEffectiveFill),
  4707. }}
  4708. />
  4709. )}
  4710. </div>
  4711. </div>
  4712. );
  4713. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  4714. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  4715. // Without this override, the L view squishes HT into a sliver next to the
  4716. // 4-slot AMS neighbors.
  4717. const htCardStyle: React.CSSProperties = { flex: '1 1 11rem', minWidth: '11rem' };
  4718. return (
  4719. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4720. {/* Row 1: Label + Nozzle + Drying */}
  4721. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4722. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4723. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4724. <AmsNameHoverCard
  4725. ams={ams}
  4726. printerId={printer.id}
  4727. label={getAmsLabel(ams.id, ams.tray.length)}
  4728. amsLabels={amsLabels}
  4729. canEdit={hasPermission('printers:update')}
  4730. onSaved={refetchAmsLabels}
  4731. >
  4732. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4733. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4734. </span>
  4735. </AmsNameHoverCard>
  4736. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4737. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4738. )}
  4739. </div>
  4740. {/* Drying button for HT AMS */}
  4741. {status.supports_drying && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4742. <div className="relative ml-auto">
  4743. <button
  4744. onClick={(e) => {
  4745. if (ams.dry_time > 0) {
  4746. stopDryingMutation.mutate(ams.id);
  4747. } else if (dryingPopoverAmsId === ams.id) {
  4748. setDryingPopoverAmsId(null);
  4749. } else {
  4750. const firstTray = ams.tray.find(t => t.tray_type);
  4751. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4752. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4753. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4754. setDryingFilament(filType);
  4755. setDryingTemp(preset[moduleType] || preset.n3f);
  4756. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4757. setDryingRotateTray(false);
  4758. setDryingPopoverModuleType(ams.module_type);
  4759. setDryingPopoverAmsId(ams.id);
  4760. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4761. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4762. }
  4763. }}
  4764. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4765. ams.dry_time > 0
  4766. ? 'bg-amber-500/20 text-amber-400'
  4767. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4768. }`}
  4769. title={ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  4770. >
  4771. <Flame className="w-3 h-3" />
  4772. </button>
  4773. </div>
  4774. )}
  4775. </div>
  4776. {/* HT AMS drying status bar */}
  4777. {ams.dry_time > 0 && (
  4778. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-500/10 px-2 py-1 text-[9px]">
  4779. <Flame className="w-3 h-3 text-amber-400 shrink-0" />
  4780. <span className="text-amber-300/70 text-[8px] truncate">
  4781. {ams.dry_time >= 60
  4782. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4783. : `${ams.dry_time}m`}
  4784. </span>
  4785. <button
  4786. onClick={() => stopDryingMutation.mutate(ams.id)}
  4787. disabled={stopDryingMutation.isPending}
  4788. className="ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0"
  4789. title={t('printers.drying.stop')}
  4790. >
  4791. <X className="w-3 h-3" />
  4792. </button>
  4793. </div>
  4794. )}
  4795. {/* Row 2: Slot (left) + Stats (right stacked) */}
  4796. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  4797. {/* Slot wrapper with loading overlay */}
  4798. <div className="relative group min-w-14 flex-1">
  4799. {/* Loading overlay during RFID re-read */}
  4800. {isHtRefreshing && (
  4801. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4802. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4803. </div>
  4804. )}
  4805. {/* Hover card wraps only the visual content */}
  4806. {filamentData ? (
  4807. <FilamentHoverCard
  4808. data={filamentData}
  4809. actions={renderAmsSlotActions({
  4810. amsId: ams.id,
  4811. slotId: htSlotId,
  4812. loadTrayId: ams.id * 4 + htSlotId,
  4813. isRefreshing: isHtRefreshing,
  4814. })}
  4815. spoolman={{
  4816. enabled: spoolmanEnabled,
  4817. // #1457: slot assignment outranks tag-link (see top-level slot block).
  4818. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  4819. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  4820. spoolmanUrl,
  4821. syncMode: spoolmanSyncMode,
  4822. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  4823. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  4824. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  4825. setLinkSpoolModal({
  4826. tagUid: filamentData.tagUid || linkTag,
  4827. trayUuid: filamentData.trayUuid || '',
  4828. printerId: printer.id,
  4829. amsId: ams.id,
  4830. trayId: htSlotId,
  4831. });
  4832. } : undefined,
  4833. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  4834. }}
  4835. inventory={(() => {
  4836. if (spoolmanEnabled) {
  4837. if (spoolmanLoading) return undefined;
  4838. const slotAssignment = htSlotAssignmentForFill;
  4839. const spoolmanSpool = htSlotSpoolForFill;
  4840. return {
  4841. assignedSpool: spoolmanSpool ? {
  4842. id: spoolmanSpool.id,
  4843. material: spoolmanSpool.material,
  4844. brand: spoolmanSpool.brand ?? null,
  4845. color_name: spoolmanSpool.color_name ?? null,
  4846. remainingWeightGrams: spoolmanSpool.label_weight
  4847. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4848. : undefined,
  4849. } : null,
  4850. onAssignSpool: () => setAssignSpoolModal({
  4851. printerId: printer.id,
  4852. amsId: ams.id,
  4853. trayId: htSlotId,
  4854. trayInfo: {
  4855. type: tray?.tray_type || filamentData.profile,
  4856. material: tray?.tray_type ?? undefined,
  4857. profile: filamentData.profile,
  4858. color: filamentData.colorHex || '',
  4859. location: getAmsLabel(ams.id, ams.tray.length),
  4860. },
  4861. }),
  4862. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4863. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4864. };
  4865. }
  4866. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4867. return {
  4868. assignedSpool: assignment?.spool ? {
  4869. id: assignment.spool.id,
  4870. material: assignment.spool.material,
  4871. brand: assignment.spool.brand,
  4872. color_name: assignment.spool.color_name,
  4873. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4874. } : null,
  4875. onAssignSpool: () => setAssignSpoolModal({
  4876. printerId: printer.id,
  4877. amsId: ams.id,
  4878. trayId: htSlotId,
  4879. trayInfo: {
  4880. type: tray?.tray_type || filamentData.profile,
  4881. material: tray?.tray_type ?? undefined,
  4882. profile: filamentData.profile,
  4883. color: filamentData.colorHex || '',
  4884. location: getAmsLabel(ams.id, ams.tray.length),
  4885. },
  4886. }),
  4887. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  4888. isAssigned: !!assignment || isBambuLabSpool(tray),
  4889. };
  4890. })()}
  4891. configureSlot={{
  4892. enabled: hasPermission('printers:control'),
  4893. onConfigure: () => setConfigureSlotModal({
  4894. amsId: ams.id,
  4895. trayId: htSlotId,
  4896. trayCount: ams.tray.length,
  4897. trayType: tray?.tray_type || undefined,
  4898. trayColor: tray?.tray_color || undefined,
  4899. traySubBrands: tray?.tray_sub_brands || undefined,
  4900. trayInfoIdx: tray?.tray_info_idx || undefined,
  4901. extruderId: mappedExtruderId,
  4902. caliIdx: tray?.cali_idx,
  4903. savedPresetId: slotPreset?.preset_id,
  4904. }),
  4905. }}
  4906. >
  4907. {slotVisual}
  4908. </FilamentHoverCard>
  4909. ) : (
  4910. <EmptySlotHoverCard
  4911. kind={emptyKind ?? undefined}
  4912. actions={renderAmsSlotActions({
  4913. amsId: ams.id,
  4914. slotId: htSlotId,
  4915. loadTrayId: ams.id * 4 + htSlotId,
  4916. isRefreshing: isHtRefreshing,
  4917. })}
  4918. configureSlot={{
  4919. enabled: hasPermission('printers:control'),
  4920. onConfigure: () => setConfigureSlotModal({
  4921. amsId: ams.id,
  4922. trayId: htSlotId,
  4923. trayCount: ams.tray.length,
  4924. extruderId: mappedExtruderId,
  4925. }),
  4926. }}
  4927. onAssignSpool={() => setAssignSpoolModal({
  4928. printerId: printer.id,
  4929. amsId: ams.id,
  4930. trayId: htSlotId,
  4931. trayInfo: {
  4932. type: '',
  4933. material: undefined,
  4934. profile: '',
  4935. color: '',
  4936. location: getAmsLabel(ams.id, ams.tray.length),
  4937. },
  4938. })}
  4939. >
  4940. {slotVisual}
  4941. </EmptySlotHoverCard>
  4942. )}
  4943. </div>
  4944. {/* Stats stacked vertically: Temp on top, Humidity below */}
  4945. {(ams.humidity != null || ams.temp != null) && (
  4946. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  4947. {ams.temp != null && (
  4948. <TemperatureIndicator
  4949. temp={ams.temp}
  4950. goodThreshold={amsThresholds?.tempGood}
  4951. fairThreshold={amsThresholds?.tempFair}
  4952. onClick={() => setAmsHistoryModal({
  4953. amsId: ams.id,
  4954. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4955. mode: 'temperature',
  4956. })}
  4957. compact
  4958. />
  4959. )}
  4960. {ams.humidity != null && (
  4961. <HumidityIndicator
  4962. humidity={ams.humidity}
  4963. goodThreshold={amsThresholds?.humidityGood}
  4964. fairThreshold={amsThresholds?.humidityFair}
  4965. onClick={() => setAmsHistoryModal({
  4966. amsId: ams.id,
  4967. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4968. mode: 'humidity',
  4969. })}
  4970. compact
  4971. />
  4972. )}
  4973. </div>
  4974. )}
  4975. </div>
  4976. </div>
  4977. );
  4978. })}
  4979. {/* External spool(s) - grouped in one card like regular AMS */}
  4980. {status.vt_tray.length > 0 && (
  4981. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4982. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4983. <span className="block min-w-0 flex-1 truncate text-[10px] text-white font-medium">{t('printers.external')}</span>
  4984. </div>
  4985. <div className={`grid w-full ${status.vt_tray.length > 1 ? 'grid-cols-[repeat(2,minmax(3.5rem,1fr))]' : 'grid-cols-[minmax(3.5rem,1fr)]'} gap-1`}>
  4986. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  4987. const extTrayId = extTray.id ?? 254;
  4988. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  4989. // generically — use active_extruder to determine L vs R:
  4990. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  4991. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  4992. ? (extTrayId === 254 && status.active_extruder === 1) ||
  4993. (extTrayId === 255 && status.active_extruder === 0)
  4994. : effectiveTrayNow === extTrayId;
  4995. const slotTrayId = extTrayId - 254; // 0 or 1
  4996. const extLabel = isDualNozzle
  4997. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  4998. : '';
  4999. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5000. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5001. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5002. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5003. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5004. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5005. const extInventoryFill = (() => {
  5006. const sp = extInventoryAssignment?.spool;
  5007. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5008. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5009. }
  5010. return null;
  5011. })();
  5012. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5013. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5014. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5015. ? null : extInventoryFill;
  5016. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5017. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5018. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5019. : undefined;
  5020. const extSlotSpoolForFill = extSlotAssignmentForFill
  5021. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5022. : undefined;
  5023. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5024. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5025. : null;
  5026. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5027. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5028. : extResolvedInventoryFill !== null ? 'inventory' as const
  5029. : extHasFillLevel ? 'ams' as const
  5030. : undefined;
  5031. const extFilamentData = {
  5032. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5033. profile: extSlotPreset?.preset_name || (extSlotSpoolForFill ? [extSlotSpoolForFill.brand, extSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || extSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || extInventoryAssignment?.spool?.slicer_filament_name || extCloudInfo?.name || extTray.tray_sub_brands || extTray.tray_type || 'Unknown',
  5034. colorName: getColorName(extTray.tray_color || ''),
  5035. colorHex: extTray.tray_color || null,
  5036. kFactor: formatKValue(extTray.k),
  5037. fillLevel: extEffectiveFill,
  5038. trayUuid: extTray.tray_uuid || null,
  5039. tagUid: extTray.tag_uid || null,
  5040. fillSource: extFillSource,
  5041. };
  5042. const isEmpty = !extTray.tray_type;
  5043. const emptyKind = getEmptySlotKind(extTray);
  5044. const extSlotContent = (
  5045. <div className={`w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isExtActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}>
  5046. {/* Filament color circle with 1-based slot number centered inside */}
  5047. <FilamentSlotCircle
  5048. trayColor={extTray.tray_color}
  5049. trayType={extTray.tray_type}
  5050. isEmpty={isEmpty}
  5051. emptyKind={emptyKind}
  5052. slotNumber={slotTrayId + 1}
  5053. />
  5054. <div className={`text-[9px] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5055. {extTray.tray_type || t('ams.slotEmpty')}
  5056. </div>
  5057. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5058. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5059. <div
  5060. className="h-full rounded-full transition-all"
  5061. style={{
  5062. width: `${extEffectiveFill}%`,
  5063. backgroundColor: getFillBarColor(extEffectiveFill),
  5064. }}
  5065. />
  5066. )}
  5067. </div>
  5068. {extLabel && <div className="text-[7px] text-white/40 mt-0.5 truncate">{extLabel}</div>}
  5069. </div>
  5070. );
  5071. return (
  5072. <div key={extTrayId} className={`relative group w-full ${filamentSlotClass}`}>
  5073. {!isEmpty ? (
  5074. <FilamentHoverCard
  5075. data={extFilamentData}
  5076. actions={renderAmsSlotActions({
  5077. amsId: 255,
  5078. slotId: slotTrayId,
  5079. loadTrayId: extTrayId,
  5080. includeRfid: false,
  5081. })}
  5082. spoolman={{
  5083. enabled: spoolmanEnabled,
  5084. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5085. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5086. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5087. spoolmanUrl,
  5088. syncMode: spoolmanSyncMode,
  5089. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5090. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5091. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5092. setLinkSpoolModal({
  5093. tagUid: extFilamentData.tagUid || linkTag,
  5094. trayUuid: extFilamentData.trayUuid || '',
  5095. printerId: printer.id,
  5096. amsId: 255,
  5097. trayId: slotTrayId,
  5098. });
  5099. } : undefined,
  5100. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5101. }}
  5102. inventory={(() => {
  5103. if (spoolmanEnabled) {
  5104. if (spoolmanLoading) return undefined;
  5105. const slotAssignment = extSlotAssignmentForFill;
  5106. const spoolmanSpool = extSlotSpoolForFill;
  5107. return {
  5108. assignedSpool: spoolmanSpool ? {
  5109. id: spoolmanSpool.id,
  5110. material: spoolmanSpool.material,
  5111. brand: spoolmanSpool.brand ?? null,
  5112. color_name: spoolmanSpool.color_name ?? null,
  5113. remainingWeightGrams: spoolmanSpool.label_weight
  5114. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5115. : undefined,
  5116. } : null,
  5117. onAssignSpool: () => setAssignSpoolModal({
  5118. printerId: printer.id,
  5119. amsId: 255,
  5120. trayId: slotTrayId,
  5121. trayInfo: {
  5122. type: extTray.tray_type || extFilamentData.profile,
  5123. material: extTray.tray_type ?? undefined,
  5124. profile: extFilamentData.profile,
  5125. color: extFilamentData.colorHex || '',
  5126. location: extLabel || t('printers.external'),
  5127. },
  5128. }),
  5129. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5130. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5131. };
  5132. }
  5133. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5134. return {
  5135. assignedSpool: assignment?.spool ? {
  5136. id: assignment.spool.id,
  5137. material: assignment.spool.material,
  5138. brand: assignment.spool.brand,
  5139. color_name: assignment.spool.color_name,
  5140. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5141. } : null,
  5142. onAssignSpool: () => setAssignSpoolModal({
  5143. printerId: printer.id,
  5144. amsId: 255,
  5145. trayId: slotTrayId,
  5146. trayInfo: {
  5147. type: extTray.tray_type || extFilamentData.profile,
  5148. material: extTray.tray_type ?? undefined,
  5149. profile: extFilamentData.profile,
  5150. color: extFilamentData.colorHex || '',
  5151. location: extLabel || t('printers.external'),
  5152. },
  5153. }),
  5154. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5155. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5156. };
  5157. })()}
  5158. configureSlot={{
  5159. enabled: hasPermission('printers:control'),
  5160. onConfigure: () => setConfigureSlotModal({
  5161. amsId: 255,
  5162. trayId: slotTrayId,
  5163. trayCount: 1,
  5164. trayType: extTray.tray_type || undefined,
  5165. trayColor: extTray.tray_color || undefined,
  5166. traySubBrands: extTray.tray_sub_brands || undefined,
  5167. trayInfoIdx: extTray.tray_info_idx || undefined,
  5168. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5169. caliIdx: extTray.cali_idx,
  5170. savedPresetId: extSlotPreset?.preset_id,
  5171. }),
  5172. }}
  5173. >
  5174. {extSlotContent}
  5175. </FilamentHoverCard>
  5176. ) : (
  5177. <EmptySlotHoverCard
  5178. kind={emptyKind ?? undefined}
  5179. actions={renderAmsSlotActions({
  5180. amsId: 255,
  5181. slotId: slotTrayId,
  5182. loadTrayId: extTrayId,
  5183. includeRfid: false,
  5184. })}
  5185. configureSlot={{
  5186. enabled: hasPermission('printers:control'),
  5187. onConfigure: () => setConfigureSlotModal({
  5188. amsId: 255,
  5189. trayId: slotTrayId,
  5190. trayCount: 1,
  5191. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5192. }),
  5193. }}
  5194. onAssignSpool={() => setAssignSpoolModal({
  5195. printerId: printer.id,
  5196. amsId: 255,
  5197. trayId: slotTrayId,
  5198. trayInfo: {
  5199. type: '',
  5200. material: undefined,
  5201. profile: '',
  5202. color: '',
  5203. location: `External Slot ${slotTrayId + 1}`,
  5204. },
  5205. })}
  5206. >
  5207. {extSlotContent}
  5208. </EmptySlotHoverCard>
  5209. )}
  5210. </div>
  5211. );
  5212. })}
  5213. </div>
  5214. </div>
  5215. )}
  5216. </div>
  5217. </div>
  5218. );
  5219. })()}
  5220. </>
  5221. )}
  5222. {/* Bottom block (power row + action bar). Wrapped together so the
  5223. power row hugs the action bar at the card bottom instead of
  5224. floating up when there's less filament content above. */}
  5225. {viewMode === 'expanded' && (
  5226. <div className="mt-auto">
  5227. {smartPlug && (
  5228. <div className="pt-4">
  5229. <div className="flex items-center gap-2 mb-2">
  5230. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  5231. {t('printers.power', 'Power')}
  5232. </span>
  5233. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5234. </div>
  5235. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  5236. {/* Plug name + current power */}
  5237. <div className="flex items-center gap-2 min-w-0 pl-1">
  5238. <Zap className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  5239. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  5240. <span
  5241. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[10px] font-medium flex-shrink-0"
  5242. title={t('smartPlugs.power')}
  5243. >
  5244. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  5245. </span>
  5246. </div>
  5247. {/* Spacer */}
  5248. <div className="flex-1" />
  5249. <div className="flex items-center gap-2">
  5250. {/* Auto-off */}
  5251. <button
  5252. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  5253. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  5254. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  5255. className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg text-xs font-bold transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
  5256. !hasPermission('smart_plugs:control')
  5257. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5258. : smartPlug.auto_off || smartPlug.auto_off_executed
  5259. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5260. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5261. }`}
  5262. >
  5263. <Clock className="w-4 h-4" />
  5264. </button>
  5265. <button
  5266. onClick={() => {
  5267. if (plugStatus?.state === 'ON') {
  5268. setShowPowerOffConfirm(true);
  5269. } else {
  5270. setShowPowerOnConfirm(true);
  5271. }
  5272. }}
  5273. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  5274. className={`flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg text-xs transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
  5275. !hasPermission('smart_plugs:control')
  5276. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5277. : plugStatus?.state === 'ON'
  5278. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5279. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5280. }`}
  5281. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  5282. >
  5283. <Zap className="w-4 h-4" />
  5284. </button>
  5285. </div>
  5286. </div>
  5287. {/* HA entity buttons row */}
  5288. {scriptPlugs && scriptPlugs.length > 0 && (
  5289. <div className="flex items-center gap-2 mt-2">
  5290. <Home className="w-3.5 h-3.5 text-blue-400 flex-shrink-0" />
  5291. <span className="text-xs text-bambu-gray">HA:</span>
  5292. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  5293. <div className="flex flex-wrap gap-1">
  5294. {scriptPlugs.map(script => {
  5295. const isScript = script.ha_entity_id?.startsWith('script.');
  5296. return (
  5297. <button
  5298. key={script.id}
  5299. onClick={() => {
  5300. if (isScript) {
  5301. runScriptMutation.mutate({ id: script.id, action: 'on' });
  5302. } else {
  5303. setHaToggleConfirm(script);
  5304. }
  5305. }}
  5306. disabled={runScriptMutation.isPending}
  5307. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  5308. className="px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1"
  5309. >
  5310. <Play className="w-2.5 h-2.5" />
  5311. {script.name}
  5312. </button>
  5313. );
  5314. })}
  5315. </div>
  5316. </div>
  5317. )}
  5318. </div>
  5319. )}
  5320. {/* Connection Info & Actions */}
  5321. <div className="pt-4">
  5322. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  5323. <div className="flex items-center justify-between gap-2">
  5324. {printerActionsMenu}
  5325. <div className="flex items-center justify-end gap-2 flex-wrap">
  5326. {/* Camera Button */}
  5327. <Button
  5328. variant="secondary"
  5329. size="sm"
  5330. onClick={() => {
  5331. if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
  5332. onOpenEmbeddedCamera(printer.id, printer.name);
  5333. } else {
  5334. // Use saved window state or defaults
  5335. const saved = localStorage.getItem('cameraWindowState');
  5336. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  5337. const features = [
  5338. `width=${state.width}`,
  5339. `height=${state.height}`,
  5340. state.left !== undefined ? `left=${state.left}` : '',
  5341. state.top !== undefined ? `top=${state.top}` : '',
  5342. // No `noopener`: same-origin popup needs opener so the browser
  5343. // copies sessionStorage (auth token) into the new window.
  5344. 'menubar=no,toolbar=no,location=no,status=no',
  5345. ].filter(Boolean).join(',');
  5346. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  5347. }
  5348. }}
  5349. disabled={!status?.connected || !hasPermission('camera:view')}
  5350. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  5351. className={footerIconButtonClass}
  5352. >
  5353. <Video className="w-4 h-4" />
  5354. </Button>
  5355. <Button
  5356. variant="secondary"
  5357. size="sm"
  5358. onClick={() => setShowFileManager(true)}
  5359. disabled={!isConnected || !hasPermission('printers:files')}
  5360. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  5361. className={footerIconButtonClass}
  5362. >
  5363. <HardDrive className="w-4 h-4" />
  5364. </Button>
  5365. {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
  5366. <Button
  5367. size="sm"
  5368. onClick={() => setShowUploadForPrint(true)}
  5369. disabled={!hasPermission('printers:control')}
  5370. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('common.print')}
  5371. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  5372. >
  5373. <PrinterIcon className="w-4 h-4" />
  5374. {t('common.print')}
  5375. </Button>
  5376. )}
  5377. </div>
  5378. </div>
  5379. </div>
  5380. </div>
  5381. )}
  5382. </CardContent>
  5383. {/* File Manager Modal */}
  5384. {showFileManager && (
  5385. <FileManagerModal
  5386. printerId={printer.id}
  5387. printerName={printer.name}
  5388. onClose={() => setShowFileManager(false)}
  5389. />
  5390. )}
  5391. {/* Upload for Print Modal */}
  5392. {showUploadForPrint && (
  5393. <FileUploadModal
  5394. folderId={null}
  5395. onClose={() => setShowUploadForPrint(false)}
  5396. onUploadComplete={() => {}}
  5397. autoUpload
  5398. accept=".gcode,.3mf"
  5399. validateFile={(file) => {
  5400. const lower = file.name.toLowerCase();
  5401. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  5402. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  5403. }
  5404. }}
  5405. onFileUploaded={(uploadedFile) => {
  5406. // Check printer compatibility if sliced_for_model is available in metadata
  5407. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  5408. const printerModel = mapModelCode(printer.model);
  5409. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  5410. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  5411. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  5412. }
  5413. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  5414. }}
  5415. />
  5416. )}
  5417. {/* Print Modal (after upload) */}
  5418. {printAfterUpload && (
  5419. <PrintModal
  5420. mode="reprint"
  5421. libraryFileId={printAfterUpload.id}
  5422. archiveName={printAfterUpload.filename}
  5423. initialSelectedPrinterIds={[printer.id]}
  5424. onClose={() => setPrintAfterUpload(null)}
  5425. onSuccess={() => setPrintAfterUpload(null)}
  5426. cleanupLibraryAfterDispatch
  5427. />
  5428. )}
  5429. {/* MQTT Debug Modal */}
  5430. {showMQTTDebug && (
  5431. <MQTTDebugModal
  5432. printerId={printer.id}
  5433. printerName={printer.name}
  5434. onClose={() => setShowMQTTDebug(false)}
  5435. />
  5436. )}
  5437. {showDiagnostic && (
  5438. <ConnectionDiagnosticModal
  5439. printerId={printer.id}
  5440. printerName={printer.name}
  5441. onClose={() => setShowDiagnostic(false)}
  5442. />
  5443. )}
  5444. {showPrinterInfo && (
  5445. <PrinterInfoModal
  5446. printer={printer}
  5447. status={status}
  5448. totalPrintHours={maintenanceInfo?.total_print_hours}
  5449. onClose={closePrinterInfo}
  5450. />
  5451. )}
  5452. {/* Plate Check Result Modal */}
  5453. {plateCheckResult && (
  5454. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  5455. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  5456. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  5457. <div className="flex items-center gap-2">
  5458. {plateCheckResult.needs_calibration ? (
  5459. <ScanSearch className="w-5 h-5 text-blue-500" />
  5460. ) : plateCheckResult.is_empty ? (
  5461. <CheckCircle className="w-5 h-5 text-green-500" />
  5462. ) : (
  5463. <XCircle className="w-5 h-5 text-yellow-500" />
  5464. )}
  5465. <h2 className="text-lg font-semibold text-white">
  5466. Build Plate Check
  5467. </h2>
  5468. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  5469. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  5470. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  5471. </span>
  5472. )}
  5473. </div>
  5474. <button
  5475. onClick={() => closePlateCheckModal()}
  5476. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  5477. >
  5478. <X className="w-5 h-5" />
  5479. </button>
  5480. </div>
  5481. <div className="p-4 space-y-4">
  5482. {plateCheckResult.needs_calibration ? (
  5483. <>
  5484. <div className="p-3 rounded-lg bg-blue-500/20 border border-blue-500/50">
  5485. <p className="font-medium text-blue-400">
  5486. {t('printers.plateDetection.calibrationRequired')}
  5487. </p>
  5488. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  5489. </div>
  5490. <div className="text-sm text-bambu-gray space-y-2">
  5491. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  5492. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  5493. </div>
  5494. </>
  5495. ) : (
  5496. <>
  5497. <div className={`p-3 rounded-lg ${plateCheckResult.is_empty ? 'bg-green-500/20 border border-green-500/50' : 'bg-yellow-500/20 border border-yellow-500/50'}`}>
  5498. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-400' : 'text-yellow-400'}`}>
  5499. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  5500. </p>
  5501. <p className="text-sm text-bambu-gray mt-1">
  5502. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  5503. </p>
  5504. </div>
  5505. {plateCheckResult.debug_image_url && (
  5506. <div>
  5507. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  5508. <img
  5509. src={plateCheckResult.debug_image_url}
  5510. alt={t('printers.plateDetection.analysisPreview')}
  5511. className="w-full rounded-lg border border-bambu-dark-tertiary"
  5512. />
  5513. <p className="text-xs text-bambu-gray mt-2">
  5514. {t('printers.plateDetection.analysisLegend')}
  5515. </p>
  5516. </div>
  5517. )}
  5518. <p className="text-xs text-bambu-gray">
  5519. {plateCheckResult.message}
  5520. </p>
  5521. </>
  5522. )}
  5523. {/* Saved References Grid */}
  5524. {plateReferences && plateReferences.references.length > 0 && (
  5525. <div className="mt-4">
  5526. <div className="flex items-center gap-2 mb-2">
  5527. <p className="text-sm font-medium text-white shrink-0">
  5528. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  5529. </p>
  5530. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5531. </div>
  5532. <div className="grid grid-cols-5 gap-2">
  5533. {plateReferences.references.map((ref) => (
  5534. <div key={ref.index} className="relative group">
  5535. <img
  5536. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  5537. alt={ref.label || `Reference ${ref.index + 1}`}
  5538. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  5539. />
  5540. {/* Delete button */}
  5541. <button
  5542. onClick={() => handleDeleteRef(ref.index)}
  5543. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  5544. title={t('printers.plateDetection.deleteReference')}
  5545. >
  5546. <X className="w-3 h-3 text-white" />
  5547. </button>
  5548. {/* Label */}
  5549. {editingRefLabel?.index === ref.index ? (
  5550. <input
  5551. type="text"
  5552. value={editingRefLabel.label}
  5553. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  5554. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  5555. onKeyDown={(e) => {
  5556. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  5557. if (e.key === 'Escape') setEditingRefLabel(null);
  5558. }}
  5559. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  5560. autoFocus
  5561. placeholder={t('printers.plateDetection.labelPlaceholder')}
  5562. />
  5563. ) : (
  5564. <p
  5565. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  5566. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  5567. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  5568. >
  5569. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  5570. </p>
  5571. )}
  5572. {/* Timestamp */}
  5573. <p className="text-[10px] text-bambu-gray/60">
  5574. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  5575. </p>
  5576. </div>
  5577. ))}
  5578. </div>
  5579. </div>
  5580. )}
  5581. {/* ROI Editor */}
  5582. {!plateCheckResult.needs_calibration && (
  5583. <div className="mt-4">
  5584. <div className="flex items-center justify-between mb-2">
  5585. <div className="flex min-w-0 flex-1 items-center gap-2">
  5586. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  5587. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5588. </div>
  5589. {!editingRoi ? (
  5590. <Button
  5591. variant="ghost"
  5592. size="sm"
  5593. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  5594. >
  5595. <Pencil className="w-3 h-3 mr-1" />
  5596. {t('common.edit')}
  5597. </Button>
  5598. ) : (
  5599. <div className="flex gap-1">
  5600. <Button
  5601. variant="ghost"
  5602. size="sm"
  5603. onClick={() => setEditingRoi(null)}
  5604. disabled={isSavingRoi}
  5605. >
  5606. {t('common.cancel')}
  5607. </Button>
  5608. <Button
  5609. size="sm"
  5610. onClick={handleSaveRoi}
  5611. disabled={isSavingRoi}
  5612. >
  5613. {isSavingRoi ? <Loader2 className="w-3 h-3 animate-spin" /> : t('common.save')}
  5614. </Button>
  5615. </div>
  5616. )}
  5617. </div>
  5618. {editingRoi ? (
  5619. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  5620. <div className="grid grid-cols-2 gap-3">
  5621. <div>
  5622. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  5623. <input
  5624. type="range"
  5625. min="0"
  5626. max="0.9"
  5627. step="0.01"
  5628. value={editingRoi.x}
  5629. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  5630. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5631. />
  5632. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  5633. </div>
  5634. <div>
  5635. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  5636. <input
  5637. type="range"
  5638. min="0"
  5639. max="0.9"
  5640. step="0.01"
  5641. value={editingRoi.y}
  5642. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  5643. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5644. />
  5645. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  5646. </div>
  5647. <div>
  5648. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  5649. <input
  5650. type="range"
  5651. min="0.1"
  5652. max="1"
  5653. step="0.01"
  5654. value={editingRoi.w}
  5655. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  5656. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5657. />
  5658. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  5659. </div>
  5660. <div>
  5661. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  5662. <input
  5663. type="range"
  5664. min="0.1"
  5665. max="1"
  5666. step="0.01"
  5667. value={editingRoi.h}
  5668. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  5669. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5670. />
  5671. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  5672. </div>
  5673. </div>
  5674. <p className="text-xs text-bambu-gray">
  5675. {t('printers.roi.instruction')}
  5676. </p>
  5677. </div>
  5678. ) : (
  5679. <p className="text-xs text-bambu-gray">
  5680. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  5681. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  5682. </p>
  5683. )}
  5684. </div>
  5685. )}
  5686. </div>
  5687. <div className="flex justify-end gap-2 p-4">
  5688. {plateCheckResult.needs_calibration ? (
  5689. <>
  5690. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  5691. {t('common.cancel')}
  5692. </Button>
  5693. <Button
  5694. onClick={() => handleCalibratePlate()}
  5695. disabled={isCalibrating}
  5696. >
  5697. {isCalibrating ? (
  5698. <>
  5699. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  5700. Calibrating...
  5701. </>
  5702. ) : (
  5703. 'Calibrate Empty Plate'
  5704. )}
  5705. </Button>
  5706. </>
  5707. ) : (
  5708. <>
  5709. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  5710. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  5711. </Button>
  5712. <Button onClick={() => closePlateCheckModal()}>
  5713. Close
  5714. </Button>
  5715. </>
  5716. )}
  5717. </div>
  5718. </div>
  5719. </div>
  5720. )}
  5721. {/* Power On Confirmation */}
  5722. {showPowerOnConfirm && smartPlug && (
  5723. <ConfirmModal
  5724. title={t('printers.confirm.powerOnTitle')}
  5725. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  5726. confirmText={t('printers.confirm.powerOnButton')}
  5727. variant="default"
  5728. onConfirm={() => {
  5729. powerControlMutation.mutate('on');
  5730. setShowPowerOnConfirm(false);
  5731. }}
  5732. onCancel={() => setShowPowerOnConfirm(false)}
  5733. />
  5734. )}
  5735. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  5736. disconnects MQTT, which stops progress tracking + completion
  5737. notifications for the in-flight job. Idle / FINISH / FAILED states
  5738. skip this dialog and toggle directly. */}
  5739. {confirmMaintenanceEnter && (
  5740. <ConfirmModal
  5741. title={t('printers.maintenance.confirmMidPrintTitle')}
  5742. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  5743. confirmText={t('printers.maintenance.menuEnter')}
  5744. variant="danger"
  5745. onConfirm={() => {
  5746. maintenanceMutation.mutate(false);
  5747. setConfirmMaintenanceEnter(false);
  5748. }}
  5749. onCancel={() => setConfirmMaintenanceEnter(false)}
  5750. />
  5751. )}
  5752. {/* Power Off Confirmation */}
  5753. {showPowerOffConfirm && smartPlug && (
  5754. <ConfirmModal
  5755. title={t('printers.confirm.powerOffTitle')}
  5756. message={
  5757. status?.state === 'RUNNING'
  5758. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  5759. : t('printers.confirm.powerOffMessage', { name: printer.name })
  5760. }
  5761. confirmText={t('printers.confirm.powerOffButton')}
  5762. variant="danger"
  5763. onConfirm={() => {
  5764. powerControlMutation.mutate('off');
  5765. setShowPowerOffConfirm(false);
  5766. }}
  5767. onCancel={() => setShowPowerOffConfirm(false)}
  5768. />
  5769. )}
  5770. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  5771. {haToggleConfirm && (
  5772. <ConfirmModal
  5773. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  5774. message={
  5775. status?.state === 'RUNNING'
  5776. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5777. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5778. }
  5779. confirmText={t('printers.confirm.haToggleButton')}
  5780. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  5781. onConfirm={() => {
  5782. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  5783. setHaToggleConfirm(null);
  5784. }}
  5785. onCancel={() => setHaToggleConfirm(null)}
  5786. />
  5787. )}
  5788. {/* Stop Print Confirmation */}
  5789. {showStopConfirm && (
  5790. <ConfirmModal
  5791. title={t('printers.confirm.stopTitle')}
  5792. message={t('printers.confirm.stopMessage', { name: printer.name })}
  5793. confirmText={t('printers.confirm.stopButton')}
  5794. variant="danger"
  5795. onConfirm={() => {
  5796. stopPrintMutation.mutate();
  5797. setShowStopConfirm(false);
  5798. }}
  5799. onCancel={() => setShowStopConfirm(false)}
  5800. />
  5801. )}
  5802. {/* Pause Print Confirmation */}
  5803. {showPauseConfirm && (
  5804. <ConfirmModal
  5805. title={t('printers.confirm.pauseTitle')}
  5806. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  5807. confirmText={t('printers.confirm.pauseButton')}
  5808. variant="default"
  5809. onConfirm={() => {
  5810. pausePrintMutation.mutate();
  5811. setShowPauseConfirm(false);
  5812. }}
  5813. onCancel={() => setShowPauseConfirm(false)}
  5814. />
  5815. )}
  5816. {/* Resume Print Confirmation */}
  5817. {showResumeConfirm && (
  5818. <ConfirmModal
  5819. title={t('printers.confirm.resumeTitle')}
  5820. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  5821. confirmText={t('printers.confirm.resumeButton')}
  5822. variant="default"
  5823. onConfirm={() => {
  5824. resumePrintMutation.mutate();
  5825. setShowResumeConfirm(false);
  5826. }}
  5827. onCancel={() => setShowResumeConfirm(false)}
  5828. />
  5829. )}
  5830. {/* Bed Jog — not-homed warning (Studio-style) */}
  5831. {showNotHomedModal && (
  5832. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
  5833. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5">
  5834. <div className="flex items-start gap-3 mb-4">
  5835. <AlertTriangle className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
  5836. <div>
  5837. <h3 className="text-sm font-semibold text-white mb-1">
  5838. {t('printers.bedJog.notHomedTitle')}
  5839. </h3>
  5840. <p className="text-xs text-bambu-gray leading-relaxed">
  5841. {t('printers.bedJog.notHomedMessage')}
  5842. </p>
  5843. </div>
  5844. </div>
  5845. <div className="flex flex-col gap-2">
  5846. <button
  5847. onClick={() => {
  5848. homeAxesMutation.mutate('all');
  5849. setShowNotHomedModal(null);
  5850. }}
  5851. className="w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors"
  5852. >
  5853. {t('printers.bedJog.homeZ')}
  5854. </button>
  5855. <button
  5856. onClick={() => {
  5857. const d = showNotHomedModal.distance;
  5858. try { sessionStorage.setItem(`bambuddy.bedJog.warned.${printer.id}`, '1'); } catch { /* ignore */ }
  5859. bedJogMutation.mutate({ distance: d, force: true });
  5860. setShowNotHomedModal(null);
  5861. }}
  5862. className="w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors"
  5863. >
  5864. {t('printers.bedJog.moveAnyway')}
  5865. </button>
  5866. <button
  5867. onClick={() => setShowNotHomedModal(null)}
  5868. className="w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors"
  5869. >
  5870. {t('common.cancel')}
  5871. </button>
  5872. </div>
  5873. </div>
  5874. </div>
  5875. )}
  5876. {/* Skip Objects Modal */}
  5877. <SkipObjectsModal
  5878. printerId={printer.id}
  5879. isOpen={showSkipObjectsModal}
  5880. onClose={() => setShowSkipObjectsModal(false)}
  5881. />
  5882. {/* HMS Error Modal */}
  5883. {showHMSModal && (
  5884. <HMSErrorModal
  5885. printerName={printer.name}
  5886. errors={status?.hms_errors || []}
  5887. onClose={() => setShowHMSModal(false)}
  5888. printerId={printer.id}
  5889. hasPermission={hasPermission}
  5890. />
  5891. )}
  5892. {/* AMS Filament Backup status / control modal (#1762) */}
  5893. {amsBackupModalOpen && status && (
  5894. <AmsBackupModal
  5895. isOpen={amsBackupModalOpen}
  5896. state={status.ams_filament_backup}
  5897. amsUnits={status.ams}
  5898. amsExtruderMap={status.ams_extruder_map}
  5899. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  5900. canToggle={hasPermission('printers:control')}
  5901. pending={setAmsBackupMutation.isPending}
  5902. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  5903. onClose={() => setAmsBackupModalOpen(false)}
  5904. />
  5905. )}
  5906. {/* AMS History Modal */}
  5907. {amsHistoryModal && (
  5908. <AMSHistoryModal
  5909. isOpen={!!amsHistoryModal}
  5910. onClose={() => setAmsHistoryModal(null)}
  5911. printerId={printer.id}
  5912. printerName={printer.name}
  5913. amsId={amsHistoryModal.amsId}
  5914. amsLabel={amsHistoryModal.amsLabel}
  5915. initialMode={amsHistoryModal.mode}
  5916. thresholds={amsThresholds}
  5917. />
  5918. )}
  5919. {/* Heater History Modal (nozzle / bed / chamber) */}
  5920. {heaterHistoryModal && (
  5921. <HeaterHistoryModal
  5922. isOpen={!!heaterHistoryModal}
  5923. onClose={() => setHeaterHistoryModal(null)}
  5924. printerId={printer.id}
  5925. printerName={printer.name}
  5926. initialKind={heaterHistoryModal.initialKind}
  5927. availableKinds={heaterHistoryModal.availableKinds}
  5928. />
  5929. )}
  5930. {/* Link Spool Modal */}
  5931. {linkSpoolModal && (
  5932. <LinkSpoolModal
  5933. isOpen={!!linkSpoolModal}
  5934. onClose={() => setLinkSpoolModal(null)}
  5935. tagUid={linkSpoolModal.tagUid}
  5936. trayUuid={linkSpoolModal.trayUuid}
  5937. printerId={linkSpoolModal.printerId}
  5938. amsId={linkSpoolModal.amsId}
  5939. trayId={linkSpoolModal.trayId}
  5940. />
  5941. )}
  5942. {/* Assign Spool Modal */}
  5943. {assignSpoolModal && (
  5944. <AssignSpoolModal
  5945. isOpen={!!assignSpoolModal}
  5946. onClose={() => setAssignSpoolModal(null)}
  5947. printerId={assignSpoolModal.printerId}
  5948. amsId={assignSpoolModal.amsId}
  5949. trayId={assignSpoolModal.trayId}
  5950. trayInfo={assignSpoolModal.trayInfo}
  5951. spoolmanEnabled={!!spoolmanEnabled}
  5952. />
  5953. )}
  5954. {/* Configure AMS Slot Modal */}
  5955. {configureSlotModal && (
  5956. <ConfigureAmsSlotModal
  5957. isOpen={!!configureSlotModal}
  5958. onClose={() => setConfigureSlotModal(null)}
  5959. printerId={printer.id}
  5960. slotInfo={configureSlotModal}
  5961. printerModel={mapModelCode(printer.model) || undefined}
  5962. onSuccess={() => {
  5963. // Refresh slot presets to show updated profile name
  5964. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  5965. // Printer status will update automatically via WebSocket when AMS data changes
  5966. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  5967. }}
  5968. />
  5969. )}
  5970. {/* Edit Printer Modal */}
  5971. {showEditModal && (
  5972. <EditPrinterModal
  5973. printer={printer}
  5974. onClose={() => setShowEditModal(false)}
  5975. />
  5976. )}
  5977. {/* Firmware Update Modal */}
  5978. {showFirmwareModal && firmwareInfo && (
  5979. <FirmwareUpdateModal
  5980. printer={printer}
  5981. firmwareInfo={firmwareInfo}
  5982. onClose={() => setShowFirmwareModal(false)}
  5983. />
  5984. )}
  5985. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  5986. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  5987. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  5988. const sliderMin = 35;
  5989. const sliderMax = maxTemp + 10;
  5990. return (
  5991. <>
  5992. {/* Backdrop */}
  5993. <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
  5994. {/* Popover */}
  5995. <div
  5996. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  5997. style={{
  5998. top: dryingPopoverPos.top,
  5999. left: dryingPopoverPos.left,
  6000. // Cap to the space between the popover's top and the bottom
  6001. // viewport margin (8px, matching computePopoverPosition's
  6002. // margin). When the popover is taller than that space — short
  6003. // viewport, landscape phone, zoomed-in — the body scrolls and
  6004. // the footer stays pinned, so the Start button is always
  6005. // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
  6006. // Safari's bottom toolbar overlay doesn't clip the footer
  6007. // (#1669, iPhone 17 Safari).
  6008. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6009. }}
  6010. onClick={e => e.stopPropagation()}
  6011. >
  6012. {/* Header */}
  6013. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6014. <Flame className="w-3.5 h-3.5 text-bambu-green" />
  6015. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6016. </div>
  6017. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6018. {/* Body */}
  6019. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6020. {/* Filament type select */}
  6021. <div>
  6022. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6023. <ToolbarDropdown
  6024. value={dryingFilament}
  6025. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6026. onChange={fil => {
  6027. setDryingFilament(fil);
  6028. const preset = dryingPresets[fil];
  6029. if (preset) {
  6030. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6031. setDryingTemp(preset[key]);
  6032. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6033. }
  6034. }}
  6035. fullWidth
  6036. />
  6037. </div>
  6038. {/* Temperature */}
  6039. <div>
  6040. <div className="flex items-center justify-between mb-1">
  6041. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6042. <div className="flex items-center gap-1">
  6043. <input
  6044. type="number"
  6045. min={45}
  6046. max={maxTemp}
  6047. value={dryingTemp}
  6048. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6049. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6050. />
  6051. <span className="text-[10px] text-bambu-gray">°C</span>
  6052. </div>
  6053. </div>
  6054. <input
  6055. type="range"
  6056. min={sliderMin}
  6057. max={sliderMax}
  6058. value={dryingTemp}
  6059. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6060. className="w-full h-1 accent-bambu-green cursor-pointer"
  6061. />
  6062. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6063. <span>45°C</span>
  6064. <span>{maxTemp}°C</span>
  6065. </div>
  6066. </div>
  6067. {/* Duration */}
  6068. <div>
  6069. <div className="flex items-center justify-between mb-1">
  6070. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6071. <div className="flex items-center gap-1">
  6072. <input
  6073. type="number"
  6074. min={1}
  6075. max={24}
  6076. value={dryingDuration}
  6077. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6078. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6079. />
  6080. <span className="text-[10px] text-bambu-gray">{t('printers.drying.hours')}</span>
  6081. </div>
  6082. </div>
  6083. <input
  6084. type="range"
  6085. min={1}
  6086. max={24}
  6087. value={dryingDuration}
  6088. onChange={e => setDryingDuration(Number(e.target.value))}
  6089. className="w-full h-1 accent-bambu-green cursor-pointer"
  6090. />
  6091. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6092. <span>1h</span>
  6093. <span>24h</span>
  6094. </div>
  6095. </div>
  6096. {/* Rotate tray */}
  6097. <button
  6098. type="button"
  6099. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6100. aria-pressed={dryingRotateTray}
  6101. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors ${
  6102. dryingRotateTray
  6103. ? 'bg-bambu-green border-bambu-green text-white'
  6104. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  6105. }`}
  6106. >
  6107. {t('printers.drying.rotateTray')}
  6108. </button>
  6109. </div>
  6110. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6111. {/* Footer */}
  6112. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6113. <button
  6114. onClick={() => {
  6115. if (dryingPopoverAmsId !== null) {
  6116. startDryingMutation.mutate({ amsId: dryingPopoverAmsId, temp: dryingTemp, duration: dryingDuration, filament: dryingFilament, rotateTray: dryingRotateTray });
  6117. }
  6118. }}
  6119. disabled={startDryingMutation.isPending}
  6120. className="w-full py-1.5 bg-bambu-green hover:bg-bambu-green/80 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50"
  6121. >
  6122. {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
  6123. </button>
  6124. </div>
  6125. </div>
  6126. </>
  6127. );
  6128. })()}
  6129. </Card>
  6130. );
  6131. }
  6132. export function AddPrinterModal({
  6133. onClose,
  6134. onAdd,
  6135. existingSerials,
  6136. }: {
  6137. onClose: () => void;
  6138. onAdd: (data: PrinterCreate) => void;
  6139. existingSerials: string[];
  6140. }) {
  6141. const { t } = useTranslation();
  6142. const [form, setForm] = useState<PrinterCreate>({
  6143. name: '',
  6144. serial_number: '',
  6145. ip_address: '',
  6146. access_code: '',
  6147. model: '',
  6148. location: '',
  6149. auto_archive: true,
  6150. });
  6151. // Discovery state
  6152. const [discovering, setDiscovering] = useState(false);
  6153. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  6154. const [discoveryError, setDiscoveryError] = useState('');
  6155. const [hasScanned, setHasScanned] = useState(false);
  6156. const [isDocker, setIsDocker] = useState(false);
  6157. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  6158. const [subnet, setSubnet] = useState('');
  6159. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  6160. // text input so users can scan a subnet Bambuddy isn't directly on
  6161. // (printer behind a router on a different L3 segment — SSDP multicast
  6162. // won't cross that boundary, only an active unicast scan will). #1564
  6163. const [customSubnet, setCustomSubnet] = useState('');
  6164. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  6165. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  6166. const [showDiagnostic, setShowDiagnostic] = useState(false);
  6167. // Setup-time pre-flight: run the connection diagnostic on save and warn
  6168. // (not block) when checks fail, so the user doesn't add a printer that
  6169. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  6170. // failed result awaiting an explicit "save anyway".
  6171. const [checkingSave, setCheckingSave] = useState(false);
  6172. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6173. // Fetch discovery info on mount + restore the last custom CIDR the user
  6174. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  6175. // time they open this modal).
  6176. useEffect(() => {
  6177. discoveryApi.getInfo().then(info => {
  6178. setIsDocker(info.is_docker);
  6179. if (info.subnets.length > 0) {
  6180. setDetectedSubnets(info.subnets);
  6181. setSubnet(info.subnets[0]);
  6182. }
  6183. }).catch(() => {
  6184. // Ignore errors, assume not Docker
  6185. });
  6186. try {
  6187. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  6188. if (saved) setCustomSubnet(saved);
  6189. } catch {
  6190. // localStorage unavailable (private mode, quota); recall is opportunistic
  6191. }
  6192. }, []);
  6193. // Filter out already-added printers
  6194. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  6195. const handleAddSubmit = async (e: React.FormEvent) => {
  6196. e.preventDefault();
  6197. setCheckingSave(true);
  6198. try {
  6199. const result = await api.diagnoseConnection({
  6200. ip_address: form.ip_address.trim(),
  6201. serial_number: form.serial_number.trim() || undefined,
  6202. access_code: form.access_code || undefined,
  6203. });
  6204. if (result.checks.some((c) => c.status === 'fail')) {
  6205. setSaveWarning(result);
  6206. return;
  6207. }
  6208. } catch {
  6209. // Diagnostic infrastructure failed — never block the save on it.
  6210. } finally {
  6211. setCheckingSave(false);
  6212. }
  6213. onAdd(form);
  6214. };
  6215. const startDiscovery = async () => {
  6216. setDiscoveryError('');
  6217. setDiscovered([]);
  6218. setDiscovering(true);
  6219. setHasScanned(false);
  6220. setScanProgress({ scanned: 0, total: 0 });
  6221. // Native installs fall back to subnet scanning when the user picks
  6222. // "Custom" — SSDP can't reach a printer on a different L3 segment
  6223. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  6224. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  6225. const wantsSubnetScan = isDocker || useCustomSubnet;
  6226. if (wantsSubnetScan && useCustomSubnet) {
  6227. try {
  6228. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  6229. } catch {
  6230. // localStorage write best-effort; user just retypes next time
  6231. }
  6232. }
  6233. try {
  6234. if (wantsSubnetScan) {
  6235. await discoveryApi.startSubnetScan(scanCidr);
  6236. // Poll for scan status and results
  6237. const pollInterval = setInterval(async () => {
  6238. try {
  6239. const status = await discoveryApi.getScanStatus();
  6240. setScanProgress({ scanned: status.scanned, total: status.total });
  6241. const printers = await discoveryApi.getDiscoveredPrinters();
  6242. setDiscovered(printers);
  6243. if (!status.running) {
  6244. clearInterval(pollInterval);
  6245. setDiscovering(false);
  6246. setHasScanned(true);
  6247. }
  6248. } catch (e) {
  6249. console.error('Failed to get scan status:', e);
  6250. }
  6251. }, 500);
  6252. } else {
  6253. // Use SSDP discovery for native installs
  6254. await discoveryApi.startDiscovery(10);
  6255. // Poll for discovered printers every second
  6256. const pollInterval = setInterval(async () => {
  6257. try {
  6258. const printers = await discoveryApi.getDiscoveredPrinters();
  6259. setDiscovered(printers);
  6260. } catch (e) {
  6261. console.error('Failed to get discovered printers:', e);
  6262. }
  6263. }, 1000);
  6264. // Stop after 10 seconds
  6265. setTimeout(async () => {
  6266. clearInterval(pollInterval);
  6267. try {
  6268. await discoveryApi.stopDiscovery();
  6269. } catch {
  6270. // Ignore stop errors
  6271. }
  6272. setDiscovering(false);
  6273. setHasScanned(true);
  6274. // Final fetch
  6275. try {
  6276. const printers = await discoveryApi.getDiscoveredPrinters();
  6277. setDiscovered(printers);
  6278. } catch (e) {
  6279. console.error('Failed to get final discovered printers:', e);
  6280. }
  6281. }, 10000);
  6282. }
  6283. } catch (e) {
  6284. console.error('Failed to start discovery:', e);
  6285. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  6286. setDiscovering(false);
  6287. setHasScanned(true);
  6288. }
  6289. };
  6290. // Reuse module-level mapModelCode
  6291. const selectPrinter = (printer: DiscoveredPrinter) => {
  6292. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  6293. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  6294. setForm({
  6295. ...form,
  6296. name: printer.name || '',
  6297. serial_number: serialNumber,
  6298. ip_address: printer.ip_address,
  6299. model: mapModelCode(printer.model),
  6300. });
  6301. // Clear discovery results after selection
  6302. setDiscovered([]);
  6303. };
  6304. // Cleanup discovery on unmount
  6305. useEffect(() => {
  6306. return () => {
  6307. discoveryApi.stopDiscovery().catch(() => {});
  6308. discoveryApi.stopSubnetScan().catch(() => {});
  6309. };
  6310. }, []);
  6311. // Close on Escape key
  6312. useEffect(() => {
  6313. const handleKeyDown = (e: KeyboardEvent) => {
  6314. if (e.key === 'Escape') onClose();
  6315. };
  6316. window.addEventListener('keydown', handleKeyDown);
  6317. return () => window.removeEventListener('keydown', handleKeyDown);
  6318. }, [onClose]);
  6319. return (
  6320. <>
  6321. <div
  6322. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6323. onClick={onClose}
  6324. >
  6325. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6326. <CardContent>
  6327. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  6328. {/* Discovery Section */}
  6329. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  6330. {/* Subnet picker — always visible. The dropdown lists detected
  6331. interface subnets and a "Custom..." sentinel that reveals
  6332. a CIDR text input for printers on a different L3 segment
  6333. (router, VLAN, etc.). #1564 */}
  6334. <div className="mb-3">
  6335. <label className="block text-sm text-bambu-gray mb-1">
  6336. {t('printers.discovery.subnetToScan')}
  6337. </label>
  6338. {detectedSubnets.length > 0 ? (
  6339. <select
  6340. className="w-full 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"
  6341. value={useCustomSubnet ? '__custom__' : subnet}
  6342. onChange={(e) => {
  6343. if (e.target.value === '__custom__') {
  6344. setUseCustomSubnet(true);
  6345. } else {
  6346. setUseCustomSubnet(false);
  6347. setSubnet(e.target.value);
  6348. }
  6349. }}
  6350. disabled={discovering}
  6351. >
  6352. {detectedSubnets.map(s => (
  6353. <option key={s} value={s}>{s}</option>
  6354. ))}
  6355. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  6356. </select>
  6357. ) : (
  6358. <input
  6359. type="text"
  6360. className="w-full 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"
  6361. value={subnet}
  6362. onChange={(e) => setSubnet(e.target.value)}
  6363. placeholder="192.168.1.0/24"
  6364. disabled={discovering}
  6365. />
  6366. )}
  6367. {useCustomSubnet && (
  6368. <input
  6369. type="text"
  6370. aria-label={t('printers.discovery.customSubnetLabel')}
  6371. className="mt-2 w-full 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"
  6372. value={customSubnet}
  6373. onChange={(e) => setCustomSubnet(e.target.value)}
  6374. placeholder="10.1.1.0/24"
  6375. disabled={discovering}
  6376. />
  6377. )}
  6378. <p className="mt-1 text-xs text-bambu-gray">
  6379. {isDocker
  6380. ? t('printers.discovery.dockerNote')
  6381. : t('printers.discovery.customSubnetNote')}
  6382. </p>
  6383. </div>
  6384. <Button
  6385. type="button"
  6386. variant="secondary"
  6387. onClick={startDiscovery}
  6388. disabled={discovering}
  6389. className="w-full"
  6390. >
  6391. {discovering ? (
  6392. <>
  6393. <Loader2 className="w-4 h-4 animate-spin" />
  6394. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  6395. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  6396. : t('printers.discovery.scanning')}
  6397. </>
  6398. ) : (
  6399. <>
  6400. <Search className="w-4 h-4" />
  6401. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  6402. </>
  6403. )}
  6404. </Button>
  6405. {discoveryError && (
  6406. <div className="mt-2 text-sm text-red-400">{discoveryError}</div>
  6407. )}
  6408. {newPrinters.length > 0 && (
  6409. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  6410. {newPrinters.map((printer) => (
  6411. <div
  6412. key={printer.serial}
  6413. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  6414. onClick={() => selectPrinter(printer)}
  6415. >
  6416. <div className="min-w-0 flex-1">
  6417. <p className="font-medium text-white text-sm truncate">
  6418. {printer.name || printer.serial}
  6419. </p>
  6420. <p className="text-xs text-bambu-gray truncate">
  6421. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  6422. {printer.serial.startsWith('unknown-') && (
  6423. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  6424. )}
  6425. </p>
  6426. </div>
  6427. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  6428. </div>
  6429. ))}
  6430. </div>
  6431. )}
  6432. {discovering && (
  6433. <p className="mt-2 text-sm text-bambu-gray text-center">
  6434. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  6435. </p>
  6436. )}
  6437. {hasScanned && !discovering && discovered.length === 0 && (
  6438. <p className="mt-2 text-sm text-bambu-gray text-center">
  6439. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  6440. </p>
  6441. )}
  6442. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  6443. <p className="mt-2 text-sm text-bambu-gray text-center">
  6444. {t('printers.discovery.allConfigured')}
  6445. </p>
  6446. )}
  6447. </div>
  6448. <form onSubmit={handleAddSubmit} className="space-y-4">
  6449. <div>
  6450. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6451. <input
  6452. type="text"
  6453. required
  6454. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6455. value={form.name}
  6456. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6457. placeholder={t('printers.modal.myPrinter')}
  6458. />
  6459. </div>
  6460. <div>
  6461. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6462. <input
  6463. type="text"
  6464. required
  6465. pattern="(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)"
  6466. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6467. value={form.ip_address}
  6468. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6469. placeholder="192.168.1.100 or printer.local"
  6470. />
  6471. </div>
  6472. <div>
  6473. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6474. <input
  6475. type="text"
  6476. required
  6477. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6478. value={form.serial_number}
  6479. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  6480. placeholder="01P00A000000000"
  6481. />
  6482. </div>
  6483. <div>
  6484. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6485. <input
  6486. type="password"
  6487. required
  6488. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6489. value={form.access_code}
  6490. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6491. placeholder={t('printers.modal.fromPrinterSettings')}
  6492. />
  6493. </div>
  6494. <div>
  6495. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  6496. <select
  6497. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6498. value={form.model || ''}
  6499. onChange={(e) => setForm({ ...form, model: e.target.value })}
  6500. >
  6501. <option value="">{t('printers.modal.selectModel')}</option>
  6502. <optgroup label="A1 Series">
  6503. <option value="A1">A1</option>
  6504. <option value="A1 Mini">A1 Mini</option>
  6505. </optgroup>
  6506. <optgroup label="A2 Series">
  6507. <option value="A2L">A2L</option>
  6508. </optgroup>
  6509. <optgroup label="H2 Series">
  6510. <option value="H2C">H2C</option>
  6511. <option value="H2D">H2D</option>
  6512. <option value="H2D Pro">H2D Pro</option>
  6513. <option value="H2S">H2S</option>
  6514. </optgroup>
  6515. <optgroup label="P Series">
  6516. <option value="P1P">P1P</option>
  6517. <option value="P1S">P1S</option>
  6518. <option value="P2S">P2S</option>
  6519. </optgroup>
  6520. <optgroup label="X1 Series">
  6521. <option value="X1">X1</option>
  6522. <option value="X1C">X1 Carbon</option>
  6523. <option value="X1E">X1E</option>
  6524. </optgroup>
  6525. <optgroup label="X2 Series">
  6526. <option value="X2D">X2D</option>
  6527. </optgroup>
  6528. </select>
  6529. </div>
  6530. <div>
  6531. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  6532. <input
  6533. type="text"
  6534. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6535. value={form.location || ''}
  6536. onChange={(e) => setForm({ ...form, location: e.target.value })}
  6537. placeholder={t('printers.modal.locationPlaceholder')}
  6538. />
  6539. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  6540. </div>
  6541. <div className="flex items-center gap-2">
  6542. <input
  6543. type="checkbox"
  6544. id="auto_archive"
  6545. checked={form.auto_archive}
  6546. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  6547. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  6548. />
  6549. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  6550. {t('printers.modal.autoArchiveLabel')}
  6551. </label>
  6552. </div>
  6553. <button
  6554. type="button"
  6555. onClick={() => setShowDiagnostic(true)}
  6556. disabled={!form.ip_address.trim()}
  6557. className="w-full flex items-center justify-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white disabled:opacity-40 disabled:cursor-not-allowed border border-bambu-dark-tertiary rounded-lg transition-colors"
  6558. >
  6559. <Stethoscope className="w-4 h-4" />
  6560. {t('diagnostic.runButton')}
  6561. </button>
  6562. {saveWarning ? (
  6563. <div className="rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3">
  6564. <div className="flex items-start gap-2">
  6565. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400" />
  6566. <p className="text-sm text-amber-300">{t('printers.addPreflight.warning')}</p>
  6567. </div>
  6568. <DiagnosticChecklist result={saveWarning} />
  6569. <div className="flex gap-3">
  6570. <Button
  6571. type="button"
  6572. variant="secondary"
  6573. onClick={() => setSaveWarning(null)}
  6574. className="flex-1"
  6575. >
  6576. {t('printers.addPreflight.back')}
  6577. </Button>
  6578. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  6579. {t('printers.addPreflight.saveAnyway')}
  6580. </Button>
  6581. </div>
  6582. </div>
  6583. ) : (
  6584. <div className="flex gap-3 pt-2">
  6585. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  6586. {t('common.cancel')}
  6587. </Button>
  6588. <Button type="submit" disabled={checkingSave} className="flex-1">
  6589. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  6590. </Button>
  6591. </div>
  6592. )}
  6593. </form>
  6594. </CardContent>
  6595. </Card>
  6596. </div>
  6597. {showDiagnostic && (
  6598. <ConnectionDiagnosticModal
  6599. connection={{
  6600. ip_address: form.ip_address.trim(),
  6601. serial_number: form.serial_number.trim() || undefined,
  6602. access_code: form.access_code || undefined,
  6603. }}
  6604. printerName={form.name || null}
  6605. onClose={() => setShowDiagnostic(false)}
  6606. />
  6607. )}
  6608. </>
  6609. );
  6610. }
  6611. function FirmwareUpdateModal({
  6612. printer,
  6613. firmwareInfo,
  6614. onClose,
  6615. }: {
  6616. printer: Printer;
  6617. firmwareInfo: FirmwareUpdateInfo;
  6618. onClose: () => void;
  6619. }) {
  6620. const { t } = useTranslation();
  6621. const queryClient = useQueryClient();
  6622. const { showToast } = useToast();
  6623. const { hasPermission } = useAuth();
  6624. const canUpdate = hasPermission('firmware:update');
  6625. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  6626. const [isUploading, setIsUploading] = useState(false);
  6627. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  6628. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  6629. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  6630. );
  6631. // Prepare check query — runs when a version is selected and user can update
  6632. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  6633. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  6634. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  6635. staleTime: 30000,
  6636. enabled: !!selectedVersion && canUpdate && !isUploading,
  6637. });
  6638. // Start upload mutation
  6639. const uploadMutation = useMutation({
  6640. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  6641. onSuccess: () => {
  6642. setIsUploading(true);
  6643. // Start polling for status
  6644. const interval = setInterval(async () => {
  6645. try {
  6646. const status = await firmwareApi.getUploadStatus(printer.id);
  6647. setUploadStatus(status);
  6648. if (status.status === 'complete' || status.status === 'error') {
  6649. clearInterval(interval);
  6650. setPollInterval(null);
  6651. setIsUploading(false);
  6652. if (status.status === 'complete') {
  6653. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  6654. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  6655. }
  6656. }
  6657. } catch {
  6658. // Ignore errors during polling
  6659. }
  6660. }, 2000);
  6661. setPollInterval(interval);
  6662. },
  6663. onError: (error: Error) => {
  6664. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  6665. setIsUploading(false);
  6666. },
  6667. });
  6668. // Cleanup on unmount
  6669. useEffect(() => {
  6670. return () => {
  6671. if (pollInterval) clearInterval(pollInterval);
  6672. };
  6673. }, [pollInterval]);
  6674. const handleStartUpload = () => {
  6675. setUploadStatus(null);
  6676. uploadMutation.mutate();
  6677. };
  6678. return (
  6679. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  6680. <Card className="w-full max-w-md mx-4">
  6681. <CardContent>
  6682. <div className="flex items-start gap-3 mb-4">
  6683. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-500/20' : 'bg-status-ok/20'}`}>
  6684. {firmwareInfo.update_available
  6685. ? <Download className="w-5 h-5 text-orange-400" />
  6686. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  6687. </div>
  6688. <div className="flex-1">
  6689. <h3 className="text-lg font-semibold text-white">
  6690. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  6691. </h3>
  6692. <p className="text-sm text-bambu-gray mt-1">
  6693. {printer.name}
  6694. </p>
  6695. </div>
  6696. </div>
  6697. {/* Version Info */}
  6698. {(() => {
  6699. const selectedEntry = selectedVersion
  6700. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  6701. : null;
  6702. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  6703. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  6704. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  6705. return (
  6706. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  6707. <div className="flex justify-between items-center text-sm">
  6708. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  6709. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  6710. {firmwareInfo.current_version || t('common.unknown')}
  6711. </span>
  6712. </div>
  6713. {showSecondLine && (
  6714. <div className="flex justify-between items-center text-sm mt-1">
  6715. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  6716. <span className="text-orange-400 font-mono">{displayVersion}</span>
  6717. </div>
  6718. )}
  6719. {displayNotes && (
  6720. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  6721. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-400' : 'text-status-ok'}`}>
  6722. {t('printers.firmwareModal.releaseNotes')}
  6723. </summary>
  6724. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  6725. {displayNotes}
  6726. </div>
  6727. </details>
  6728. )}
  6729. </div>
  6730. );
  6731. })()}
  6732. {/* Available versions list */}
  6733. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  6734. <div className="mb-4">
  6735. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  6736. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  6737. {firmwareInfo.available_versions.map((v) => {
  6738. const isCurrent = firmwareInfo.current_version === v.version;
  6739. const isSelected = selectedVersion === v.version;
  6740. const cmp = firmwareInfo.current_version
  6741. ? compareFwVersions(v.version, firmwareInfo.current_version)
  6742. : 0;
  6743. const relLabel = isCurrent
  6744. ? t('printers.firmwareModal.currentBadge')
  6745. : cmp > 0
  6746. ? t('printers.firmwareModal.newerBadge')
  6747. : t('printers.firmwareModal.olderBadge');
  6748. const relClass = isCurrent
  6749. ? 'text-bambu-gray'
  6750. : cmp > 0
  6751. ? 'text-orange-400'
  6752. : 'text-blue-400';
  6753. return (
  6754. <button
  6755. key={v.version}
  6756. type="button"
  6757. disabled={!v.file_available || !canUpdate || isCurrent}
  6758. onClick={() => setSelectedVersion(v.version)}
  6759. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  6760. isSelected ? 'bg-orange-500/10' : 'hover:bg-bambu-dark'
  6761. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  6762. >
  6763. <div className="flex items-center gap-2 min-w-0">
  6764. <span className="font-mono text-white">{v.version}</span>
  6765. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  6766. </div>
  6767. <span className={`text-xs px-2 py-0.5 rounded-full ${
  6768. isCurrent
  6769. ? 'bg-blue-500/15 text-blue-400 border border-blue-500/30'
  6770. : v.file_available
  6771. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  6772. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  6773. }`}>
  6774. {isCurrent
  6775. ? t('printers.firmwareModal.installed')
  6776. : v.file_available
  6777. ? t('printers.firmwareModal.usable')
  6778. : t('printers.firmwareModal.unavailable')}
  6779. </span>
  6780. </button>
  6781. );
  6782. })}
  6783. </div>
  6784. </div>
  6785. )}
  6786. {/* Status / Progress (only when a version is selected) */}
  6787. {!selectedVersion ? null : isPreparing ? (
  6788. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  6789. <Loader2 className="w-4 h-4 animate-spin" />
  6790. {t('printers.firmwareModal.checkingPrereqs')}
  6791. </div>
  6792. ) : prepareInfo && !isUploading && !uploadStatus ? (
  6793. <div className="mb-4">
  6794. {prepareInfo.can_proceed ? (
  6795. <div className="flex items-center gap-2 text-bambu-green text-sm">
  6796. <Box className="w-4 h-4" />
  6797. {t('printers.firmwareModal.sdCardReady')}
  6798. </div>
  6799. ) : (
  6800. <div className="space-y-1">
  6801. {prepareInfo.errors.map((error, i) => (
  6802. <div key={i} className="flex items-center gap-2 text-red-400 text-sm">
  6803. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  6804. {error}
  6805. </div>
  6806. ))}
  6807. </div>
  6808. )}
  6809. </div>
  6810. ) : null}
  6811. {/* Upload Progress */}
  6812. {(isUploading || uploadStatus) && uploadStatus && (
  6813. <div className="mb-4">
  6814. <div className="flex items-center justify-between text-sm mb-1">
  6815. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  6816. <span className="text-white">{uploadStatus.progress}%</span>
  6817. </div>
  6818. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  6819. <div
  6820. className={`h-2 rounded-full transition-all ${
  6821. uploadStatus.status === 'error' ? 'bg-status-error' :
  6822. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  6823. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  6824. style={{ width: `${uploadStatus.progress}%` }}
  6825. />
  6826. </div>
  6827. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  6828. {uploadStatus.error && (
  6829. <p className="text-xs text-red-400 mt-1">{uploadStatus.error}</p>
  6830. )}
  6831. </div>
  6832. )}
  6833. {/* Success Message */}
  6834. {uploadStatus?.status === 'complete' && (
  6835. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  6836. <p className="text-sm text-bambu-green font-medium mb-2">
  6837. {t('printers.firmwareModal.uploadedSuccess')}
  6838. </p>
  6839. <p className="text-xs text-bambu-gray">
  6840. {t('printers.firmwareModal.applyInstructions')}
  6841. </p>
  6842. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  6843. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  6844. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  6845. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  6846. <li>{t('printers.firmwareModal.step4')}</li>
  6847. </ol>
  6848. </div>
  6849. )}
  6850. {/* Buttons */}
  6851. <div className="flex gap-2 justify-end">
  6852. <Button variant="secondary" onClick={onClose}>
  6853. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  6854. </Button>
  6855. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  6856. <Button
  6857. onClick={handleStartUpload}
  6858. disabled={uploadMutation.isPending}
  6859. >
  6860. {uploadMutation.isPending ? (
  6861. <>
  6862. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  6863. {t('printers.firmwareModal.starting')}
  6864. </>
  6865. ) : (
  6866. <>
  6867. <Download className="w-4 h-4 mr-2" />
  6868. {t('printers.firmwareModal.uploadFirmware')}
  6869. </>
  6870. )}
  6871. </Button>
  6872. )}
  6873. </div>
  6874. </CardContent>
  6875. </Card>
  6876. </div>
  6877. );
  6878. }
  6879. function EditPrinterModal({
  6880. printer,
  6881. onClose,
  6882. }: {
  6883. printer: Printer;
  6884. onClose: () => void;
  6885. }) {
  6886. const { t } = useTranslation();
  6887. const queryClient = useQueryClient();
  6888. const { showToast } = useToast();
  6889. const [form, setForm] = useState({
  6890. name: printer.name,
  6891. ip_address: printer.ip_address,
  6892. access_code: '',
  6893. model: printer.model || '',
  6894. location: printer.location || '',
  6895. auto_archive: printer.auto_archive,
  6896. is_active: printer.is_active,
  6897. });
  6898. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  6899. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  6900. const [checkingSave, setCheckingSave] = useState(false);
  6901. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6902. const updateMutation = useMutation({
  6903. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  6904. onSuccess: () => {
  6905. queryClient.invalidateQueries({ queryKey: ['printers'] });
  6906. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6907. onClose();
  6908. },
  6909. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  6910. });
  6911. // Close on Escape key
  6912. useEffect(() => {
  6913. const handleKeyDown = (e: KeyboardEvent) => {
  6914. if (e.key === 'Escape') onClose();
  6915. };
  6916. window.addEventListener('keydown', handleKeyDown);
  6917. return () => window.removeEventListener('keydown', handleKeyDown);
  6918. }, [onClose]);
  6919. const doSave = () => {
  6920. const data: Partial<PrinterCreate> = {
  6921. name: form.name,
  6922. ip_address: form.ip_address,
  6923. model: form.model || undefined,
  6924. location: form.location || undefined,
  6925. auto_archive: form.auto_archive,
  6926. is_active: form.is_active,
  6927. };
  6928. // Only include access_code if it was changed
  6929. if (form.access_code) {
  6930. data.access_code = form.access_code;
  6931. }
  6932. updateMutation.mutate(data);
  6933. };
  6934. const handleSubmit = async (e: React.FormEvent) => {
  6935. e.preventDefault();
  6936. setCheckingSave(true);
  6937. try {
  6938. const result = await api.diagnoseConnection({
  6939. ip_address: form.ip_address.trim(),
  6940. serial_number: printer.serial_number,
  6941. access_code: form.access_code || undefined,
  6942. });
  6943. if (result.checks.some((c) => c.status === 'fail')) {
  6944. setSaveWarning(result);
  6945. return;
  6946. }
  6947. } catch {
  6948. // Diagnostic infrastructure failed — never block the save on it.
  6949. } finally {
  6950. setCheckingSave(false);
  6951. }
  6952. doSave();
  6953. };
  6954. return (
  6955. <div
  6956. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6957. onClick={onClose}
  6958. >
  6959. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6960. <CardContent>
  6961. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  6962. <form onSubmit={handleSubmit} className="space-y-4">
  6963. <div>
  6964. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6965. <input
  6966. type="text"
  6967. required
  6968. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6969. value={form.name}
  6970. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6971. placeholder={t('printers.modal.myPrinter')}
  6972. />
  6973. </div>
  6974. <div>
  6975. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6976. <input
  6977. type="text"
  6978. required
  6979. pattern="(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)"
  6980. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  6981. value={form.ip_address}
  6982. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6983. placeholder="192.168.1.100 or printer.local"
  6984. />
  6985. </div>
  6986. <div>
  6987. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6988. <input
  6989. type="text"
  6990. disabled
  6991. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  6992. value={printer.serial_number}
  6993. />
  6994. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  6995. </div>
  6996. <div>
  6997. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6998. <input
  6999. type="password"
  7000. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7001. value={form.access_code}
  7002. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7003. placeholder={t('printers.accessCodePlaceholder')}
  7004. />
  7005. </div>
  7006. <div>
  7007. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7008. <select
  7009. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7010. value={form.model}
  7011. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7012. >
  7013. <option value="">{t('printers.modal.selectModel')}</option>
  7014. <optgroup label="A1 Series">
  7015. <option value="A1">A1</option>
  7016. <option value="A1 Mini">A1 Mini</option>
  7017. </optgroup>
  7018. <optgroup label="A2 Series">
  7019. <option value="A2L">A2L</option>
  7020. </optgroup>
  7021. <optgroup label="H2 Series">
  7022. <option value="H2C">H2C</option>
  7023. <option value="H2D">H2D</option>
  7024. <option value="H2D Pro">H2D Pro</option>
  7025. <option value="H2S">H2S</option>
  7026. </optgroup>
  7027. <optgroup label="P Series">
  7028. <option value="P1P">P1P</option>
  7029. <option value="P1S">P1S</option>
  7030. <option value="P2S">P2S</option>
  7031. </optgroup>
  7032. <optgroup label="X1 Series">
  7033. <option value="X1">X1</option>
  7034. <option value="X1C">X1 Carbon</option>
  7035. <option value="X1E">X1E</option>
  7036. </optgroup>
  7037. <optgroup label="X2 Series">
  7038. <option value="X2D">X2D</option>
  7039. </optgroup>
  7040. </select>
  7041. </div>
  7042. <div>
  7043. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7044. <input
  7045. type="text"
  7046. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7047. value={form.location}
  7048. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7049. placeholder={t('printers.modal.locationPlaceholder')}
  7050. />
  7051. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7052. </div>
  7053. <div className="flex items-center gap-2">
  7054. <input
  7055. type="checkbox"
  7056. id="edit_auto_archive"
  7057. checked={form.auto_archive}
  7058. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7059. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7060. />
  7061. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7062. {t('printers.modal.autoArchiveLabel')}
  7063. </label>
  7064. </div>
  7065. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7066. is_active because the user-facing concept is "is this printer
  7067. in maintenance" not "is it active". */}
  7068. <div>
  7069. <div className="flex items-center gap-2">
  7070. <input
  7071. type="checkbox"
  7072. id="edit_maintenance_mode"
  7073. checked={!form.is_active}
  7074. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  7075. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  7076. />
  7077. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  7078. <Wrench className="w-3.5 h-3.5 text-amber-400" />
  7079. {t('printers.maintenance.editFieldLabel')}
  7080. </label>
  7081. </div>
  7082. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  7083. {t('printers.maintenance.editFieldHelp')}
  7084. </p>
  7085. </div>
  7086. {saveWarning ? (
  7087. <div className="rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3">
  7088. <div className="flex items-start gap-2">
  7089. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400" />
  7090. <p className="text-sm text-amber-300">{t('printers.addPreflight.warning')}</p>
  7091. </div>
  7092. <DiagnosticChecklist result={saveWarning} />
  7093. <div className="flex gap-3">
  7094. <Button
  7095. type="button"
  7096. variant="secondary"
  7097. onClick={() => setSaveWarning(null)}
  7098. className="flex-1"
  7099. >
  7100. {t('printers.addPreflight.back')}
  7101. </Button>
  7102. <Button
  7103. type="button"
  7104. onClick={doSave}
  7105. className="flex-1"
  7106. disabled={updateMutation.isPending}
  7107. >
  7108. {t('printers.addPreflight.saveAnyway')}
  7109. </Button>
  7110. </div>
  7111. </div>
  7112. ) : (
  7113. <div className="flex gap-3 pt-4">
  7114. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7115. {t('common.cancel')}
  7116. </Button>
  7117. <Button
  7118. type="submit"
  7119. className="flex-1"
  7120. disabled={updateMutation.isPending || checkingSave}
  7121. >
  7122. {checkingSave
  7123. ? t('printers.addPreflight.checking')
  7124. : updateMutation.isPending
  7125. ? t('common.saving')
  7126. : t('printers.modal.saveChanges')}
  7127. </Button>
  7128. </div>
  7129. )}
  7130. </form>
  7131. </CardContent>
  7132. </Card>
  7133. </div>
  7134. );
  7135. }
  7136. // Component to check if a printer is offline (for power dropdown)
  7137. function usePrinterOfflineStatus(printerId: number) {
  7138. const { data: status } = useQuery({
  7139. queryKey: ['printerStatus', printerId],
  7140. queryFn: () => api.getPrinterStatus(printerId),
  7141. refetchInterval: 30000,
  7142. });
  7143. return !status?.connected;
  7144. }
  7145. // Power dropdown item for an offline printer
  7146. function PowerDropdownItem({
  7147. printer,
  7148. plug,
  7149. onPowerOn,
  7150. isPowering,
  7151. }: {
  7152. printer: Printer;
  7153. plug: { id: number; name: string };
  7154. onPowerOn: (plugId: number) => void;
  7155. isPowering: boolean;
  7156. }) {
  7157. const isOffline = usePrinterOfflineStatus(printer.id);
  7158. // Fetch plug status
  7159. const { data: plugStatus } = useQuery({
  7160. queryKey: ['smartPlugStatus', plug.id],
  7161. queryFn: () => api.getSmartPlugStatus(plug.id),
  7162. refetchInterval: 10000,
  7163. });
  7164. // Only show if printer is offline
  7165. if (!isOffline) {
  7166. return null;
  7167. }
  7168. return (
  7169. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  7170. <div className="flex items-center gap-2 min-w-0">
  7171. <span className="text-sm text-gray-900 dark:text-white truncate">{printer.name}</span>
  7172. {plugStatus && (
  7173. <span
  7174. className={`text-xs px-1.5 py-0.5 rounded ${
  7175. plugStatus.state === 'ON'
  7176. ? 'bg-bambu-green/20 text-bambu-green'
  7177. : 'bg-red-500/20 text-red-400'
  7178. }`}
  7179. >
  7180. {plugStatus.state || '?'}
  7181. </span>
  7182. )}
  7183. </div>
  7184. <button
  7185. onClick={() => onPowerOn(plug.id)}
  7186. disabled={isPowering || plugStatus?.state === 'ON'}
  7187. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  7188. plugStatus?.state === 'ON'
  7189. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  7190. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  7191. }`}
  7192. >
  7193. <Power className="w-3 h-3" />
  7194. {isPowering ? '...' : 'On'}
  7195. </button>
  7196. </div>
  7197. );
  7198. }
  7199. export function PrintersPage() {
  7200. const { t } = useTranslation();
  7201. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  7202. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  7203. const accentButtonClass = {
  7204. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  7205. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  7206. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  7207. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  7208. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  7209. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  7210. }[activeAccent];
  7211. const [showAddModal, setShowAddModal] = useState(false);
  7212. const [hideDisconnected, setHideDisconnected] = useState(() => {
  7213. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  7214. });
  7215. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  7216. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  7217. const [sortBy, setSortBy] = useState<SortOption>(() => {
  7218. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  7219. });
  7220. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  7221. return localStorage.getItem('printerSortAsc') !== 'false';
  7222. });
  7223. // Card size: 1=small, 2=medium, 3=large, 4=xl
  7224. const [cardSize, setCardSize] = useState<number>(() => {
  7225. const saved = localStorage.getItem('printerCardSize');
  7226. return saved ? parseInt(saved, 10) : 2; // Default to medium
  7227. });
  7228. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  7229. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  7230. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  7231. const scrollPrinterIntoView = useCallback((printerId: number) => {
  7232. requestAnimationFrame(() => {
  7233. requestAnimationFrame(() => {
  7234. const card = document.getElementById(`printer-card-${printerId}`);
  7235. if (!card) return;
  7236. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  7237. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  7238. window.scrollTo({
  7239. top: Math.max(0, top),
  7240. behavior: 'smooth',
  7241. });
  7242. });
  7243. });
  7244. }, []);
  7245. const openCompactCard = useCallback((printerId: number) => {
  7246. setCompactDrilldownPrinterId(printerId);
  7247. setCardSize(2);
  7248. localStorage.setItem('printerCardSize', '2');
  7249. scrollPrinterIntoView(printerId);
  7250. }, [scrollPrinterIntoView]);
  7251. const returnToCompactCards = useCallback(() => {
  7252. const printerId = compactDrilldownPrinterId;
  7253. setCompactDrilldownPrinterId(null);
  7254. setCardSize(1);
  7255. localStorage.setItem('printerCardSize', '1');
  7256. if (printerId != null) {
  7257. scrollPrinterIntoView(printerId);
  7258. }
  7259. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  7260. const [search, setSearch] = useState('');
  7261. const [statusFilter, setStatusFilter] = useState<string>('all');
  7262. const [locationFilter, setLocationFilter] = useState<string>('all');
  7263. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  7264. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  7265. try {
  7266. const saved = localStorage.getItem('printerCollapsedSections');
  7267. return saved ? JSON.parse(saved) : {};
  7268. } catch { return {}; }
  7269. });
  7270. const queryClient = useQueryClient();
  7271. const { showToast } = useToast();
  7272. const { hasPermission } = useAuth();
  7273. // Embedded camera viewer state - supports multiple simultaneous viewers
  7274. // Persisted to localStorage so cameras reopen after navigation
  7275. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  7276. // Initialize from localStorage if camera_view_mode is embedded
  7277. const saved = localStorage.getItem('openEmbeddedCameras');
  7278. if (saved) {
  7279. try {
  7280. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  7281. return new Map(cameras.map(c => [c.id, c]));
  7282. } catch {
  7283. return new Map();
  7284. }
  7285. }
  7286. return new Map();
  7287. });
  7288. // Persist open cameras to localStorage when they change
  7289. useEffect(() => {
  7290. const cameras = Array.from(embeddedCameraPrinters.values());
  7291. if (cameras.length > 0) {
  7292. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  7293. } else {
  7294. localStorage.removeItem('openEmbeddedCameras');
  7295. }
  7296. }, [embeddedCameraPrinters]);
  7297. const { data: printers, isLoading } = useQuery({
  7298. queryKey: ['printers'],
  7299. queryFn: api.getPrinters,
  7300. });
  7301. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  7302. // so users with printers:read but no settings:read still get the values needed
  7303. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  7304. const { data: settings } = useQuery({
  7305. queryKey: ['ui-preferences'],
  7306. queryFn: api.getUiPreferences,
  7307. });
  7308. // Parse user-configured temperature/fan presets once, with defensive fallback
  7309. // to built-in defaults on parse failure (validators on the backend already
  7310. // reject malformed writes, so this is just forward-compat).
  7311. const effectiveNozzleTempPresets = useMemo(
  7312. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  7313. [settings?.nozzle_temp_presets],
  7314. );
  7315. const effectiveBedTempPresets = useMemo(
  7316. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  7317. [settings?.bed_temp_presets],
  7318. );
  7319. const effectiveChamberTempPresets = useMemo(
  7320. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, 60),
  7321. [settings?.chamber_temp_presets],
  7322. );
  7323. const effectiveFanSpeedPresets = useMemo(
  7324. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  7325. [settings?.fan_speed_presets],
  7326. );
  7327. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  7328. const effectiveDryingPresets = useMemo(() => {
  7329. if (settings?.drying_presets) {
  7330. try {
  7331. const userPresets = JSON.parse(settings.drying_presets);
  7332. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  7333. return { ...DRYING_PRESETS, ...userPresets };
  7334. }
  7335. } catch { /* ignore parse errors, use defaults */ }
  7336. }
  7337. return DRYING_PRESETS;
  7338. }, [settings?.drying_presets]);
  7339. // Close embedded cameras if mode changes to 'window'
  7340. useEffect(() => {
  7341. if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
  7342. setEmbeddedCameraPrinters(new Map());
  7343. }
  7344. }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
  7345. // Fetch all smart plugs to know which printers have them
  7346. const { data: smartPlugs } = useQuery({
  7347. queryKey: ['smart-plugs'],
  7348. queryFn: api.getSmartPlugs,
  7349. });
  7350. // Fetch maintenance overview for all printers to show badges
  7351. const { data: maintenanceOverview } = useQuery({
  7352. queryKey: ['maintenanceOverview'],
  7353. queryFn: api.getMaintenanceOverview,
  7354. staleTime: 60 * 1000, // 1 minute
  7355. });
  7356. // Fetch Spoolman status to enable link spool feature
  7357. const { data: spoolmanStatus } = useQuery({
  7358. queryKey: ['spoolman-status'],
  7359. queryFn: api.getSpoolmanStatus,
  7360. staleTime: 60 * 1000, // 1 minute
  7361. });
  7362. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  7363. // Fetch Spoolman settings to get sync mode
  7364. const { data: spoolmanSettings } = useQuery({
  7365. queryKey: ['spoolman-settings'],
  7366. queryFn: api.getSpoolmanSettings,
  7367. enabled: !!spoolmanEnabled,
  7368. staleTime: 60 * 1000, // 1 minute
  7369. });
  7370. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  7371. // Fetch unlinked spools to know if link button should be enabled
  7372. const { data: unlinkedSpools } = useQuery({
  7373. queryKey: ['unlinked-spools'],
  7374. queryFn: api.getUnlinkedSpools,
  7375. enabled: !!spoolmanEnabled,
  7376. staleTime: 30 * 1000, // 30 seconds
  7377. });
  7378. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  7379. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  7380. const { data: linkedSpoolsData } = useQuery({
  7381. queryKey: ['linked-spools'],
  7382. queryFn: api.getLinkedSpools,
  7383. enabled: !!spoolmanEnabled,
  7384. staleTime: 30 * 1000, // 30 seconds
  7385. });
  7386. const linkedSpools = linkedSpoolsData?.linked;
  7387. // Fetch spool assignments for inventory feature
  7388. const { data: spoolAssignments } = useQuery({
  7389. queryKey: ['spool-assignments'],
  7390. queryFn: () => api.getAssignments(),
  7391. enabled: hasPermission('inventory:view_assignments'),
  7392. staleTime: 30 * 1000,
  7393. });
  7394. const unassignMutation = useMutation({
  7395. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  7396. api.unassignSpool(printerId, amsId, trayId),
  7397. onSuccess: () => {
  7398. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  7399. },
  7400. });
  7401. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  7402. queryKey: ['spoolman-inventory-spools'],
  7403. queryFn: () => api.getSpoolmanInventorySpools(false),
  7404. enabled: !!spoolmanEnabled,
  7405. staleTime: 30 * 1000,
  7406. });
  7407. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  7408. queryKey: ['spoolman-slot-assignments'],
  7409. queryFn: () => api.getSpoolmanSlotAssignments(),
  7410. enabled: !!spoolmanEnabled,
  7411. staleTime: 30 * 1000,
  7412. });
  7413. const unassignSpoolmanMutation = useMutation({
  7414. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  7415. onSuccess: () => {
  7416. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  7417. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  7418. },
  7419. });
  7420. // Helper to find assignment for a specific slot
  7421. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  7422. return spoolAssignments?.find(
  7423. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  7424. );
  7425. };
  7426. // Create a map of printer_id -> maintenance info for quick lookup
  7427. const maintenanceByPrinter = maintenanceOverview?.reduce(
  7428. (acc, overview) => {
  7429. acc[overview.printer_id] = {
  7430. due_count: overview.due_count,
  7431. warning_count: overview.warning_count,
  7432. total_print_hours: overview.total_print_hours,
  7433. };
  7434. return acc;
  7435. },
  7436. {} as Record<number, PrinterMaintenanceInfo>
  7437. ) || {};
  7438. // Create a map of printer_id -> smart plug
  7439. const smartPlugByPrinter = smartPlugs?.reduce(
  7440. (acc, plug) => {
  7441. if (plug.printer_id) {
  7442. acc[plug.printer_id] = plug;
  7443. }
  7444. return acc;
  7445. },
  7446. {} as Record<number, typeof smartPlugs[0]>
  7447. ) || {};
  7448. const addMutation = useMutation({
  7449. mutationFn: api.createPrinter,
  7450. onSuccess: () => {
  7451. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7452. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  7453. setShowAddModal(false);
  7454. },
  7455. onError: (error: Error) => {
  7456. // Localized message when the backend returns a stable error code;
  7457. // the raw message is an English fallback for non-UI clients.
  7458. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  7459. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  7460. return;
  7461. }
  7462. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  7463. },
  7464. });
  7465. const powerOnMutation = useMutation({
  7466. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  7467. onSuccess: () => {
  7468. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  7469. setPoweringOn(null);
  7470. },
  7471. onError: () => {
  7472. setPoweringOn(null);
  7473. },
  7474. });
  7475. // Bulk selection state
  7476. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  7477. const [isSelectionMode, setIsSelectionMode] = useState(false);
  7478. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  7479. const [bulkActionPending, setBulkActionPending] = useState(false);
  7480. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  7481. const toggleSelect = useCallback((id: number) => {
  7482. setSelectedPrinterIds(prev => {
  7483. const next = new Set(prev);
  7484. if (next.has(id)) next.delete(id);
  7485. else next.add(id);
  7486. return next;
  7487. });
  7488. }, []);
  7489. const clearSelection = useCallback(() => {
  7490. setSelectedPrinterIds(new Set());
  7491. setIsSelectionMode(false);
  7492. }, []);
  7493. // Escape key exits selection mode
  7494. useEffect(() => {
  7495. const handleKeyDown = (e: KeyboardEvent) => {
  7496. if (e.key === 'Escape' && selectionMode) {
  7497. clearSelection();
  7498. }
  7499. };
  7500. window.addEventListener('keydown', handleKeyDown);
  7501. return () => window.removeEventListener('keydown', handleKeyDown);
  7502. }, [selectionMode, clearSelection]);
  7503. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7504. setBulkActionPending(true);
  7505. const ids = Array.from(selectedPrinterIds);
  7506. // Filter to only applicable printers based on cached state
  7507. const applicableIds = ids.filter(id => {
  7508. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  7509. if (!status?.connected) return false;
  7510. switch (action) {
  7511. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  7512. case 'pause': return status.state === 'RUNNING';
  7513. case 'resume': return status.state === 'PAUSE';
  7514. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  7515. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  7516. default: return false;
  7517. }
  7518. });
  7519. if (applicableIds.length === 0) {
  7520. showToast(t('printers.bulk.noneApplicable'), 'error');
  7521. setBulkActionPending(false);
  7522. setBulkConfirmAction(null);
  7523. return;
  7524. }
  7525. const apiCall = {
  7526. stop: api.stopPrint,
  7527. pause: api.pausePrint,
  7528. resume: api.resumePrint,
  7529. clearPlate: api.clearPlate,
  7530. clearHMS: api.clearHMSErrors,
  7531. }[action];
  7532. const results = await Promise.allSettled(
  7533. applicableIds.map(id => apiCall(id))
  7534. );
  7535. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  7536. const failed = results.filter(r => r.status === 'rejected').length;
  7537. if (failed === 0) {
  7538. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  7539. } else {
  7540. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  7541. }
  7542. // Invalidate status queries for affected printers
  7543. applicableIds.forEach(id => {
  7544. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  7545. });
  7546. setBulkActionPending(false);
  7547. setBulkConfirmAction(null);
  7548. }, [selectedPrinterIds, queryClient, showToast, t]);
  7549. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7550. // Actions that need confirmation
  7551. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  7552. setBulkConfirmAction(action);
  7553. } else {
  7554. executeBulkAction(action);
  7555. }
  7556. }, [executeBulkAction]);
  7557. const toggleHideDisconnected = () => {
  7558. const newValue = !hideDisconnected;
  7559. setHideDisconnected(newValue);
  7560. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  7561. };
  7562. const handleSortChange = (newSort: SortOption) => {
  7563. setSortBy(newSort);
  7564. localStorage.setItem('printerSortBy', newSort);
  7565. };
  7566. const toggleSortDirection = () => {
  7567. const newAsc = !sortAsc;
  7568. setSortAsc(newAsc);
  7569. localStorage.setItem('printerSortAsc', String(newAsc));
  7570. };
  7571. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  7572. const getGridClasses = () => {
  7573. switch (cardSize) {
  7574. case 1: return 'grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5'; // S: many small cards
  7575. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  7576. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  7577. case 4: return 'grid-cols-1'; // XL: single column, full width
  7578. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  7579. }
  7580. };
  7581. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  7582. // Increment version counter whenever a printer status cache entry is updated so
  7583. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  7584. useEffect(() => {
  7585. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  7586. if (
  7587. event.type === 'updated' &&
  7588. Array.isArray(event.query.queryKey) &&
  7589. event.query.queryKey[0] === 'printerStatus'
  7590. ) {
  7591. setStatusCacheVersion(v => v + 1);
  7592. }
  7593. });
  7594. return unsubscribe;
  7595. }, [queryClient]);
  7596. // Filter printers by search term, status, and location
  7597. const filteredPrinters = useMemo(() => {
  7598. if (!printers) return [];
  7599. let result = printers;
  7600. // Text search
  7601. if (search.trim()) {
  7602. const q = search.trim().toLowerCase();
  7603. result = result.filter(p =>
  7604. p.name.toLowerCase().includes(q) ||
  7605. (p.model || '').toLowerCase().includes(q) ||
  7606. (p.location || '').toLowerCase().includes(q) ||
  7607. (p.serial_number || '').toLowerCase().includes(q)
  7608. );
  7609. }
  7610. // Location filter
  7611. if (locationFilter !== 'all') {
  7612. result = result.filter(p => (p.location || '') === locationFilter);
  7613. }
  7614. // Status filter
  7615. if (statusFilter !== 'all') {
  7616. result = result.filter(p => {
  7617. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7618. if (!status?.connected) return statusFilter === 'offline';
  7619. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  7620. switch (statusFilter) {
  7621. case 'printing': return status.state === 'RUNNING';
  7622. case 'paused': return status.state === 'PAUSE';
  7623. case 'finished': return status.state === 'FINISH';
  7624. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  7625. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  7626. case 'offline': return false; // Connected printers are never offline
  7627. default: return true;
  7628. }
  7629. });
  7630. }
  7631. return result;
  7632. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  7633. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  7634. // Derive unique locations for the location filter dropdown
  7635. const availableLocations = useMemo(() => {
  7636. if (!printers) return [];
  7637. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  7638. }, [printers]);
  7639. // Sort printers based on selected option
  7640. const sortedPrinters = useMemo(() => {
  7641. const sorted = [...filteredPrinters];
  7642. switch (sortBy) {
  7643. case 'name':
  7644. sorted.sort((a, b) => a.name.localeCompare(b.name));
  7645. break;
  7646. case 'model':
  7647. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  7648. break;
  7649. case 'location':
  7650. // Sort by location, with ungrouped printers last
  7651. sorted.sort((a, b) => {
  7652. const locA = a.location || '';
  7653. const locB = b.location || '';
  7654. if (!locA && locB) return 1;
  7655. if (locA && !locB) return -1;
  7656. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  7657. });
  7658. break;
  7659. case 'status':
  7660. // Sort by status: HMS errors > printing > idle > offline
  7661. sorted.sort((a, b) => {
  7662. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  7663. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  7664. const getPriority = (s: typeof statusA) => {
  7665. if (!s?.connected) return 3; // offline
  7666. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  7667. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  7668. if (s.state === 'RUNNING') return 1; // printing
  7669. return 2; // idle
  7670. };
  7671. return getPriority(statusA) - getPriority(statusB);
  7672. });
  7673. break;
  7674. case 'eta':
  7675. sorted.sort((a, b) => {
  7676. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  7677. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  7678. const tier = (s: typeof statusA) => {
  7679. if (!s?.connected) return 3; // offline last
  7680. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  7681. if (s.state === 'RUNNING') return 1; // printing without ETA
  7682. return 2; // idle
  7683. };
  7684. const ta = tier(statusA);
  7685. const tb = tier(statusB);
  7686. if (ta !== tb) return ta - tb;
  7687. if (ta === 0) {
  7688. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  7689. if (diff !== 0) return diff;
  7690. }
  7691. return a.name.localeCompare(b.name);
  7692. });
  7693. break;
  7694. }
  7695. // Apply ascending/descending
  7696. if (!sortAsc) {
  7697. sorted.reverse();
  7698. }
  7699. return sorted;
  7700. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  7701. const selectAll = useCallback(() => {
  7702. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  7703. setIsSelectionMode(true);
  7704. }, [sortedPrinters]);
  7705. const selectByState = useCallback((state: PrinterState) => {
  7706. setSelectedPrinterIds(prev => {
  7707. const next = new Set(prev);
  7708. sortedPrinters.forEach(p => {
  7709. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7710. if (classifyPrinterStatus(status) === state) next.add(p.id);
  7711. });
  7712. return next;
  7713. });
  7714. setIsSelectionMode(true);
  7715. }, [sortedPrinters, queryClient]);
  7716. const selectByLocation = useCallback((location: string) => {
  7717. setSelectedPrinterIds(prev => {
  7718. const next = new Set(prev);
  7719. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  7720. return next;
  7721. });
  7722. setIsSelectionMode(true);
  7723. }, [sortedPrinters]);
  7724. const selectByModel = useCallback((model: string) => {
  7725. setSelectedPrinterIds(prev => {
  7726. const next = new Set(prev);
  7727. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  7728. return next;
  7729. });
  7730. setIsSelectionMode(true);
  7731. }, [sortedPrinters]);
  7732. const toggleSectionCollapse = useCallback((key: string) => {
  7733. setCollapsedSections(prev => {
  7734. const next = { ...prev, [key]: !prev[key] };
  7735. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  7736. return next;
  7737. });
  7738. }, []);
  7739. // Group printers when sorted by location, status, or model
  7740. const groupedPrinters = useMemo(() => {
  7741. if (sortBy === 'name' || sortBy === 'eta') return null;
  7742. const groups: Record<string, typeof sortedPrinters> = {};
  7743. if (sortBy === 'location') {
  7744. sortedPrinters.forEach(printer => {
  7745. const location = printer.location || 'Ungrouped';
  7746. if (!groups[location]) groups[location] = [];
  7747. groups[location].push(printer);
  7748. });
  7749. } else if (sortBy === 'model') {
  7750. sortedPrinters.forEach(printer => {
  7751. const model = printer.model || 'Unknown';
  7752. if (!groups[model]) groups[model] = [];
  7753. groups[model].push(printer);
  7754. });
  7755. } else if (sortBy === 'status') {
  7756. sortedPrinters.forEach(printer => {
  7757. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  7758. const group = classifyPrinterStatus(status);
  7759. if (!groups[group]) groups[group] = [];
  7760. groups[group].push(printer);
  7761. });
  7762. }
  7763. return groups;
  7764. // eslint-disable-next-line react-hooks/exhaustive-deps -- classifyPrinterStatus & filterKnownHMSErrors are stable module-level functions, not reactive deps; statusCacheVersion forces recompute on WebSocket status updates
  7765. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  7766. const toolbarRef = useRef<HTMLDivElement>(null);
  7767. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  7768. const expandedToolbarWidthRef = useRef(0);
  7769. const [compactToolbar, setCompactToolbar] = useState(false);
  7770. const measureToolbar = useCallback(() => {
  7771. const toolbar = toolbarRef.current;
  7772. if (!toolbar) return;
  7773. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  7774. if (measuredControlsWidth) {
  7775. expandedToolbarWidthRef.current = measuredControlsWidth;
  7776. }
  7777. const searchMinimumWidth = 220;
  7778. const gapWidth = 8;
  7779. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  7780. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  7781. }, []);
  7782. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  7783. useLayoutEffect(() => {
  7784. measureToolbar();
  7785. const toolbar = toolbarRef.current;
  7786. if (!toolbar) return;
  7787. if (typeof ResizeObserver === 'undefined') {
  7788. window.addEventListener('resize', measureToolbar);
  7789. return () => window.removeEventListener('resize', measureToolbar);
  7790. }
  7791. const resizeObserver = new ResizeObserver(() => measureToolbar());
  7792. resizeObserver.observe(toolbar);
  7793. window.addEventListener('resize', measureToolbar);
  7794. return () => {
  7795. resizeObserver.disconnect();
  7796. window.removeEventListener('resize', measureToolbar);
  7797. };
  7798. }, [
  7799. measureToolbar,
  7800. printers?.length,
  7801. availableLocations.length,
  7802. hideDisconnected,
  7803. smartPlugCount,
  7804. ]);
  7805. const renderFilterControls = (inMenu = false) => (
  7806. <>
  7807. {/* Status filter */}
  7808. {printers && printers.length > 0 && (
  7809. <ToolbarDropdown
  7810. value={statusFilter}
  7811. onChange={setStatusFilter}
  7812. fullWidth={inMenu}
  7813. options={[
  7814. { value: 'all', label: t('printers.filter.allStatuses') },
  7815. { value: 'printing', label: t('printers.status.printing') },
  7816. { value: 'paused', label: t('printers.status.paused') },
  7817. { value: 'idle', label: t('printers.status.idle') },
  7818. { value: 'finished', label: t('printers.status.finished') },
  7819. { value: 'error', label: t('printers.status.error') },
  7820. { value: 'offline', label: t('printers.status.offline') },
  7821. ]}
  7822. />
  7823. )}
  7824. {/* Location filter — only shown when at least one printer has a location */}
  7825. {printers && printers.length > 0 && availableLocations.length > 0 && (
  7826. <ToolbarDropdown
  7827. value={locationFilter}
  7828. onChange={setLocationFilter}
  7829. fullWidth={inMenu}
  7830. options={[
  7831. { value: 'all', label: t('printers.filter.allLocations') },
  7832. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  7833. ]}
  7834. />
  7835. )}
  7836. <button
  7837. type="button"
  7838. onClick={toggleHideDisconnected}
  7839. aria-pressed={hideDisconnected}
  7840. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  7841. hideDisconnected
  7842. ? 'bg-bambu-green border-bambu-green text-white'
  7843. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7844. }`}
  7845. >
  7846. {t('printers.hideOffline')}
  7847. </button>
  7848. </>
  7849. );
  7850. const renderViewControls = (inMenu = false) => (
  7851. <>
  7852. {/* Sort dropdown */}
  7853. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  7854. <ToolbarDropdown<SortOption>
  7855. value={sortBy}
  7856. onChange={handleSortChange}
  7857. fullWidth={inMenu}
  7858. options={[
  7859. { value: 'name', label: t('printers.sort.name') },
  7860. { value: 'status', label: t('printers.sort.status') },
  7861. { value: 'model', label: t('printers.sort.model') },
  7862. { value: 'location', label: t('printers.sort.location') },
  7863. { value: 'eta', label: t('printers.sort.eta') },
  7864. ]}
  7865. />
  7866. <button
  7867. onClick={toggleSortDirection}
  7868. className="h-8 shrink-0 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center"
  7869. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  7870. >
  7871. {sortAsc ? (
  7872. <ArrowUp className="w-4 h-4 text-white" />
  7873. ) : (
  7874. <ArrowDown className="w-4 h-4 text-white" />
  7875. )}
  7876. </button>
  7877. </div>
  7878. {/* Card size selector */}
  7879. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  7880. {cardSizeLabels.map((label, index) => {
  7881. const size = index + 1;
  7882. const isSelected = cardSize === size;
  7883. return (
  7884. <button
  7885. key={label}
  7886. onClick={() => {
  7887. setCompactDrilldownPrinterId(null);
  7888. setCardSize(size);
  7889. localStorage.setItem('printerCardSize', String(size));
  7890. }}
  7891. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  7892. index === 0 ? 'rounded-l-lg' : ''
  7893. } ${
  7894. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  7895. } ${
  7896. isSelected
  7897. ? 'bg-bambu-green text-white'
  7898. : 'text-white hover:bg-bambu-dark-tertiary'
  7899. }`}
  7900. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  7901. >
  7902. {label}
  7903. </button>
  7904. );
  7905. })}
  7906. </div>
  7907. </>
  7908. );
  7909. const renderActionControls = (inMenu = false) => (
  7910. <>
  7911. {/* Bulk select toggle */}
  7912. <button
  7913. onClick={() => {
  7914. if (selectionMode) clearSelection();
  7915. else setIsSelectionMode(true);
  7916. }}
  7917. className={`h-8 px-2 rounded-lg border transition-colors ${inMenu ? 'w-full justify-center gap-1.5 text-sm font-medium flex items-center' : ''} ${
  7918. selectionMode
  7919. ? 'bg-bambu-green border-bambu-green text-white'
  7920. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7921. }`}
  7922. title={t('printers.bulk.select')}
  7923. disabled={!hasPermission('printers:control')}
  7924. >
  7925. <CheckSquare className="w-4 h-4" />
  7926. {inMenu && <span>{t('printers.bulk.select')}</span>}
  7927. </button>
  7928. {/* Power dropdown for offline printers with smart plugs */}
  7929. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  7930. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  7931. <button
  7932. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  7933. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  7934. inMenu
  7935. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  7936. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7937. }`}
  7938. >
  7939. <span className="flex items-center gap-1.5">
  7940. <Power className="w-4 h-4" />
  7941. {t('printers.powerOn')}
  7942. </span>
  7943. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  7944. </button>
  7945. {showPowerDropdown && (
  7946. <>
  7947. {/* Backdrop to close dropdown */}
  7948. <div
  7949. className="fixed inset-0 z-10"
  7950. onClick={() => setShowPowerDropdown(false)}
  7951. />
  7952. <div className="absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1">
  7953. <div className="px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary">
  7954. {t('printers.offlinePrintersWithPlugs')}
  7955. </div>
  7956. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  7957. <PowerDropdownItem
  7958. key={printer.id}
  7959. printer={printer}
  7960. plug={smartPlugByPrinter[printer.id]}
  7961. onPowerOn={(plugId) => {
  7962. setPoweringOn(plugId);
  7963. powerOnMutation.mutate(plugId);
  7964. }}
  7965. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  7966. />
  7967. ))}
  7968. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  7969. <div className="px-3 py-2 text-sm text-bambu-gray">
  7970. No printers with smart plugs
  7971. </div>
  7972. )}
  7973. </div>
  7974. </>
  7975. )}
  7976. </div>
  7977. )}
  7978. <Button
  7979. onClick={() => setShowAddModal(true)}
  7980. disabled={!hasPermission('printers:create')}
  7981. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  7982. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  7983. >
  7984. <Plus className="w-4 h-4" />
  7985. {t('printers.addPrinter')}
  7986. </Button>
  7987. </>
  7988. );
  7989. return (
  7990. <div className="p-4 md:p-8">
  7991. <div className="space-y-3 mb-6">
  7992. <div>
  7993. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  7994. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  7995. {t('printers.title')}
  7996. </h1>
  7997. <StatusSummaryBar printers={printers} />
  7998. </div>
  7999. <div ref={toolbarRef} className="relative flex items-center gap-2">
  8000. {/* Only show search bar when printers exist */}
  8001. {printers && printers.length > 0 && (
  8002. <div className="relative min-w-0 flex-1">
  8003. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  8004. <input
  8005. type="search"
  8006. name="printer-search"
  8007. autoComplete="off"
  8008. data-1p-ignore
  8009. data-lpignore="true"
  8010. value={search}
  8011. onChange={(e) => setSearch(e.target.value)}
  8012. placeholder={t('printers.search')}
  8013. aria-label={t('printers.search')}
  8014. className="w-full h-8 pl-9 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  8015. />
  8016. {search && (
  8017. <button
  8018. type="button"
  8019. aria-label={t('common.clear')}
  8020. onClick={() => setSearch('')}
  8021. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  8022. >
  8023. <X className="w-4 h-4" />
  8024. </button>
  8025. )}
  8026. </div>
  8027. )}
  8028. <div
  8029. ref={expandedToolbarControlsRef}
  8030. aria-hidden={compactToolbar}
  8031. inert={compactToolbar}
  8032. className={`${compactToolbar ? 'absolute -left-[9999px] top-0 flex w-max pointer-events-none opacity-0' : 'flex'} ml-auto items-center justify-end gap-2 flex-nowrap [&>*]:shrink-0`}
  8033. >
  8034. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8035. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  8036. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8037. <div className="flex items-center gap-2">{renderViewControls()}</div>
  8038. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8039. <div className="flex items-center gap-2">{renderActionControls()}</div>
  8040. </div>
  8041. {compactToolbar && (
  8042. <div className="ml-auto flex items-center justify-end gap-1">
  8043. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  8044. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  8045. </ToolbarMenu>
  8046. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  8047. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  8048. </ToolbarMenu>
  8049. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  8050. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  8051. </ToolbarMenu>
  8052. </div>
  8053. )}
  8054. </div>
  8055. </div>
  8056. {isLoading ? (
  8057. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  8058. ) : printers?.length === 0 ? (
  8059. <Card>
  8060. <CardContent className="text-center py-12">
  8061. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  8062. <Button
  8063. onClick={() => setShowAddModal(true)}
  8064. disabled={!hasPermission('printers:create')}
  8065. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8066. >
  8067. <Plus className="w-4 h-4" />
  8068. {t('printers.addPrinter')}
  8069. </Button>
  8070. </CardContent>
  8071. </Card>
  8072. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  8073. <Card>
  8074. <CardContent className="text-center py-12">
  8075. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  8076. </CardContent>
  8077. </Card>
  8078. ) : groupedPrinters ? (
  8079. /* Grouped view (location, status, or model) */
  8080. <div className="space-y-6">
  8081. {(() => {
  8082. const keys = sortBy === 'status'
  8083. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  8084. : Object.keys(groupedPrinters);
  8085. // For status grouping, asc/desc flips the fixed priority order
  8086. // (asc = error→offline, desc = offline→error). This matches the
  8087. // sort-toggle behaviour for other groupings.
  8088. return (sortAsc ? keys : [...keys].reverse());
  8089. })().map((groupKey) => {
  8090. const groupPrinters = groupedPrinters[groupKey];
  8091. const collapseKey = `${sortBy}:${groupKey}`;
  8092. const isOpen = !collapsedSections[collapseKey];
  8093. const dot = sortBy === 'status'
  8094. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  8095. : 'bg-bambu-green';
  8096. const label = sortBy === 'status'
  8097. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  8098. : groupKey;
  8099. return (
  8100. <Collapsible
  8101. key={groupKey}
  8102. open={isOpen}
  8103. onToggle={() => toggleSectionCollapse(collapseKey)}
  8104. summaryClassName="py-1"
  8105. summary={
  8106. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  8107. <span className={`w-2 h-2 rounded-full ${dot}`} />
  8108. {label}
  8109. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  8110. {selectionMode && (
  8111. <button
  8112. onClick={(e) => {
  8113. e.stopPropagation();
  8114. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  8115. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  8116. else if (sortBy === 'model') selectByModel(groupKey);
  8117. }}
  8118. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  8119. >
  8120. {t('printers.bulk.selectAll')}
  8121. </button>
  8122. )}
  8123. </h2>
  8124. }
  8125. >
  8126. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8127. {groupPrinters.map((printer) => (
  8128. <PrinterCard
  8129. key={printer.id}
  8130. printer={printer}
  8131. hideIfDisconnected={hideDisconnected}
  8132. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8133. viewMode={viewMode}
  8134. cardSize={cardSize}
  8135. amsThresholds={settings ? {
  8136. humidityGood: Number(settings.ams_humidity_good) || 40,
  8137. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8138. tempGood: Number(settings.ams_temp_good) || 28,
  8139. tempFair: Number(settings.ams_temp_fair) || 35,
  8140. } : undefined}
  8141. spoolmanEnabled={spoolmanEnabled}
  8142. hasUnlinkedSpools={hasUnlinkedSpools}
  8143. linkedSpools={linkedSpools}
  8144. spoolmanUrl={spoolmanStatus?.url}
  8145. spoolmanSyncMode={spoolmanSyncMode}
  8146. onGetAssignment={getAssignment}
  8147. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8148. spoolmanSpools={spoolmanSpools}
  8149. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8150. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8151. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8152. timeFormat={settings?.time_format || 'system'}
  8153. cameraViewMode={settings?.camera_view_mode || 'window'}
  8154. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8155. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8156. dryingPresets={effectiveDryingPresets}
  8157. nozzleTempPresets={effectiveNozzleTempPresets}
  8158. bedTempPresets={effectiveBedTempPresets}
  8159. chamberTempPresets={effectiveChamberTempPresets}
  8160. fanSpeedPresets={effectiveFanSpeedPresets}
  8161. requirePlateClear={settings?.require_plate_clear === true}
  8162. selectionMode={selectionMode}
  8163. isSelected={selectedPrinterIds.has(printer.id)}
  8164. onToggleSelect={toggleSelect}
  8165. onOpenCompactCard={openCompactCard}
  8166. />
  8167. ))}
  8168. </div>
  8169. </Collapsible>
  8170. );
  8171. })}
  8172. </div>
  8173. ) : (
  8174. /* Regular grid view */
  8175. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8176. {sortedPrinters.map((printer) => (
  8177. <PrinterCard
  8178. key={printer.id}
  8179. printer={printer}
  8180. hideIfDisconnected={hideDisconnected}
  8181. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8182. viewMode={viewMode}
  8183. cardSize={cardSize}
  8184. spoolmanEnabled={spoolmanEnabled}
  8185. hasUnlinkedSpools={hasUnlinkedSpools}
  8186. linkedSpools={linkedSpools}
  8187. spoolmanUrl={spoolmanStatus?.url}
  8188. spoolmanSyncMode={spoolmanSyncMode}
  8189. onGetAssignment={getAssignment}
  8190. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8191. spoolmanSpools={spoolmanSpools}
  8192. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8193. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8194. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8195. amsThresholds={settings ? {
  8196. humidityGood: Number(settings.ams_humidity_good) || 40,
  8197. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8198. tempGood: Number(settings.ams_temp_good) || 28,
  8199. tempFair: Number(settings.ams_temp_fair) || 35,
  8200. } : undefined}
  8201. timeFormat={settings?.time_format || 'system'}
  8202. cameraViewMode={settings?.camera_view_mode || 'window'}
  8203. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8204. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8205. dryingPresets={effectiveDryingPresets}
  8206. nozzleTempPresets={effectiveNozzleTempPresets}
  8207. bedTempPresets={effectiveBedTempPresets}
  8208. chamberTempPresets={effectiveChamberTempPresets}
  8209. fanSpeedPresets={effectiveFanSpeedPresets}
  8210. requirePlateClear={settings?.require_plate_clear === true}
  8211. selectionMode={selectionMode}
  8212. isSelected={selectedPrinterIds.has(printer.id)}
  8213. onToggleSelect={toggleSelect}
  8214. onOpenCompactCard={openCompactCard}
  8215. />
  8216. ))}
  8217. </div>
  8218. )}
  8219. {cardSize === 2 && compactDrilldownPrinterId != null && (
  8220. <button
  8221. type="button"
  8222. onClick={returnToCompactCards}
  8223. className={`fixed bottom-5 left-1/2 z-40 inline-flex -translate-x-1/2 items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium shadow-xl transition-colors ${accentButtonClass}`}
  8224. title={t('common.back', 'Back')}
  8225. >
  8226. <ArrowLeft className="w-4 h-4" />
  8227. {t('common.back', 'Back')}
  8228. </button>
  8229. )}
  8230. {showAddModal && (
  8231. <AddPrinterModal
  8232. onClose={() => setShowAddModal(false)}
  8233. onAdd={(data) => addMutation.mutate(data)}
  8234. existingSerials={printers?.map(p => p.serial_number) || []}
  8235. />
  8236. )}
  8237. {/* Bulk selection toolbar */}
  8238. {selectionMode && printers && (
  8239. <BulkPrinterToolbar
  8240. selectedIds={selectedPrinterIds}
  8241. printers={printers}
  8242. onClose={clearSelection}
  8243. onSelectAll={selectAll}
  8244. onSelectByLocation={selectByLocation}
  8245. onSelectByState={selectByState}
  8246. onAction={handleBulkAction}
  8247. actionPending={bulkActionPending}
  8248. />
  8249. )}
  8250. {/* Bulk action confirmation modals */}
  8251. {bulkConfirmAction === 'stop' && (
  8252. <ConfirmModal
  8253. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  8254. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  8255. confirmText={t('printers.bulk.confirm.stopButton')}
  8256. variant="danger"
  8257. isLoading={bulkActionPending}
  8258. onConfirm={() => executeBulkAction('stop')}
  8259. onCancel={() => setBulkConfirmAction(null)}
  8260. />
  8261. )}
  8262. {bulkConfirmAction === 'pause' && (
  8263. <ConfirmModal
  8264. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  8265. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  8266. confirmText={t('printers.bulk.confirm.pauseButton')}
  8267. isLoading={bulkActionPending}
  8268. onConfirm={() => executeBulkAction('pause')}
  8269. onCancel={() => setBulkConfirmAction(null)}
  8270. />
  8271. )}
  8272. {bulkConfirmAction === 'clearPlate' && (
  8273. <ConfirmModal
  8274. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  8275. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  8276. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  8277. isLoading={bulkActionPending}
  8278. onConfirm={() => executeBulkAction('clearPlate')}
  8279. onCancel={() => setBulkConfirmAction(null)}
  8280. />
  8281. )}
  8282. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  8283. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  8284. <EmbeddedCameraViewer
  8285. key={camera.id}
  8286. printerId={camera.id}
  8287. printerName={camera.name}
  8288. viewerIndex={index}
  8289. onClose={() => setEmbeddedCameraPrinters(prev => {
  8290. const next = new Map(prev);
  8291. next.delete(camera.id);
  8292. return next;
  8293. })}
  8294. />
  8295. ))}
  8296. </div>
  8297. );
  8298. }