PrintersPage.tsx 500 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { mapModelCode } from '../utils/printerModel';
  5. import { formatPrintName } from '../utils/printName';
  6. import { isBedSlinger } from '../utils/bedSlinger';
  7. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  8. import {
  9. openCameraWindow,
  10. readStoredCameraViewMode,
  11. storeCameraViewMode,
  12. type CameraViewMode,
  13. } from '../utils/camera';
  14. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  15. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  16. import {
  17. isExternalSpoolHidden,
  18. setExternalSpoolHidden as persistExternalSpoolHidden,
  19. } from '../utils/printerCardPrefs';
  20. import {
  21. BED_TEMP_DEFAULTS,
  22. CHAMBER_TEMP_DEFAULTS,
  23. FAN_SPEED_DEFAULTS,
  24. NOZZLE_TEMP_DEFAULTS,
  25. buildPresetOptions,
  26. parsePresetTriple,
  27. } from '../utils/temperatureFanPresets';
  28. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  29. // covers header + filament select + temp slider + duration + rotate-tray
  30. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  31. // earlier); under-estimating leaves the popover clipped off the bottom (the
  32. // original bug at #1447).
  33. const DRYING_POPOVER_WIDTH = 240;
  34. // Height in "now" mode plus the tallest start-mode control; a conservative
  35. // over-estimate just flips the popover above the trigger sooner.
  36. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  37. // Delay presets for the "After delay" drying start mode, in minutes.
  38. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  39. // Every printer card reads the same fleet-wide scheduled-drying list.
  40. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  41. // Why a due run has not started yet: every waiting_reason the scheduler can
  42. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  43. // for ..." with no hint why nothing is happening.
  44. const WAITING_REASON_KEYS: Record<string, string> = {
  45. ams_power_required: 'printers.drying.powerRequired',
  46. ams_retract_filament: 'printers.drying.retractFilament',
  47. ams_blocked: 'printers.drying.cannotDryNow',
  48. ams_not_found: 'printers.drying.waitingAmsNotFound',
  49. printer_offline: 'printers.drying.waitingOffline',
  50. printer_busy: 'printers.drying.waitingPrinterBusy',
  51. already_drying: 'printers.drying.waitingAlreadyDrying',
  52. interrupted: 'printers.drying.waitingInterrupted',
  53. };
  54. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  55. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  56. }
  57. // Why a scheduled drying failed, by the code the scheduler stores. A row with
  58. // no code (failed before codes existed) or an unknown one shows the backend's
  59. // English error_message instead.
  60. const FAILED_REASON_KEYS: Record<string, string> = {
  61. screen_only: 'printers.drying.screenOnly',
  62. unsupported: 'printers.drying.notSupported',
  63. did_not_start: 'printers.drying.scheduleFailedDidNotStart',
  64. };
  65. function failedReasonKey(code: string | null | undefined): string | undefined {
  66. return code ? FAILED_REASON_KEYS[code] : undefined;
  67. }
  68. // Which cannot-dry code to name when the firmware reports several at once.
  69. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  70. // button's tooltip and a scheduled row's waiting reason describe one blocked
  71. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  72. // left at the outlet, and both need the user to go and do something. The rest
  73. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  74. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  75. const codes = (reasons ?? []).map(r => Number(r));
  76. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  77. if (codes.includes(3)) return 'printers.drying.retractFilament';
  78. return 'printers.drying.cannotDryNow';
  79. }
  80. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  81. import { useTranslation } from 'react-i18next';
  82. import { useTheme } from '../contexts/ThemeContext';
  83. import { useAuth } from '../contexts/AuthContext';
  84. import {
  85. Plus,
  86. Link,
  87. Unlink,
  88. Signal,
  89. Clock,
  90. MoreVertical,
  91. Trash2,
  92. RefreshCw,
  93. RotateCw,
  94. Box,
  95. HardDrive,
  96. AlertTriangle,
  97. AlertCircle,
  98. Terminal,
  99. Power,
  100. Zap,
  101. Wrench,
  102. ChevronDown,
  103. Eye,
  104. EyeOff,
  105. Filter,
  106. Pencil,
  107. ArrowLeft,
  108. ArrowRight,
  109. ArrowUp,
  110. ArrowDown,
  111. Layers,
  112. Video,
  113. Search,
  114. Loader2,
  115. Square,
  116. Pause,
  117. Play,
  118. X,
  119. Fan,
  120. Wind,
  121. AirVent,
  122. Download,
  123. ScanSearch,
  124. CheckCircle,
  125. CheckSquare,
  126. XCircle,
  127. User,
  128. Home,
  129. Printer as PrinterIcon,
  130. Info,
  131. Cable,
  132. Flame,
  133. Hourglass,
  134. Repeat,
  135. Snowflake,
  136. Gauge,
  137. DoorOpen,
  138. DoorClosed,
  139. Move,
  140. LogIn,
  141. LogOut,
  142. MoreHorizontal,
  143. SlidersHorizontal,
  144. Stethoscope,
  145. ScanEye,
  146. LineChart as LineChartIcon,
  147. LayoutGrid,
  148. MonitorPlay,
  149. ExternalLink,
  150. PictureInPicture2,
  151. ThumbsUp,
  152. ThumbsDown,
  153. KeyRound,
  154. } from 'lucide-react';
  155. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  156. // Aliased: lucide-react already exports a `Link` icon into this module.
  157. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  158. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  159. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  160. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  161. import { Card, CardContent } from '../components/Card';
  162. import { Button } from '../components/Button';
  163. import { ConfirmModal } from '../components/ConfirmModal';
  164. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  165. import { FileManagerModal } from '../components/FileManagerModal';
  166. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  167. import { CameraWall } from '../components/CameraWall';
  168. import { DEFAULT_CAM_WALL_TILE_SIZE } from '../components/camWallTileSize';
  169. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  170. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  171. import { HMSErrorModal, filterKnownHMSErrors, isSevereHMSError } from '../components/HMSErrorModal';
  172. import { AiDetectionModal } from '../components/AiDetectionModal';
  173. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  174. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  175. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  176. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  177. import { AmsBackupModal } from '../components/AmsBackupModal';
  178. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  179. import type { HeaterSensorKind } from '../api/client';
  180. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  181. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  182. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  183. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  184. import { useToast } from '../contexts/ToastContext';
  185. import { ChamberLight } from '../components/icons/ChamberLight';
  186. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  187. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  188. import { FileUploadModal } from '../components/FileUploadModal';
  189. import { PrintModal } from '../components/PrintModal';
  190. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  191. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  192. import { getAmsLabel, getEmptySlotKind, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  193. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  194. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  195. import { Collapsible } from '../components/Collapsible';
  196. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  197. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  198. import { NumberInput } from '../components/NumberInput';
  199. import { getCurrencySymbol } from '../utils/currency';
  200. // The status filter's options, and the only values it may hold. One list so a
  201. // saved filter cannot be validated against a set the dropdown has since moved
  202. // on from (#2833). Labels stay literal so they remain greppable.
  203. const STATUS_FILTER_OPTIONS = [
  204. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  205. { value: 'printing', labelKey: 'printers.status.printing' },
  206. { value: 'paused', labelKey: 'printers.status.paused' },
  207. { value: 'idle', labelKey: 'printers.status.idle' },
  208. { value: 'finished', labelKey: 'printers.status.finished' },
  209. { value: 'error', labelKey: 'printers.status.error' },
  210. { value: 'offline', labelKey: 'printers.status.offline' },
  211. ] as const;
  212. function isKnownStatusFilter(value: string | null): boolean {
  213. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  214. }
  215. export interface SpoolmanSlotAssignmentRow {
  216. printer_id: number;
  217. ams_id: number;
  218. tray_id: number;
  219. spoolman_spool_id: number;
  220. }
  221. // Color names resolve via getColorName() which reads the backend color_catalog
  222. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  223. // Format K value with 3 decimal places, default to 0.020 if null
  224. function formatKValue(k: number | null | undefined): string {
  225. const value = k ?? 0.020;
  226. return value.toFixed(3);
  227. }
  228. // K-profile value shown on the slot card itself (#2532) rather than only inside
  229. // the hover popup, the way BambuStudio shows it per slot.
  230. //
  231. // `k` arrives already gated on the slot being loaded; falsy means the printer
  232. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  233. // missing value, which is captioned inside the hover card but would read as a
  234. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  235. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  236. // reported 0 makes that expression evaluate to the number 0, and React renders
  237. // numbers, putting a bare "0" under the material name.
  238. //
  239. // `reserve` holds the row's height open on the slots without a value whenever
  240. // some other slot on the same card has one, so every fill bar stays on one line.
  241. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  242. const { t } = useTranslation();
  243. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  244. if (!k) {
  245. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  246. }
  247. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  248. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  249. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  250. // family per browser and so measured differently in Safari.
  251. return (
  252. <div className={className} title={t('ams.kFactor')}>
  253. {t('ams.kFactorShort')} {formatKValue(k)}
  254. </div>
  255. );
  256. }
  257. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  258. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  259. const { mode } = useTheme();
  260. const { t } = useTranslation();
  261. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  262. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  263. return (
  264. <span
  265. className="inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded"
  266. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  267. title={side === 'L' ? t('common.left') : t('common.right')}
  268. >
  269. {side}
  270. </span>
  271. );
  272. }
  273. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  274. // deliberately a different colour, because it means something different: this
  275. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  276. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  277. const { mode } = useTheme();
  278. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  279. return (
  280. <span
  281. className="inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded"
  282. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  283. title={title}
  284. >
  285. {FTS_INLET_SIDE[inlet]}
  286. </span>
  287. );
  288. }
  289. /**
  290. * Which side indicator, if any, belongs on an AMS card header.
  291. *
  292. * Three sources, in descending authority:
  293. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  294. * through the switch, so the inlet is the only meaningful label.
  295. * 2. A real extruder id from ams_extruder_map.
  296. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  297. * never reported a map. This one is only a guess, and it is suppressed
  298. * when a switch is installed: with an FTS every unit reports extruder
  299. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  300. * nothing but their unit numbers.
  301. */
  302. function amsSideBadge(
  303. amsId: number,
  304. amsExtruderMap: Record<string, number>,
  305. amsSwitchInlet: Record<string, 'A' | 'B'>,
  306. ftsInstalled: boolean
  307. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  308. const inlet = amsSwitchInlet[String(amsId)];
  309. if (inlet) return { kind: 'inlet', inlet };
  310. const mapped = amsExtruderMap[String(amsId)];
  311. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  312. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  313. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  314. return null;
  315. }
  316. // Expand nozzle type codes to material names
  317. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  318. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  319. function nozzleTypeName(type: string, t: (key: string) => string): string {
  320. if (!type) return '';
  321. // Full text names (from main nozzle info)
  322. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  323. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  324. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  325. // 4-char codes (e.g. "HS01"): last 2 digits = material
  326. if (type.length >= 4) {
  327. const material = type.slice(2, 4);
  328. if (material === '00') return t('printers.nozzleStainlessSteel');
  329. if (material === '01') return t('printers.nozzleHardenedSteel');
  330. if (material === '05') return t('printers.nozzleTungstenCarbide');
  331. }
  332. // 2-digit numeric codes
  333. if (type === '00') return t('printers.nozzleStainlessSteel');
  334. if (type === '01') return t('printers.nozzleHardenedSteel');
  335. if (type === '05') return t('printers.nozzleTungstenCarbide');
  336. // 2-char alpha codes: H prefix = hardened steel
  337. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  338. return type;
  339. }
  340. // Parse flow type from nozzle type code
  341. // HH = high flow, HS = standard/normal
  342. function nozzleFlowName(type: string, t: (key: string) => string): string {
  343. if (!type) return '';
  344. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  345. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  346. return '';
  347. }
  348. // Per-slot hover card for nozzle rack
  349. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  350. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  351. slot: import('../api/client').NozzleRackSlot;
  352. index: number;
  353. activeStatus?: boolean;
  354. filamentName?: string;
  355. children: React.ReactNode;
  356. }) {
  357. const { t } = useTranslation();
  358. const [isVisible, setIsVisible] = useState(false);
  359. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  360. const triggerRef = useRef<HTMLDivElement>(null);
  361. const cardRef = useRef<HTMLDivElement>(null);
  362. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  363. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  364. const isMounted = slot.stat === 1;
  365. useEffect(() => {
  366. if (isVisible && triggerRef.current && cardRef.current) {
  367. const triggerRect = triggerRef.current.getBoundingClientRect();
  368. const cardHeight = cardRef.current.offsetHeight;
  369. const headerHeight = 56;
  370. const spaceAbove = triggerRect.top - headerHeight;
  371. const spaceBelow = window.innerHeight - triggerRect.bottom;
  372. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  373. setPosition('bottom');
  374. } else {
  375. setPosition('top');
  376. }
  377. }
  378. }, [isVisible]);
  379. const handleMouseEnter = () => {
  380. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  381. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  382. };
  383. const handleMouseLeave = () => {
  384. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  385. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  386. };
  387. useEffect(() => {
  388. return () => {
  389. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  390. };
  391. }, []);
  392. const filamentCss = parseFilamentColor(slot.filament_color);
  393. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  394. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  395. return (
  396. <div
  397. ref={triggerRef}
  398. className="relative"
  399. onMouseEnter={handleMouseEnter}
  400. onMouseLeave={handleMouseLeave}
  401. >
  402. {children}
  403. {isVisible && (
  404. <div
  405. ref={cardRef}
  406. className={`
  407. absolute left-1/2 -translate-x-1/2 z-50
  408. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  409. animate-in fade-in-0 zoom-in-95 duration-150
  410. `}
  411. style={{ maxWidth: 'calc(100vw - 24px)' }}
  412. >
  413. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  414. {isEmpty ? (
  415. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  416. Slot {index + 1} — Empty
  417. </div>
  418. ) : (
  419. <div className="p-2.5 space-y-1.5">
  420. {/* Diameter */}
  421. <div className="flex items-center justify-between">
  422. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  423. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  424. </div>
  425. {/* Type */}
  426. {typeFull && (
  427. <div className="flex items-center justify-between">
  428. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  429. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  430. </div>
  431. )}
  432. {/* Flow (hide if empty) */}
  433. {flowFull && (
  434. <div className="flex items-center justify-between">
  435. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  436. <span className="text-xs text-white font-semibold">{flowFull}</span>
  437. </div>
  438. )}
  439. {/* Status badge */}
  440. <div className="flex items-center justify-between">
  441. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  442. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  443. activeStatus || isMounted
  444. ? 'bg-green-900/50 text-green-400'
  445. : 'bg-bambu-dark-tertiary text-bambu-gray'
  446. }`}>
  447. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  448. </span>
  449. </div>
  450. {/* Wear (hide if null) */}
  451. {slot.wear != null && (
  452. <div className="flex items-center justify-between">
  453. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  454. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  455. </div>
  456. )}
  457. {/* Max Temp (hide if 0) */}
  458. {slot.max_temp > 0 && (
  459. <div className="flex items-center justify-between">
  460. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  461. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  462. </div>
  463. )}
  464. {/* Serial (hide if empty) */}
  465. {slot.serial_number && (
  466. <div className="flex items-center justify-between">
  467. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  468. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  469. </div>
  470. )}
  471. {/* Filament: material type + color swatch (hide if no color) */}
  472. {(filamentCss || slot.filament_type) && (
  473. <div className="flex items-center justify-between">
  474. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  475. <div className="flex items-center gap-1">
  476. {filamentCss && (
  477. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  478. )}
  479. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  480. </div>
  481. </div>
  482. )}
  483. </div>
  484. )}
  485. </div>
  486. {/* Arrow pointer */}
  487. <div
  488. className={`
  489. absolute left-1/2 -translate-x-1/2 w-0 h-0
  490. border-l-[6px] border-l-transparent
  491. border-r-[6px] border-r-transparent
  492. ${position === 'top'
  493. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  494. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  495. `}
  496. />
  497. </div>
  498. )}
  499. </div>
  500. );
  501. }
  502. // Dual-nozzle hover card showing L and R nozzle details side by side
  503. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  504. leftSlot?: import('../api/client').NozzleRackSlot;
  505. rightSlot?: import('../api/client').NozzleRackSlot;
  506. activeNozzle: 'L' | 'R';
  507. filamentInfo?: Record<string, { name: string; k: number | null }>;
  508. children: React.ReactNode;
  509. }) {
  510. const { t } = useTranslation();
  511. const [isVisible, setIsVisible] = useState(false);
  512. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  513. const triggerRef = useRef<HTMLDivElement>(null);
  514. const cardRef = useRef<HTMLDivElement>(null);
  515. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  516. useEffect(() => {
  517. if (isVisible && triggerRef.current && cardRef.current) {
  518. const triggerRect = triggerRef.current.getBoundingClientRect();
  519. const cardHeight = cardRef.current.offsetHeight;
  520. const headerHeight = 56;
  521. const spaceAbove = triggerRect.top - headerHeight;
  522. const spaceBelow = window.innerHeight - triggerRect.bottom;
  523. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  524. setPosition('bottom');
  525. } else {
  526. setPosition('top');
  527. }
  528. }
  529. }, [isVisible]);
  530. const handleMouseEnter = () => {
  531. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  532. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  533. };
  534. const handleMouseLeave = () => {
  535. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  536. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  537. };
  538. useEffect(() => {
  539. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  540. }, []);
  541. if (!leftSlot && !rightSlot) return <>{children}</>;
  542. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  543. const isActive = activeNozzle === side;
  544. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  545. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  546. const filamentCss = parseFilamentColor(slot.filament_color);
  547. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  548. return (
  549. <div className="flex-1 space-y-1.5">
  550. <div className={`text-[length:var(--pc-t10,10px)] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-700 dark:text-amber-400' : 'text-bambu-gray'}`}>
  551. {side === 'L' ? t('common.left') : t('common.right')}
  552. </div>
  553. {slot.nozzle_diameter && (
  554. <div className="flex items-center justify-between">
  555. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  556. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  557. </div>
  558. )}
  559. {typeFull && (
  560. <div className="flex items-center justify-between">
  561. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  562. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  563. </div>
  564. )}
  565. {flowFull && (
  566. <div className="flex items-center justify-between">
  567. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  568. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  569. </div>
  570. )}
  571. <div className="flex items-center justify-between">
  572. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  573. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  574. isActive
  575. ? 'bg-green-900/50 text-green-400'
  576. : 'bg-bambu-dark-tertiary text-bambu-gray'
  577. }`}>
  578. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  579. </span>
  580. </div>
  581. {slot.wear != null && (
  582. <div className="flex items-center justify-between">
  583. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  584. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  585. </div>
  586. )}
  587. {/* Serial and max temp only available on the right (removable) nozzle */}
  588. {side === 'R' && slot.max_temp > 0 && (
  589. <div className="flex items-center justify-between">
  590. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  591. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  592. </div>
  593. )}
  594. {side === 'R' && slot.serial_number && (
  595. <div className="flex items-center justify-between">
  596. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  597. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  598. </div>
  599. )}
  600. {(filamentCss || slot.filament_type || slot.filament_id) && (
  601. <div className="flex items-center justify-between">
  602. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  603. <div className="flex items-center gap-1">
  604. {filamentCss && (
  605. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  606. )}
  607. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  608. {filamentName || slot.filament_type || slot.filament_id || ''}
  609. </span>
  610. </div>
  611. </div>
  612. )}
  613. </div>
  614. );
  615. };
  616. return (
  617. <div
  618. ref={triggerRef}
  619. className="relative flex-1"
  620. onMouseEnter={handleMouseEnter}
  621. onMouseLeave={handleMouseLeave}
  622. >
  623. {children}
  624. {isVisible && (
  625. <div
  626. ref={cardRef}
  627. className={`
  628. absolute left-1/2 -translate-x-1/2 z-50
  629. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  630. animate-in fade-in-0 zoom-in-95 duration-150
  631. `}
  632. style={{ maxWidth: 'calc(100vw - 24px)' }}
  633. >
  634. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  635. <div className="p-2.5 flex gap-3">
  636. {leftSlot && renderColumn(leftSlot, 'L')}
  637. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  638. {rightSlot && renderColumn(rightSlot, 'R')}
  639. </div>
  640. </div>
  641. {/* Arrow pointer */}
  642. <div
  643. className={`
  644. absolute left-1/2 -translate-x-1/2 w-0 h-0
  645. border-l-[6px] border-l-transparent
  646. border-r-[6px] border-r-transparent
  647. ${position === 'top'
  648. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  649. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  650. `}
  651. />
  652. </div>
  653. )}
  654. </div>
  655. );
  656. }
  657. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  658. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  659. const { t } = useTranslation();
  660. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  661. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  662. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  663. // base — computing it from min(present IDs) shifts everything left when slot 16
  664. // is the one currently mounted (#943).
  665. const rackNozzles = slots.filter(s => s.id >= 2);
  666. const RACK_SIZE = 6;
  667. const RACK_BASE_ID = 16;
  668. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  669. { length: RACK_SIZE },
  670. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  671. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  672. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  673. },
  674. );
  675. return (
  676. // Sized to its contents rather than growing: the six chips are a fixed
  677. // width at any one card size, so extra width would be dead space taken
  678. // from the temperature cards beside it — which are flex-1 with a 0 basis
  679. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  680. // stays enabled so the card still gives way on a narrow printer card
  681. // instead of overflowing.
  682. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  683. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  684. <div className="flex gap-[3px] justify-center">
  685. {rackSlots.map((slot, i) => {
  686. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  687. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  688. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  689. return (
  690. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  691. <div className="flex flex-col items-center gap-0.5">
  692. <div
  693. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  694. isEmpty
  695. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  696. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  697. }`}
  698. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  699. >
  700. <span
  701. data-rack-diameter
  702. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  703. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  704. >
  705. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  706. </span>
  707. </div>
  708. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  709. acted on without counting chips. Sits below the chip rather
  710. than inside it: the chip is barely wider than its own
  711. diameter text and already carries that over a
  712. filament-coloured background. */}
  713. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  714. {i + 1}
  715. </span>
  716. </div>
  717. </NozzleSlotHoverCard>
  718. );
  719. })}
  720. </div>
  721. </div>
  722. );
  723. }
  724. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  725. function WaterDropEmpty({ className }: { className?: string }) {
  726. return (
  727. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  728. <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"/>
  729. </svg>
  730. );
  731. }
  732. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  733. function WaterDropHalf({ className }: { className?: string }) {
  734. return (
  735. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  736. <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"/>
  737. <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"/>
  738. </svg>
  739. );
  740. }
  741. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  742. function WaterDropFull({ className }: { className?: string }) {
  743. return (
  744. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  745. <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"/>
  746. <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"/>
  747. </svg>
  748. );
  749. }
  750. // Thermometer SVG - empty outline
  751. function ThermometerEmpty({ className }: { className?: string }) {
  752. return (
  753. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  754. <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"/>
  755. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  756. </svg>
  757. );
  758. }
  759. // Thermometer SVG - half filled (gold - same as humidity fair)
  760. function ThermometerHalf({ className }: { className?: string }) {
  761. return (
  762. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  763. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  764. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  765. <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"/>
  766. </svg>
  767. );
  768. }
  769. // Thermometer SVG - fully filled (red - same as humidity bad)
  770. function ThermometerFull({ className }: { className?: string }) {
  771. return (
  772. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  773. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  774. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  775. <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"/>
  776. </svg>
  777. );
  778. }
  779. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  780. // Added for visual parity with the thermometer icons on the dual-nozzle card
  781. // that previously had no icon at all (#1115, design by @m4rtini2).
  782. function NozzleIcon({ className }: { className?: string }) {
  783. return (
  784. <svg
  785. className={className}
  786. viewBox="0 0 24 24"
  787. fill="none"
  788. xmlns="http://www.w3.org/2000/svg"
  789. stroke="currentColor"
  790. strokeWidth="1.5"
  791. strokeLinecap="round"
  792. strokeLinejoin="round"
  793. >
  794. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  795. <rect x="6" y="11.5" width="12.1" height="3.7" />
  796. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  797. </svg>
  798. );
  799. }
  800. // Heater thermometer icon - filled when heating, outline when off
  801. interface HeaterThermometerProps {
  802. className?: string;
  803. color: string; // The color class (e.g., "text-orange-400")
  804. isHeating: boolean;
  805. }
  806. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  807. // Extract the actual color from Tailwind class for SVG fill
  808. const colorMap: Record<string, string> = {
  809. 'text-orange-400': '#fb923c',
  810. 'text-blue-400': '#60a5fa',
  811. 'text-green-400': '#4ade80',
  812. };
  813. const fillColor = colorMap[color] || '#888';
  814. // Glow style when heating
  815. const glowStyle = isHeating ? {
  816. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  817. } : {};
  818. if (isHeating) {
  819. // Filled thermometer with glow - heater is ON
  820. return (
  821. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  822. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  823. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  824. <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"/>
  825. </svg>
  826. );
  827. }
  828. // Empty thermometer - heater is OFF
  829. return (
  830. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  831. <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"/>
  832. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  833. </svg>
  834. );
  835. }
  836. // AMS Filament Backup tri-state indicator + toggle.
  837. // state=true → ON, click to disable
  838. // state=false → OFF, click opens modal
  839. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  840. interface AmsBackupBadgeProps {
  841. state: boolean | null;
  842. onClick: () => void;
  843. }
  844. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  845. const { t } = useTranslation();
  846. const known = state !== null;
  847. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  848. let title: string;
  849. if (state === true) {
  850. className += known
  851. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  852. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  853. title = t('printers.amsBackup.titleOn');
  854. } else if (state === false) {
  855. className += known
  856. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  857. : 'bg-bambu-dark text-bambu-gray cursor-default';
  858. title = t('printers.amsBackup.titleOff');
  859. } else {
  860. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  861. title = t('printers.amsBackup.titleUnknown');
  862. }
  863. return (
  864. <button
  865. type="button"
  866. disabled={!known}
  867. onClick={() => known && onClick()}
  868. className={className}
  869. title={title}
  870. aria-label={title}
  871. >
  872. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  873. </button>
  874. );
  875. }
  876. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  877. // like AmsBackupBadge so the two sit together in the section header, but
  878. // pinned to the right-hand end of the rule: this is a view preference for the
  879. // row, not a property of the printer.
  880. interface ExternalSpoolToggleProps {
  881. hidden: boolean;
  882. onClick: () => void;
  883. }
  884. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  885. const { t } = useTranslation();
  886. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  887. return (
  888. <button
  889. type="button"
  890. onClick={onClick}
  891. aria-pressed={hidden}
  892. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  893. hidden
  894. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  895. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  896. }`}
  897. title={title}
  898. aria-label={title}
  899. >
  900. {hidden ? <EyeOff className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Eye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  901. </button>
  902. );
  903. }
  904. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  905. // Reference: https://github.com/theicedmango/bambu-humidity
  906. interface HumidityIndicatorProps {
  907. humidity: number | string;
  908. goodThreshold?: number; // <= this is green
  909. fairThreshold?: number; // <= this is orange, > is red
  910. onClick?: () => void;
  911. compact?: boolean; // Smaller version for grid layout
  912. }
  913. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  914. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  915. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  916. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  917. // Status thresholds (configurable via settings)
  918. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  919. let textColor: string;
  920. let statusText: string;
  921. if (isNaN(humidityValue)) {
  922. textColor = '#C3C2C1';
  923. statusText = 'Unknown';
  924. } else if (humidityValue <= good) {
  925. textColor = '#22a352'; // Green - Good
  926. statusText = 'Good';
  927. } else if (humidityValue <= fair) {
  928. textColor = '#d4a017'; // Gold - Fair
  929. statusText = 'Fair';
  930. } else {
  931. textColor = '#c62828'; // Red - Bad
  932. statusText = 'Bad';
  933. }
  934. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  935. let DropComponent: React.FC<{ className?: string }>;
  936. if (isNaN(humidityValue)) {
  937. DropComponent = WaterDropEmpty;
  938. } else if (humidityValue <= good) {
  939. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  940. } else if (humidityValue <= fair) {
  941. DropComponent = WaterDropHalf; // Fair - half filled
  942. } else {
  943. DropComponent = WaterDropFull; // Bad - full (too humid)
  944. }
  945. return (
  946. <button
  947. type="button"
  948. onClick={onClick}
  949. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  950. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  951. >
  952. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  953. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  954. </button>
  955. );
  956. }
  957. // Temperature indicator with dynamic icon and coloring
  958. interface TemperatureIndicatorProps {
  959. temp: number;
  960. goodThreshold?: number; // <= this is blue
  961. fairThreshold?: number; // <= this is orange, > is red
  962. onClick?: () => void;
  963. compact?: boolean; // Smaller version for grid layout
  964. }
  965. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  966. // Ensure thresholds are numbers
  967. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  968. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  969. let textColor: string;
  970. let statusText: string;
  971. let ThermoComponent: React.FC<{ className?: string }>;
  972. if (temp <= good) {
  973. textColor = '#22a352'; // Green - good (same as humidity)
  974. statusText = 'Good';
  975. ThermoComponent = ThermometerEmpty;
  976. } else if (temp <= fair) {
  977. textColor = '#d4a017'; // Gold - fair (same as humidity)
  978. statusText = 'Fair';
  979. ThermoComponent = ThermometerHalf;
  980. } else {
  981. textColor = '#c62828'; // Red - bad (same as humidity)
  982. statusText = 'Bad';
  983. ThermoComponent = ThermometerFull;
  984. }
  985. return (
  986. <button
  987. type="button"
  988. onClick={onClick}
  989. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  990. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  991. >
  992. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  993. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  994. </button>
  995. );
  996. }
  997. // How long to wait for an AMS to report a live drying cycle after the printer
  998. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  999. // within a couple of seconds; 30s covers the slowest observed push cadence
  1000. // without leaving the user waiting on a verdict.
  1001. const DRY_START_CONFIRM_MS = 30_000;
  1002. export function CoverImage({
  1003. url,
  1004. printName,
  1005. className = 'w-20 h-20',
  1006. radiusClass = 'rounded-lg',
  1007. }: {
  1008. url: string | null;
  1009. printName?: string;
  1010. className?: string;
  1011. radiusClass?: string;
  1012. }) {
  1013. const { t } = useTranslation();
  1014. const [loaded, setLoaded] = useState(false);
  1015. const [error, setError] = useState(false);
  1016. const [showOverlay, setShowOverlay] = useState(false);
  1017. const imgRef = useRef<HTMLImageElement>(null);
  1018. // Cache-bust the image URL when the print name changes so the browser
  1019. // fetches the new cover instead of serving the stale cached image.
  1020. const cacheBustedUrl = useMemo(() => {
  1021. if (!url) return null;
  1022. const sep = url.includes('?') ? '&' : '?';
  1023. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1024. }, [url, printName]);
  1025. // Re-evaluate load state when the image URL changes, and ask the element
  1026. // whether it is already showing something rather than assuming it is not.
  1027. //
  1028. // `onLoad` used to be the only thing that could set `loaded`, and this
  1029. // effect reset it to false unconditionally. That is right when the URL
  1030. // really changes, but it also runs on mount — and the two are not the same
  1031. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1032. // constant for the duration of a print, so navigating away from the
  1033. // printers page and back re-mounts with a byte-identical src that the
  1034. // browser serves from its in-memory cache. The `load` event for a cache hit
  1035. // and React's passive-effect flush are both plain tasks with no ordering
  1036. // between them, so when `load` won, this effect ran afterwards and undid
  1037. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1038. // sat there until a full reload. Nothing recovered it, because the URL
  1039. // never changes again during the print and so this effect never re-runs.
  1040. //
  1041. // Being a race, it reproduced every time for #2826's reporter and not at
  1042. // all here, which is also why the network panel showed no request: there
  1043. // was no request to show.
  1044. //
  1045. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1046. // which of the two ran first. It is also correct for the case the reporter
  1047. // proposed (a `load` that fires before React's handler is live), so the
  1048. // fix stands whichever mechanism is really at work.
  1049. useEffect(() => {
  1050. setError(false);
  1051. const el = imgRef.current;
  1052. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1053. }, [cacheBustedUrl]);
  1054. return (
  1055. <>
  1056. <div
  1057. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1058. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1059. >
  1060. {cacheBustedUrl && !error ? (
  1061. <>
  1062. <img
  1063. ref={imgRef}
  1064. src={cacheBustedUrl}
  1065. alt={t('printers.printPreview')}
  1066. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1067. onLoad={() => setLoaded(true)}
  1068. onError={() => setError(true)}
  1069. />
  1070. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1071. </>
  1072. ) : (
  1073. <Box className="w-8 h-8 text-bambu-gray" />
  1074. )}
  1075. </div>
  1076. {/* Cover Image Overlay */}
  1077. {showOverlay && cacheBustedUrl && (
  1078. <div
  1079. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1080. onClick={() => setShowOverlay(false)}
  1081. >
  1082. <div className="relative max-w-2xl max-h-full">
  1083. <img
  1084. src={cacheBustedUrl}
  1085. alt={t('printers.printPreview')}
  1086. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1087. />
  1088. {printName && (
  1089. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1090. )}
  1091. </div>
  1092. </div>
  1093. )}
  1094. </>
  1095. );
  1096. }
  1097. interface PrinterMaintenanceInfo {
  1098. due_count: number;
  1099. warning_count: number;
  1100. total_print_hours: number;
  1101. }
  1102. // Status summary bar component - uses queryClient to read cached statuses
  1103. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1104. const { t } = useTranslation();
  1105. const queryClient = useQueryClient();
  1106. // Subscribe to query cache changes to re-render when status updates
  1107. // Throttled to prevent rapid re-renders from causing tab crashes
  1108. const [cacheTick, setCacheTick] = useState(0);
  1109. useEffect(() => {
  1110. let pending = false;
  1111. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1112. if (!pending) {
  1113. pending = true;
  1114. requestAnimationFrame(() => {
  1115. setCacheTick(t => t + 1);
  1116. pending = false;
  1117. });
  1118. }
  1119. });
  1120. return () => unsubscribe();
  1121. }, [queryClient]);
  1122. const { counts, nextFinish } = useMemo(() => {
  1123. let printing = 0;
  1124. let paused = 0;
  1125. let finished = 0;
  1126. let idle = 0;
  1127. let offline = 0;
  1128. let loading = 0;
  1129. let error = 0;
  1130. let nextPrinterName: string | null = null;
  1131. let nextRemainingMin: number | null = null;
  1132. let nextProgress: number = 0;
  1133. printers?.forEach((printer) => {
  1134. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1135. if (status === undefined) {
  1136. // Status not yet loaded - don't count as offline yet
  1137. loading++;
  1138. } else if (!status.connected) {
  1139. offline++;
  1140. } else {
  1141. // Count printers with active HMS errors as problems
  1142. const knownHmsCount =
  1143. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1144. if (knownHmsCount > 0) {
  1145. error++;
  1146. }
  1147. switch (status.state) {
  1148. case 'RUNNING':
  1149. printing++;
  1150. if (status.remaining_time != null && status.remaining_time > 0) {
  1151. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1152. nextRemainingMin = status.remaining_time;
  1153. nextPrinterName = printer.name;
  1154. nextProgress = status.progress || 0;
  1155. }
  1156. }
  1157. break;
  1158. case 'PAUSE':
  1159. paused++;
  1160. break;
  1161. case 'FINISH':
  1162. finished++;
  1163. break;
  1164. case 'FAILED':
  1165. // FAILED is the printer's terminal gcode_state after a print stops —
  1166. // including user cancellations, where there's no actual fault. Only
  1167. // count it as a "problem" when an HMS error is also active; otherwise
  1168. // it's just a print that ended unsuccessfully and the plate needs
  1169. // clearing (same as FINISH from the operator's perspective).
  1170. if (knownHmsCount > 0) {
  1171. // Already counted above
  1172. } else {
  1173. finished++;
  1174. }
  1175. break;
  1176. default:
  1177. idle++;
  1178. break;
  1179. }
  1180. }
  1181. });
  1182. return {
  1183. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1184. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1185. };
  1186. // eslint-disable-next-line react-hooks/exhaustive-deps
  1187. }, [printers, queryClient, cacheTick]);
  1188. if (!printers?.length) return null;
  1189. const badges: { count: number; dot: string; label: string }[] = [
  1190. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1191. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1192. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1193. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1194. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1195. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1196. ];
  1197. return (
  1198. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1199. {badges.map(({ count, dot, label }) => count > 0 && (
  1200. <div key={label} className="flex items-center gap-1.5">
  1201. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1202. <span className="text-bambu-gray">
  1203. <span className="text-white font-medium">{count}</span> {label}
  1204. </span>
  1205. </div>
  1206. ))}
  1207. {nextFinish && (
  1208. <>
  1209. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1210. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1211. <div className="flex items-center gap-2">
  1212. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1213. <span className="text-white font-medium">{nextFinish.name}</span>
  1214. </div>
  1215. <div className="flex items-center gap-2 w-full sm:w-auto">
  1216. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1217. <div
  1218. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1219. style={{ width: `${nextFinish.progress}%` }}
  1220. />
  1221. </div>
  1222. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1223. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1224. </div>
  1225. </div>
  1226. </>
  1227. )}
  1228. </div>
  1229. );
  1230. }
  1231. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1232. type ViewMode = 'expanded' | 'compact';
  1233. type ToolbarDropdownOption<T extends string> = {
  1234. value: T;
  1235. label: string;
  1236. };
  1237. function ToolbarDropdown<T extends string>({
  1238. value,
  1239. options,
  1240. onChange,
  1241. fullWidth = false,
  1242. }: {
  1243. value: T;
  1244. options: ToolbarDropdownOption<T>[];
  1245. onChange: (value: T) => void;
  1246. fullWidth?: boolean;
  1247. }) {
  1248. const [isOpen, setIsOpen] = useState(false);
  1249. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1250. return (
  1251. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1252. <button
  1253. type="button"
  1254. onClick={() => setIsOpen(open => !open)}
  1255. 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'}`}
  1256. >
  1257. <span className="truncate">{selectedOption?.label}</span>
  1258. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1259. </button>
  1260. {isOpen && (
  1261. <>
  1262. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1263. <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">
  1264. {options.map(option => (
  1265. <button
  1266. key={option.value}
  1267. type="button"
  1268. onClick={() => {
  1269. onChange(option.value);
  1270. setIsOpen(false);
  1271. }}
  1272. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1273. option.value === value ? 'text-bambu-green' : 'text-white'
  1274. }`}
  1275. >
  1276. {option.label}
  1277. </button>
  1278. ))}
  1279. </div>
  1280. </>
  1281. )}
  1282. </div>
  1283. );
  1284. }
  1285. function ToolbarMenu({
  1286. label,
  1287. icon,
  1288. children,
  1289. }: {
  1290. label: string;
  1291. icon: React.ReactNode;
  1292. children: React.ReactNode;
  1293. }) {
  1294. const [isOpen, setIsOpen] = useState(false);
  1295. return (
  1296. <div className="relative">
  1297. <button
  1298. type="button"
  1299. onClick={() => setIsOpen(open => !open)}
  1300. 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"
  1301. aria-label={label}
  1302. title={label}
  1303. >
  1304. {icon}
  1305. </button>
  1306. {isOpen && (
  1307. <>
  1308. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1309. <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">
  1310. {children}
  1311. </div>
  1312. </>
  1313. )}
  1314. </div>
  1315. );
  1316. }
  1317. function IndicatorControlPopover({
  1318. title,
  1319. options = [],
  1320. unit,
  1321. customMin,
  1322. customMax,
  1323. customStep = 1,
  1324. widthClass = 'w-[240px]',
  1325. popoverWidth = 240,
  1326. popoverHeight = 280,
  1327. isPending,
  1328. onClose,
  1329. onSubmit,
  1330. children,
  1331. }: {
  1332. title: string;
  1333. options?: Array<{ label: string; value: number }>;
  1334. unit?: string;
  1335. customMin?: number;
  1336. customMax?: number;
  1337. customStep?: number;
  1338. widthClass?: string;
  1339. popoverWidth?: number;
  1340. popoverHeight?: number;
  1341. isPending?: boolean;
  1342. onClose: () => void;
  1343. onSubmit?: (value: number) => void;
  1344. children?: React.ReactNode;
  1345. }) {
  1346. const anchorRef = useRef<HTMLSpanElement>(null);
  1347. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1348. const [customValue, setCustomValue] = useState('');
  1349. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1350. // can position via fixed coords. Portaling to document.body escapes
  1351. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1352. // own contexts and would otherwise cover the popover even at z-[60].
  1353. useLayoutEffect(() => {
  1354. const trigger = anchorRef.current?.parentElement;
  1355. if (!trigger) return;
  1356. const measure = () => {
  1357. const rect = trigger.getBoundingClientRect();
  1358. setCoords(computePopoverPosition({
  1359. triggerRect: rect,
  1360. popoverWidth,
  1361. estimatedHeight: popoverHeight,
  1362. horizontalAlign: 'center',
  1363. }));
  1364. };
  1365. measure();
  1366. window.addEventListener('resize', measure);
  1367. window.addEventListener('scroll', measure, true);
  1368. return () => {
  1369. window.removeEventListener('resize', measure);
  1370. window.removeEventListener('scroll', measure, true);
  1371. };
  1372. }, [popoverWidth, popoverHeight]);
  1373. const showCustomInput = unit !== undefined;
  1374. const submitCustom = () => {
  1375. const value = Number(customValue);
  1376. if (!Number.isFinite(value)) return;
  1377. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1378. onSubmit?.(Math.round(bounded));
  1379. };
  1380. return (
  1381. <>
  1382. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1383. {createPortal(
  1384. <>
  1385. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1386. <div
  1387. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1388. style={{
  1389. top: coords?.top ?? -9999,
  1390. left: coords?.left ?? -9999,
  1391. visibility: coords ? 'visible' : 'hidden',
  1392. }}
  1393. onClick={e => e.stopPropagation()}
  1394. >
  1395. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1396. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1397. {options.length > 0 && (
  1398. <div className="px-3 py-2.5">
  1399. <div className="grid grid-cols-2 gap-1.5">
  1400. {options.map(option => (
  1401. <button
  1402. key={`${option.label}-${option.value}`}
  1403. type="button"
  1404. disabled={isPending}
  1405. onClick={() => onSubmit?.(option.value)}
  1406. 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"
  1407. >
  1408. {option.label}
  1409. </button>
  1410. ))}
  1411. </div>
  1412. </div>
  1413. )}
  1414. {children}
  1415. {showCustomInput && (
  1416. <>
  1417. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1418. <form
  1419. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1420. onSubmit={(e) => {
  1421. e.preventDefault();
  1422. submitCustom();
  1423. }}
  1424. >
  1425. <input
  1426. type="number"
  1427. min={customMin}
  1428. max={customMax}
  1429. step={customStep}
  1430. value={customValue}
  1431. onChange={e => setCustomValue(e.target.value)}
  1432. placeholder="Custom"
  1433. 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"
  1434. />
  1435. <button
  1436. type="submit"
  1437. disabled={isPending || customValue.trim() === ''}
  1438. 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"
  1439. >
  1440. Set
  1441. </button>
  1442. </form>
  1443. </>
  1444. )}
  1445. </div>
  1446. </>,
  1447. document.body
  1448. )}
  1449. </>
  1450. );
  1451. }
  1452. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1453. function NozzleTemperatureControlBox({
  1454. label,
  1455. current,
  1456. target,
  1457. isActive,
  1458. isPending,
  1459. onSubmit,
  1460. options = NOZZLE_TEMPERATURE_OPTIONS,
  1461. }: {
  1462. label: string;
  1463. current?: number;
  1464. target?: number;
  1465. isActive: boolean;
  1466. isPending?: boolean;
  1467. onSubmit: (value: number) => void;
  1468. options?: Array<{ label: string; value: number }>;
  1469. }) {
  1470. const [customValue, setCustomValue] = useState('');
  1471. const submitCustom = () => {
  1472. const value = Number(customValue);
  1473. if (!Number.isFinite(value)) return;
  1474. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1475. };
  1476. return (
  1477. <div className={`rounded-lg border p-2 ${isActive ? 'border-amber-500/60 dark:border-amber-400/60 bg-amber-50 dark:bg-amber-400/10' : 'border-bambu-dark-tertiary bg-bambu-dark'}`}>
  1478. <div className="mb-1.5 flex items-center justify-between gap-2">
  1479. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1480. <span className="text-[10px] text-bambu-gray">
  1481. {Math.round(current ?? 0)}°C
  1482. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1483. </span>
  1484. </div>
  1485. <div className="grid grid-cols-2 gap-1">
  1486. {options.map(option => (
  1487. <button
  1488. key={`${label}-${option.value}`}
  1489. type="button"
  1490. disabled={isPending}
  1491. onClick={() => onSubmit(option.value)}
  1492. 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"
  1493. >
  1494. {option.label}
  1495. </button>
  1496. ))}
  1497. </div>
  1498. <form
  1499. className="mt-1.5 flex gap-1"
  1500. onSubmit={(e) => {
  1501. e.preventDefault();
  1502. submitCustom();
  1503. }}
  1504. >
  1505. <input
  1506. type="number"
  1507. min={0}
  1508. max={320}
  1509. step={1}
  1510. value={customValue}
  1511. onChange={e => setCustomValue(e.target.value)}
  1512. placeholder="Custom"
  1513. 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"
  1514. />
  1515. <button
  1516. type="submit"
  1517. disabled={isPending || customValue.trim() === ''}
  1518. 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"
  1519. >
  1520. Set
  1521. </button>
  1522. </form>
  1523. </div>
  1524. );
  1525. }
  1526. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1527. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1528. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1529. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1530. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1531. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1532. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1533. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1534. };
  1535. /** Classify a printer into one of the UI status buckets. */
  1536. function classifyPrinterStatus(
  1537. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1538. ): PrinterState {
  1539. if (!status?.connected) return 'offline';
  1540. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1541. if (hmsErrors.length > 0) return 'error';
  1542. switch (status.state) {
  1543. case 'RUNNING': return 'printing';
  1544. case 'PAUSE': return 'paused';
  1545. case 'FINISH': return 'finished';
  1546. // FAILED without an active HMS error is the printer's terminal state after
  1547. // any unsuccessful end — including user-cancellations. Treat the same as
  1548. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1549. // HMS code is actually attached (handled by the early-return above).
  1550. case 'FAILED': return 'finished';
  1551. default: return 'idle';
  1552. }
  1553. }
  1554. /**
  1555. * Get human-readable status display text for a printer.
  1556. * Uses stg_cur_name for detailed calibration/preparation stages,
  1557. * otherwise formats the gcode_state nicely.
  1558. */
  1559. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1560. // If we have a specific stage name (calibration, heating, etc.), use it
  1561. if (stg_cur_name) {
  1562. return stg_cur_name;
  1563. }
  1564. // Format the gcode_state nicely
  1565. switch (state) {
  1566. case 'RUNNING':
  1567. return 'Printing';
  1568. case 'PAUSE':
  1569. return 'Paused';
  1570. case 'FINISH':
  1571. return 'Finished';
  1572. case 'FAILED':
  1573. return 'Failed';
  1574. case 'IDLE':
  1575. return 'Idle';
  1576. default:
  1577. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1578. }
  1579. }
  1580. // Bambu models that ship with an enclosure chamber fan (firmware field
  1581. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1582. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1583. // widget is hidden in fanItems instead of rendered greyed-out.
  1584. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1585. 'X1C',
  1586. 'X1',
  1587. 'X1E',
  1588. 'X2D',
  1589. 'P1S',
  1590. 'P2S',
  1591. 'H2D',
  1592. 'H2D Pro',
  1593. 'H2C',
  1594. 'H2S',
  1595. ]);
  1596. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1597. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1598. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1599. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1600. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1601. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1602. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1603. 'P2S',
  1604. 'X2D',
  1605. ]);
  1606. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1607. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1608. // • User-defined friendly name (editable, protected by printers:update)
  1609. // • AMS serial number
  1610. // • AMS firmware version
  1611. export function AmsNameHoverCard({
  1612. ams,
  1613. printerId,
  1614. label,
  1615. amsLabels,
  1616. canEdit,
  1617. onSaved,
  1618. children,
  1619. }: {
  1620. ams: import('../api/client').AMSUnit;
  1621. printerId: number;
  1622. label: string; // auto-generated label, e.g. "AMS-A"
  1623. amsLabels?: Record<number, string>;
  1624. canEdit: boolean;
  1625. onSaved: () => void;
  1626. children: React.ReactNode;
  1627. }) {
  1628. const { t } = useTranslation();
  1629. const [isVisible, setIsVisible] = useState(false);
  1630. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1631. const [editValue, setEditValue] = useState('');
  1632. const [isSaving, setIsSaving] = useState(false);
  1633. const [saveError, setSaveError] = useState<string | null>(null);
  1634. const [isInputFocused, setIsInputFocused] = useState(false);
  1635. const triggerRef = useRef<HTMLDivElement>(null);
  1636. const cardRef = useRef<HTMLDivElement>(null);
  1637. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1638. useEffect(() => {
  1639. if (isVisible) {
  1640. setEditValue(amsLabels?.[ams.id] ?? '');
  1641. setSaveError(null);
  1642. requestAnimationFrame(() => {
  1643. if (triggerRef.current && cardRef.current) {
  1644. const rect = triggerRef.current.getBoundingClientRect();
  1645. const spaceAbove = rect.top - 56;
  1646. const spaceBelow = window.innerHeight - rect.bottom;
  1647. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1648. }
  1649. });
  1650. }
  1651. }, [isVisible, amsLabels, ams.id]);
  1652. const handleMouseEnter = () => {
  1653. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1654. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1655. };
  1656. const handleMouseLeave = () => {
  1657. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1658. if (!isInputFocused) {
  1659. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1660. }
  1661. };
  1662. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1663. const handleSave = async () => {
  1664. if (!canEdit) return;
  1665. setIsSaving(true);
  1666. setSaveError(null);
  1667. try {
  1668. const trimmed = editValue.trim();
  1669. if (trimmed) {
  1670. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1671. } else {
  1672. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1673. }
  1674. onSaved();
  1675. setIsVisible(false);
  1676. } catch (err) {
  1677. setSaveError(err instanceof Error ? err.message : String(err));
  1678. } finally {
  1679. setIsSaving(false);
  1680. }
  1681. };
  1682. const handleClear = async () => {
  1683. if (!canEdit) return;
  1684. setIsSaving(true);
  1685. setSaveError(null);
  1686. try {
  1687. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1688. onSaved();
  1689. setIsVisible(false);
  1690. } catch (err) {
  1691. setSaveError(err instanceof Error ? err.message : String(err));
  1692. } finally {
  1693. setIsSaving(false);
  1694. }
  1695. };
  1696. return (
  1697. <div
  1698. ref={triggerRef}
  1699. className="relative inline-block"
  1700. onMouseEnter={handleMouseEnter}
  1701. onMouseLeave={handleMouseLeave}
  1702. >
  1703. {children}
  1704. {isVisible && (
  1705. <div
  1706. ref={cardRef}
  1707. className={`
  1708. absolute left-0 z-50
  1709. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1710. animate-in fade-in-0 zoom-in-95 duration-150
  1711. `}
  1712. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1713. onMouseEnter={handleMouseEnter}
  1714. onMouseLeave={handleMouseLeave}
  1715. >
  1716. <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">
  1717. {/* AMS auto-label */}
  1718. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1719. {/* Serial number */}
  1720. <div className="flex items-center justify-between gap-2">
  1721. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1722. {t('printers.amsPopup.serialNumber')}
  1723. </span>
  1724. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1725. </div>
  1726. {/* Firmware version */}
  1727. <div className="flex items-center justify-between gap-2">
  1728. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1729. {t('printers.amsPopup.firmwareVersion')}
  1730. </span>
  1731. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1732. </div>
  1733. {/* Friendly name editor */}
  1734. <div className="space-y-1">
  1735. <div className="flex items-center gap-2">
  1736. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1737. {t('printers.amsPopup.friendlyName')}
  1738. </span>
  1739. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1740. </div>
  1741. <input
  1742. type="text"
  1743. value={editValue}
  1744. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1745. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1746. onFocus={() => setIsInputFocused(true)}
  1747. onBlur={() => {
  1748. setIsInputFocused(false);
  1749. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1750. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1751. }}
  1752. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1753. disabled={!canEdit}
  1754. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1755. 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"
  1756. maxLength={100}
  1757. />
  1758. {canEdit && (
  1759. <div className="space-y-1">
  1760. {saveError && (
  1761. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1762. )}
  1763. <div className="flex gap-1 justify-end">
  1764. <button
  1765. onClick={handleSave}
  1766. disabled={isSaving}
  1767. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1768. >
  1769. {t('printers.amsPopup.save')}
  1770. </button>
  1771. {amsLabels?.[ams.id] && (
  1772. <button
  1773. onClick={handleClear}
  1774. disabled={isSaving}
  1775. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1776. >
  1777. {t('printers.amsPopup.clear')}
  1778. </button>
  1779. )}
  1780. </div>
  1781. </div>
  1782. )}
  1783. </div>
  1784. </div>
  1785. </div>
  1786. )}
  1787. </div>
  1788. );
  1789. }
  1790. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1791. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1792. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1793. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1794. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1795. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1796. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1797. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1798. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1799. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1800. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1801. };
  1802. // How much the printer card's body type and icons grow at each card size
  1803. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1804. // 1.0 and an existing install looks identical until the user picks L or XL --
  1805. // the same control the request asked to have this follow.
  1806. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1807. // The scaled sizes, handed to the card subtree as custom properties. Every
  1808. // converted class names its old fixed value as the fallback, so anything that
  1809. // renders outside a card root -- the portalled temperature popover -- keeps
  1810. // exactly the size it has today.
  1811. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1812. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1813. // Rounded to a tenth so the values stay readable in devtools.
  1814. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1815. return {
  1816. '--pc-t8': px(8),
  1817. '--pc-t9': px(9),
  1818. '--pc-t10': px(10),
  1819. '--pc-t11': px(11),
  1820. '--pc-i2': px(8),
  1821. '--pc-i25': px(10),
  1822. '--pc-i3': px(12),
  1823. '--pc-i35': px(14),
  1824. '--pc-i4': px(16),
  1825. '--pc-i5': px(20),
  1826. '--pc-i7': px(28),
  1827. } as React.CSSProperties;
  1828. }
  1829. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1830. const { t } = useTranslation();
  1831. const queryClient = useQueryClient();
  1832. const { showToast } = useToast();
  1833. // One fleet-wide query shared by every card, not one per card: the list is
  1834. // nearly always empty and a 20-printer fleet would otherwise make 20
  1835. // requests every 30s. React Query dedupes on the key.
  1836. const { data: scheduled = [] } = useQuery({
  1837. queryKey: SCHEDULED_DRYINGS_KEY,
  1838. queryFn: () => api.listScheduledDryings(),
  1839. refetchInterval: 30_000,
  1840. });
  1841. // The live AMS status reports a starting cycle well before the next poll;
  1842. // refetch so a just-dispatched schedule doesn't linger as pending.
  1843. useEffect(() => {
  1844. if (dryingActive) {
  1845. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1846. }
  1847. }, [dryingActive, queryClient]);
  1848. const cancelMutation = useMutation({
  1849. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1850. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1851. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1852. });
  1853. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1854. // old firmware on a printer that was offline at schedule time), and without
  1855. // this the run just vanishes with only the backend log saying why.
  1856. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1857. if (rows.length === 0) return null;
  1858. return (
  1859. <div className="mt-2 space-y-1">
  1860. {rows.map(s => {
  1861. const failed = s.status === 'failed';
  1862. const reasonKey = waitingReasonKey(s.waiting_reason);
  1863. const failedKey = failedReasonKey(s.error_code);
  1864. return (
  1865. <div
  1866. key={s.id}
  1867. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1868. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1869. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1870. }`}
  1871. >
  1872. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1873. {failed ? (
  1874. t('printers.drying.scheduleFailedReason', {
  1875. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1876. })
  1877. ) : (
  1878. <>
  1879. {s.start_after
  1880. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1881. : t('printers.drying.scheduledAsap')}
  1882. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1883. </>
  1884. )}
  1885. </span>
  1886. <button
  1887. onClick={() => cancelMutation.mutate(s.id)}
  1888. disabled={cancelMutation.isPending}
  1889. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1890. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1891. >
  1892. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1893. </button>
  1894. </div>
  1895. );
  1896. })}
  1897. </div>
  1898. );
  1899. }
  1900. function PrinterCard({
  1901. printer,
  1902. hideIfDisconnected,
  1903. maintenanceInfo,
  1904. viewMode = 'expanded',
  1905. cardSize = 2,
  1906. amsThresholds,
  1907. spoolmanEnabled = false,
  1908. linkedSpools,
  1909. spoolmanUrl,
  1910. spoolmanSyncMode,
  1911. onGetAssignment,
  1912. onUnassignSpool,
  1913. spoolmanSpools,
  1914. spoolmanSlotAssignments,
  1915. spoolmanLoading = false,
  1916. onUnassignSpoolmanSpool,
  1917. timeFormat = 'system',
  1918. cameraViewMode = 'window',
  1919. onOpenEmbeddedCamera,
  1920. onSelectCameraViewMode,
  1921. checkPrinterFirmware = true,
  1922. dryingPresets = DRYING_PRESETS,
  1923. requirePlateClear = false,
  1924. selectionMode = false,
  1925. isSelected = false,
  1926. onToggleSelect,
  1927. onOpenCompactCard,
  1928. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1929. bedTempPresets = BED_TEMP_DEFAULTS,
  1930. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1931. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1932. aiDetectionEnabled = false,
  1933. aiDetection,
  1934. aiLastError = null,
  1935. }: {
  1936. printer: Printer;
  1937. hideIfDisconnected?: boolean;
  1938. maintenanceInfo?: PrinterMaintenanceInfo;
  1939. viewMode?: ViewMode;
  1940. cardSize?: number;
  1941. amsThresholds?: {
  1942. humidityGood: number;
  1943. humidityFair: number;
  1944. tempGood: number;
  1945. tempFair: number;
  1946. };
  1947. spoolmanEnabled?: boolean;
  1948. hasUnlinkedSpools?: boolean;
  1949. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1950. spoolmanUrl?: string | null;
  1951. spoolmanSyncMode?: string | null;
  1952. spoolAssignments?: SpoolAssignment[];
  1953. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1954. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1955. spoolmanSpools?: InventorySpool[];
  1956. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1957. spoolmanLoading?: boolean;
  1958. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1959. timeFormat?: 'system' | '12h' | '24h';
  1960. cameraViewMode?: CameraViewMode;
  1961. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1962. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  1963. checkPrinterFirmware?: boolean;
  1964. dryingPresets?: Record<string, DryingPreset>;
  1965. requirePlateClear?: boolean;
  1966. selectionMode?: boolean;
  1967. isSelected?: boolean;
  1968. onToggleSelect?: (id: number) => void;
  1969. onOpenCompactCard?: (id: number) => void;
  1970. nozzleTempPresets?: readonly [number, number, number];
  1971. bedTempPresets?: readonly [number, number, number];
  1972. chamberTempPresets?: readonly [number, number, number];
  1973. fanSpeedPresets?: readonly [number, number, number];
  1974. aiDetectionEnabled?: boolean;
  1975. aiDetection?: AiDetection;
  1976. aiLastError?: string | null;
  1977. }) {
  1978. const { t } = useTranslation();
  1979. const queryClient = useQueryClient();
  1980. const navigate = useNavigate();
  1981. const { showToast } = useToast();
  1982. const { hasPermission, canModify, authEnabled, isAdmin } = useAuth();
  1983. const [showMenu, setShowMenu] = useState(false);
  1984. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1985. const [deleteArchives, setDeleteArchives] = useState(true);
  1986. const [showEditModal, setShowEditModal] = useState(false);
  1987. const [showFileManager, setShowFileManager] = useState(false);
  1988. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1989. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1990. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1991. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1992. const [showHMSModal, setShowHMSModal] = useState(false);
  1993. // #1546: AI failure detection modal — opens from the AI badge.
  1994. const [showAiModal, setShowAiModal] = useState(false);
  1995. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1996. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1997. // External spool visibility (#1782) — browser-local, per printer. Read once
  1998. // per card; the toggle that writes it is the only thing that changes it.
  1999. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2000. isExternalSpoolHidden(printer.id),
  2001. );
  2002. const toggleExternalSpool = useCallback(() => {
  2003. setExternalSpoolHidden((prev) => {
  2004. const next = !prev;
  2005. persistExternalSpoolHidden(printer.id, next);
  2006. return next;
  2007. });
  2008. }, [printer.id]);
  2009. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2010. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2011. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2012. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2013. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2014. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2015. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2016. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2017. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2018. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2019. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2020. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2021. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2022. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2023. // AMS drying popover state: which AMS unit has the popover open
  2024. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2025. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2026. const [dryingFilament, setDryingFilament] = useState('PLA');
  2027. const [dryingTemp, setDryingTemp] = useState(50);
  2028. const [dryingDuration, setDryingDuration] = useState(4);
  2029. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2030. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2031. // go through scheduleDryingMutation.
  2032. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2033. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2034. const [dryingStartAt, setDryingStartAt] = useState('');
  2035. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2036. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2037. // Reset every field the popover owns, including the start mode. Leaving the
  2038. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2039. // the next open, by then in the past, and the POST rejected it.
  2040. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2041. const firstTray = ams.tray.find(t => t.tray_type);
  2042. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2043. // Only reachable if a custom preset set dropped PLA itself.
  2044. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2045. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2046. setDryingFilament(filType);
  2047. setDryingTemp(preset[moduleType] || preset.n3f);
  2048. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2049. setDryingRotateTray(false);
  2050. setDryingStartMode('now');
  2051. setDryingDelayMinutes(120);
  2052. setDryingStartAt('');
  2053. setDryingPopoverModuleType(ams.module_type);
  2054. setDryingPopoverAmsId(ams.id);
  2055. setDryingPopoverAnchor(trigger);
  2056. }, [dryingPresets]);
  2057. // Re-measure on resize/scroll so the popover and its arrow track the
  2058. // flame button, like IndicatorControlPopover.
  2059. useLayoutEffect(() => {
  2060. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2061. const measure = () => {
  2062. setDryingPopoverPos(computePopoverPosition({
  2063. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2064. popoverWidth: DRYING_POPOVER_WIDTH,
  2065. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2066. horizontalAlign: 'center',
  2067. }));
  2068. };
  2069. measure();
  2070. window.addEventListener('resize', measure);
  2071. window.addEventListener('scroll', measure, true);
  2072. return () => {
  2073. window.removeEventListener('resize', measure);
  2074. window.removeEventListener('scroll', measure, true);
  2075. };
  2076. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2077. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2078. // Whether the click hitting the backdrop is the one that dismissed the
  2079. // native datetime picker (see the backdrop's onMouseDown).
  2080. const dryingBackdropSkipCloseRef = useRef(false);
  2081. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2082. // an object rather than a bare id so restarting drying on the SAME unit produces
  2083. // a new identity and rearms the timeout below.
  2084. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2085. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2086. const [isDropUploading, setIsDropUploading] = useState(false);
  2087. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2088. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2089. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2090. // inside the card would have to open upward into the card body; anchored to
  2091. // the viewport it escapes the card and the grid's scroll container both.
  2092. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2093. const dragCounterRef = useRef(0);
  2094. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2095. amsId: number;
  2096. amsLabel: string;
  2097. mode: 'humidity' | 'temperature';
  2098. } | null>(null);
  2099. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2100. initialKind: HeaterSensorKind;
  2101. availableKinds: HeaterSensorKind[];
  2102. } | null>(null);
  2103. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2104. tagUid: string;
  2105. trayUuid: string;
  2106. printerId: number;
  2107. amsId: number;
  2108. trayId: number;
  2109. } | null>(null);
  2110. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2111. printerId: number;
  2112. amsId: number;
  2113. trayId: number;
  2114. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2115. } | null>(null);
  2116. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2117. amsId: number;
  2118. trayId: number;
  2119. trayCount: number;
  2120. trayType?: string;
  2121. trayColor?: string;
  2122. traySubBrands?: string;
  2123. trayInfoIdx?: string;
  2124. extruderId?: number;
  2125. caliIdx?: number | null;
  2126. savedPresetId?: string;
  2127. } | null>(null);
  2128. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2129. const [plateCheckResult, setPlateCheckResult] = useState<{
  2130. is_empty: boolean;
  2131. confidence: number;
  2132. difference_percent: number;
  2133. message: string;
  2134. debug_image_url?: string;
  2135. needs_calibration: boolean;
  2136. light_warning?: boolean;
  2137. reference_count?: number;
  2138. max_references?: number;
  2139. roi?: { x: number; y: number; w: number; h: number };
  2140. } | null>(null);
  2141. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2142. const [isCalibrating, setIsCalibrating] = useState(false);
  2143. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2144. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2145. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2146. const { data: status } = useQuery({
  2147. queryKey: ['printerStatus', printer.id],
  2148. queryFn: () => api.getPrinterStatus(printer.id),
  2149. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2150. });
  2151. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2152. const { data: firmwareInfo } = useQuery({
  2153. queryKey: ['firmwareUpdate', printer.id],
  2154. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2155. staleTime: 5 * 60 * 1000,
  2156. refetchInterval: 5 * 60 * 1000,
  2157. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2158. });
  2159. // Collect unique tray_info_idx values for cloud filament info lookup
  2160. const trayInfoIds = useMemo(() => {
  2161. const ids = new Set<string>();
  2162. if (status?.ams) {
  2163. for (const ams of status.ams) {
  2164. for (const tray of ams.tray || []) {
  2165. if (tray.tray_info_idx) {
  2166. ids.add(tray.tray_info_idx);
  2167. }
  2168. }
  2169. }
  2170. }
  2171. for (const vt of status?.vt_tray ?? []) {
  2172. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2173. }
  2174. if (status?.nozzle_rack) {
  2175. for (const slot of status.nozzle_rack) {
  2176. if (slot.filament_id) {
  2177. ids.add(slot.filament_id);
  2178. }
  2179. }
  2180. }
  2181. return Array.from(ids);
  2182. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2183. // Collect loaded filament types for queue widget filtering
  2184. const loadedFilamentTypes = useMemo(() => {
  2185. const types = new Set<string>();
  2186. if (status?.ams) {
  2187. for (const ams of status.ams) {
  2188. for (const tray of ams.tray || []) {
  2189. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2190. }
  2191. }
  2192. }
  2193. for (const vt of status?.vt_tray ?? []) {
  2194. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2195. }
  2196. return types;
  2197. }, [status?.ams, status?.vt_tray]);
  2198. // Collect loaded filament type+color pairs for queue widget override matching
  2199. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2200. const loadedFilaments = useMemo(() => {
  2201. const filaments = new Set<string>();
  2202. if (status?.ams) {
  2203. for (const ams of status.ams) {
  2204. for (const tray of ams.tray || []) {
  2205. if (tray.tray_type && tray.tray_color) {
  2206. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2207. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2208. }
  2209. }
  2210. }
  2211. }
  2212. for (const vt of status?.vt_tray ?? []) {
  2213. if (vt.tray_type && vt.tray_color) {
  2214. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2215. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2216. }
  2217. }
  2218. return filaments;
  2219. }, [status?.ams, status?.vt_tray]);
  2220. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2221. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2222. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2223. const loadedVariants = useMemo(() => {
  2224. const variants = new Set<string>();
  2225. if (status?.ams) {
  2226. for (const ams of status.ams) {
  2227. for (const tray of ams.tray || []) {
  2228. if (tray.tray_type && tray.tray_color) {
  2229. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2230. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2231. }
  2232. }
  2233. }
  2234. }
  2235. for (const vt of status?.vt_tray ?? []) {
  2236. if (vt.tray_type && vt.tray_color) {
  2237. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2238. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2239. }
  2240. }
  2241. return variants;
  2242. }, [status?.ams, status?.vt_tray]);
  2243. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2244. const { data: filamentInfo } = useQuery({
  2245. queryKey: ['filamentInfo', trayInfoIds],
  2246. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2247. enabled: trayInfoIds.length > 0,
  2248. staleTime: 5 * 60 * 1000, // 5 minutes
  2249. });
  2250. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2251. const { data: slotPresets } = useQuery({
  2252. queryKey: ['slotPresets', printer.id],
  2253. queryFn: () => api.getSlotPresets(printer.id),
  2254. staleTime: 2 * 60 * 1000, // 2 minutes
  2255. });
  2256. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2257. // Only queried when there's a running print backed by an archive; shared
  2258. // React Query cache with the Queue / Archives pages keeps it cheap.
  2259. const activeArchiveId =
  2260. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2261. const { data: activeArchivePlates } = useQuery({
  2262. queryKey: ['archive-plates', activeArchiveId],
  2263. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2264. enabled: activeArchiveId != null,
  2265. staleTime: 5 * 60 * 1000,
  2266. });
  2267. const activePlateLabel = (() => {
  2268. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2269. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2270. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2271. })();
  2272. // Fetch user-defined AMS friendly names from the database
  2273. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2274. queryKey: ['amsLabels', printer.id],
  2275. queryFn: () => api.getAmsLabels(printer.id),
  2276. staleTime: 5 * 60 * 1000, // 5 minutes
  2277. });
  2278. // Cache WiFi signal to prevent it disappearing on updates
  2279. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2280. useEffect(() => {
  2281. if (status?.wifi_signal != null) {
  2282. setCachedWifiSignal(status.wifi_signal);
  2283. }
  2284. }, [status?.wifi_signal]);
  2285. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2286. // Cache connected state to prevent flicker when status briefly becomes undefined
  2287. const cachedConnected = useRef<boolean | undefined>(undefined);
  2288. useEffect(() => {
  2289. if (status?.connected !== undefined) {
  2290. cachedConnected.current = status.connected;
  2291. }
  2292. }, [status?.connected]);
  2293. const isConnected = status?.connected ?? cachedConnected.current;
  2294. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2295. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2296. useEffect(() => {
  2297. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2298. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2299. }
  2300. }, [status?.ams_extruder_map]);
  2301. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2302. ? status.ams_extruder_map
  2303. : cachedAmsExtruderMap.current;
  2304. // Same caching for the Filament Track Switch inlet bindings, for the same
  2305. // reason: a partial MQTT frame briefly empties the map and the badges would
  2306. // otherwise blink out.
  2307. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2308. useEffect(() => {
  2309. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2310. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2311. }
  2312. }, [status?.ams_switch_inlet]);
  2313. const ftsInstalled = status?.fila_switch?.installed === true;
  2314. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2315. ? status.ams_switch_inlet
  2316. : cachedAmsSwitchInlet.current;
  2317. // Cache AMS data to prevent it disappearing on idle/offline printers
  2318. const cachedAmsData = useRef<AMSUnit[]>([]);
  2319. useEffect(() => {
  2320. if (status?.ams && status.ams.length > 0) {
  2321. cachedAmsData.current = status.ams;
  2322. }
  2323. }, [status?.ams]);
  2324. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2325. // #2532: the K-profile line only exists on slots the printer has actually
  2326. // calibrated. The AMS units and the external-spool group are flex siblings in
  2327. // one row, so on a card that shows a value anywhere, the slots without one
  2328. // reserve the same height -- otherwise their fill bars sit a line above their
  2329. // neighbours'. A card with no calibrated slot at all is unaffected.
  2330. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2331. || (status?.vt_tray ?? []).some(tray => tray.k);
  2332. // Confirm a drying cycle actually started (#2533). Firmware answers
  2333. // ams_filament_drying with result=success even when it then silently declines,
  2334. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2335. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2336. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2337. // means the printer took the command and dropped it.
  2338. useEffect(() => {
  2339. if (!dryStartWatch) return;
  2340. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2341. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2342. }, [dryStartWatch, amsData]);
  2343. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2344. // otherwise rearm the timeout on every frame, so it would never elapse.
  2345. useEffect(() => {
  2346. if (!dryStartWatch) return;
  2347. const timer = setTimeout(() => {
  2348. setDryStartWatch(null);
  2349. showToast(t('printers.drying.toastNotStarted'), 'error');
  2350. }, DRY_START_CONFIRM_MS);
  2351. return () => clearTimeout(timer);
  2352. }, [dryStartWatch, showToast, t]);
  2353. // Cache tray_now to prevent flickering when undefined values come in
  2354. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2355. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2356. const cachedTrayNow = useRef<number | undefined>(undefined);
  2357. const currentTrayNow = status?.tray_now;
  2358. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2359. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2360. cachedTrayNow.current = currentTrayNow;
  2361. } else if (currentTrayNow === 255) {
  2362. cachedTrayNow.current = undefined;
  2363. }
  2364. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2365. ? currentTrayNow
  2366. : cachedTrayNow.current;
  2367. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2368. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2369. // expectedTray = the slot the firmware now expects filament in
  2370. // previousTray = the slot that ran out
  2371. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2372. // so these are often different — the graphic highlights the expected one.
  2373. const expectedTray = status?.expected_tray ?? null;
  2374. const previousTray = status?.previous_tray ?? null;
  2375. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2376. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2377. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2378. if (globalId === null) return null;
  2379. if (globalId === 254) return t('printers.expectedSlot.external');
  2380. if (globalId >= 128 && globalId <= 135) {
  2381. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2382. }
  2383. const amsId = Math.floor(globalId / 4);
  2384. const slot = globalId % 4;
  2385. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2386. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2387. };
  2388. const runoutGuidance = status?.state === 'PAUSE'
  2389. ? {
  2390. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2391. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2392. }
  2393. : null;
  2394. // Fetch smart plug for this printer
  2395. const { data: smartPlug } = useQuery({
  2396. queryKey: ['smartPlugByPrinter', printer.id],
  2397. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2398. });
  2399. // Fetch script plugs for this printer (for multi-device control)
  2400. const { data: scriptPlugs } = useQuery({
  2401. queryKey: ['scriptPlugsByPrinter', printer.id],
  2402. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2403. });
  2404. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2405. const { data: plugStatus } = useQuery({
  2406. queryKey: ['smartPlugStatus', smartPlug?.id],
  2407. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2408. enabled: !!smartPlug,
  2409. refetchInterval: 10000, // 10 seconds for real-time power display
  2410. });
  2411. // Fetch queue count for this printer
  2412. const { data: queueItems } = useQuery({
  2413. queryKey: ['queue', printer.id, 'pending'],
  2414. queryFn: () => api.getQueue(printer.id, 'pending'),
  2415. });
  2416. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2417. // so the badge only shows on printers that can actually run the queued jobs.
  2418. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2419. const queueCount = useMemo(() => {
  2420. if (!queueItems?.length) return 0;
  2421. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2422. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2423. // Fetch currently printing queue item to show who started it (Issue #206)
  2424. const { data: printingQueueItems } = useQuery({
  2425. queryKey: ['queue', printer.id, 'printing'],
  2426. queryFn: () => api.getQueue(printer.id, 'printing'),
  2427. enabled: status?.state === 'RUNNING',
  2428. });
  2429. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2430. const { data: reprintUser } = useQuery({
  2431. queryKey: ['currentPrintUser', printer.id],
  2432. queryFn: () => api.getCurrentPrintUser(printer.id),
  2433. enabled: status?.state === 'RUNNING',
  2434. });
  2435. // Combine both sources: queue item user takes precedence, then reprint user
  2436. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2437. // Last print of this printer. One shared request for every card on the page
  2438. // (the key is the same for all of them); each card picks its own row.
  2439. const { data: lastPrint } = useQuery({
  2440. queryKey: ['archives', 'last-per-printer'],
  2441. queryFn: () => api.getLastArchivePerPrinter(),
  2442. select: (archives) => archives.find((a) => a.printer_id === printer.id),
  2443. });
  2444. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2445. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2446. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2447. // gate is up and the just-finished print asked for a verdict, offer
  2448. // Good/Reject right where the operator releases the plate. Releasing the
  2449. // plate without answering stays possible — the two are orthogonal (though
  2450. // the confirm_default_good_on_plate_clear setting can couple them).
  2451. // Only offered to whoever may record it: the PATCH checks archives:update
  2452. // against the archive's owner, so for anyone else the pair could only fail.
  2453. const pendingConfirmArchive =
  2454. lastPrint &&
  2455. lastPrint.status === 'completed' &&
  2456. lastPrint.confirm_requested &&
  2457. lastPrint.user_verdict == null &&
  2458. canModify('archives', 'update', lastPrint.created_by_id)
  2459. ? lastPrint
  2460. : null;
  2461. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2462. // Auto Power Off the printer is powered down exactly when the operator clears the
  2463. // plate. Hiding the control there left no way to release the gate (#2864).
  2464. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2465. const activePrintName = status?.current_print && isPrintingOrPaused
  2466. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2467. : null;
  2468. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2469. useEffect(() => {
  2470. if (activePrintName) {
  2471. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2472. } else if (!needsPlateClear) {
  2473. setRetainedPrintJob(null);
  2474. }
  2475. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2476. const plateStatus = (() => {
  2477. // Connected-only because the pill's only render site sits inside the live-status
  2478. // panel. For a powered-down printer the plate-clear button itself carries the
  2479. // state — see the standalone slot below the status block (#2864).
  2480. if (!requirePlateClear || !status?.connected) return null;
  2481. if (isPrintingOrPaused) {
  2482. return {
  2483. label: t('printers.plateStatus.inUse'),
  2484. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2485. };
  2486. }
  2487. if (status.awaiting_plate_clear) {
  2488. return {
  2489. label: t('printers.plateStatus.notCleared'),
  2490. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2491. };
  2492. }
  2493. return {
  2494. label: t('printers.plateStatus.cleared'),
  2495. className: 'bg-status-ok/20 text-status-ok',
  2496. };
  2497. })();
  2498. const plateStatusPill = plateStatus ? (
  2499. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[length:var(--pc-t10,10px)] font-medium ${plateStatus.className}`}>
  2500. {plateStatus.label}
  2501. </span>
  2502. ) : null;
  2503. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2504. const shouldHide = hideIfDisconnected && isConnected === false;
  2505. const deleteMutation = useMutation({
  2506. mutationFn: (options: { deleteArchives: boolean }) =>
  2507. api.deletePrinter(printer.id, options.deleteArchives),
  2508. onSuccess: () => {
  2509. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2510. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2511. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2512. // What was limited to the printer went with it (providers, virtual
  2513. // printers, smart plugs) or lost it (API keys, Obico).
  2514. queryClient.invalidateQueries({ queryKey: ['notification-providers'] });
  2515. queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
  2516. queryClient.invalidateQueries({ queryKey: ['api-keys'] });
  2517. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2518. // Obico's printer list lost it; a cached copy would save it back.
  2519. queryClient.invalidateQueries({ queryKey: ['settings'] });
  2520. },
  2521. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2522. });
  2523. const connectMutation = useMutation({
  2524. mutationFn: () => api.connectPrinter(printer.id),
  2525. onSuccess: () => {
  2526. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2527. },
  2528. });
  2529. const forceRefreshMutation = useMutation({
  2530. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2531. onSuccess: () => {
  2532. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2533. showToast(t('printers.forceRefreshSuccess'), 'success');
  2534. },
  2535. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2536. });
  2537. const unlinkSpoolMutation = useMutation({
  2538. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2539. onSuccess: (result) => {
  2540. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2541. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2542. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2543. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2544. },
  2545. onError: (error: Error) => {
  2546. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2547. },
  2548. });
  2549. // AMS drying mutations
  2550. const startDryingMutation = useMutation({
  2551. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2552. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2553. onSuccess: (_data, { amsId }) => {
  2554. setDryingPopoverAmsId(null);
  2555. setDryStartWatch({ amsId });
  2556. // "Command sent", not "drying started" — at this point the printer has only
  2557. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2558. // the cycle is genuinely live; the watcher below covers the case where it
  2559. // never appears.
  2560. showToast(t('printers.drying.toastCommandSent'), 'success');
  2561. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2562. },
  2563. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2564. });
  2565. // Scheduled (delayed / at-time) drying runs (#2638)
  2566. const scheduleDryingMutation = useMutation({
  2567. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2568. api.createScheduledDrying({
  2569. printer_id: printer.id,
  2570. ams_id: params.amsId,
  2571. temp: params.temp,
  2572. duration_hours: params.duration,
  2573. filament: params.filament,
  2574. rotate_tray: params.rotateTray,
  2575. start_after: params.startAfter,
  2576. }),
  2577. onSuccess: () => {
  2578. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2579. setDryingPopoverAmsId(null);
  2580. },
  2581. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2582. });
  2583. const stopDryingMutation = useMutation({
  2584. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2585. onSuccess: () => {
  2586. setDryStartWatch(null);
  2587. showToast(t('printers.drying.toastStopped'), 'success');
  2588. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2589. },
  2590. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2591. });
  2592. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2593. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2594. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2595. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2596. // showing the old backup state until the user reopens it.
  2597. const setAmsBackupMutation = useMutation({
  2598. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2599. onSuccess: (_data, enabled) => {
  2600. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2601. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2602. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2603. },
  2604. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2605. });
  2606. // Smart plug control mutations
  2607. const powerControlMutation = useMutation({
  2608. mutationFn: (action: 'on' | 'off') =>
  2609. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2610. onSuccess: () => {
  2611. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2612. },
  2613. });
  2614. const toggleAutoOffMutation = useMutation({
  2615. mutationFn: (enabled: boolean) =>
  2616. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2617. onSuccess: () => {
  2618. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2619. // Also invalidate the smart-plugs list to keep Settings page in sync
  2620. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2621. },
  2622. });
  2623. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2624. const runScriptMutation = useMutation({
  2625. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2626. onSuccess: () => {
  2627. showToast(t('printers.toast.scriptTriggered'));
  2628. },
  2629. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2630. });
  2631. // Print control mutations
  2632. const stopPrintMutation = useMutation({
  2633. mutationFn: () => api.stopPrint(printer.id),
  2634. onSuccess: () => {
  2635. showToast(t('printers.toast.printStopped'));
  2636. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2637. },
  2638. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2639. });
  2640. const pausePrintMutation = useMutation({
  2641. mutationFn: () => api.pausePrint(printer.id),
  2642. onSuccess: () => {
  2643. showToast(t('printers.toast.printPaused'));
  2644. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2645. },
  2646. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2647. });
  2648. const resumePrintMutation = useMutation({
  2649. mutationFn: () => api.resumePrint(printer.id),
  2650. onSuccess: () => {
  2651. showToast(t('printers.toast.printResumed'));
  2652. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2653. },
  2654. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2655. });
  2656. const clearPlateMutation = useMutation({
  2657. mutationFn: () => api.clearPlate(printer.id),
  2658. onSuccess: () => {
  2659. showToast(t('queue.clearPlateSuccess'));
  2660. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2661. old ? { ...old, awaiting_plate_clear: false } : old
  2662. );
  2663. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2664. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2665. },
  2666. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2667. });
  2668. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2669. // reject goes through the dialog for the optional reason + reprint.
  2670. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2671. // Only "good" is answered on the card. A reject wants a reason and possibly
  2672. // a reprint, so that button opens the dialog instead — and the parameter
  2673. // says as much, rather than accepting a verdict this path cannot send and
  2674. // then reporting it as good.
  2675. const cardVerdictMutation = useMutation({
  2676. mutationFn: (verdict: 'good') =>
  2677. api.updateArchive(pendingConfirmArchive!.id, {
  2678. user_verdict: verdict,
  2679. user_verdict_source: 'printer_card',
  2680. }),
  2681. onSuccess: () => {
  2682. showToast(t('confirmOutcome.savedGood'), 'success');
  2683. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2684. },
  2685. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2686. });
  2687. // Rendered from two places: inside the live-status block for a connected printer,
  2688. // and standalone below it for a powered-down one, whose status block isn't rendered
  2689. // at all (#2864). Shared so the two can't drift apart.
  2690. const expandedClearPlateButton = (
  2691. <>
  2692. {pendingConfirmArchive && (
  2693. <div className="mt-2 flex items-center gap-1.5">
  2694. <span
  2695. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2696. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2697. >
  2698. {t('confirmOutcome.cardPrompt')}
  2699. </span>
  2700. <button
  2701. type="button"
  2702. onClick={() => setShowConfirmOutcome(true)}
  2703. disabled={cardVerdictMutation.isPending}
  2704. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2705. title={t('confirmOutcome.reject')}
  2706. >
  2707. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2708. </button>
  2709. <button
  2710. type="button"
  2711. onClick={() => cardVerdictMutation.mutate('good')}
  2712. disabled={cardVerdictMutation.isPending}
  2713. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2714. title={t('confirmOutcome.good')}
  2715. >
  2716. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2717. </button>
  2718. </div>
  2719. )}
  2720. <button
  2721. type="button"
  2722. onClick={() => clearPlateMutation.mutate()}
  2723. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2724. className="mt-2 w-full inline-flex items-center justify-center gap-2 px-3 py-1.5 rounded-lg bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-300 dark:border-yellow-400/40 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs font-medium disabled:opacity-50"
  2725. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2726. >
  2727. {clearPlateMutation.isPending ? (
  2728. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2729. ) : (
  2730. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2731. )}
  2732. {t('printers.plateStatus.markCleared')}
  2733. </button>
  2734. {showConfirmOutcome && pendingConfirmArchive && (
  2735. <ConfirmOutcomeDialog
  2736. archiveId={pendingConfirmArchive.id}
  2737. onClose={() => setShowConfirmOutcome(false)}
  2738. />
  2739. )}
  2740. </>
  2741. );
  2742. const nozzleTemperatureMutation = useMutation({
  2743. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2744. api.setNozzleTemperature(printer.id, target, nozzle),
  2745. onSuccess: (result) => {
  2746. setStatusControlMenu(null);
  2747. showToast(result.message);
  2748. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2749. },
  2750. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2751. });
  2752. const bedTemperatureMutation = useMutation({
  2753. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2754. onSuccess: (result) => {
  2755. setStatusControlMenu(null);
  2756. showToast(result.message);
  2757. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2758. },
  2759. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2760. });
  2761. const chamberTemperatureMutation = useMutation({
  2762. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2763. onSuccess: (result) => {
  2764. setStatusControlMenu(null);
  2765. showToast(result.message);
  2766. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2767. },
  2768. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2769. });
  2770. const fanSpeedMutation = useMutation({
  2771. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2772. api.setFanSpeed(printer.id, fan, speed),
  2773. onMutate: async ({ fan, speed }) => {
  2774. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2775. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2776. const fanField = {
  2777. part: 'cooling_fan_speed',
  2778. aux: 'big_fan1_speed',
  2779. aux2: 'left_aux_fan_speed',
  2780. chamber: 'big_fan2_speed',
  2781. }[fan];
  2782. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2783. old ? { ...old, [fanField]: speed } : old
  2784. );
  2785. return { previousStatus };
  2786. },
  2787. onSuccess: (result) => {
  2788. setStatusControlMenu(null);
  2789. showToast(result.message);
  2790. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2791. },
  2792. onError: (error: Error, _variables, context) => {
  2793. if (context?.previousStatus) {
  2794. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2795. }
  2796. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2797. },
  2798. });
  2799. const selectExtruderMutation = useMutation({
  2800. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2801. onMutate: async (extruder) => {
  2802. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2803. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2804. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2805. old ? { ...old, active_extruder: extruder } : old
  2806. );
  2807. return { previousStatus };
  2808. },
  2809. onSuccess: (result) => {
  2810. setStatusControlMenu(null);
  2811. showToast(result.message);
  2812. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2813. },
  2814. onError: (error: Error, _extruder, context) => {
  2815. if (context?.previousStatus) {
  2816. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2817. }
  2818. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2819. },
  2820. });
  2821. // Chamber light mutation with optimistic update
  2822. const chamberLightMutation = useMutation({
  2823. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2824. onMutate: async (on) => {
  2825. // Cancel any outgoing refetches
  2826. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2827. // Snapshot the previous value
  2828. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2829. // Optimistically update
  2830. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2831. ...old,
  2832. chamber_light: on,
  2833. }));
  2834. return { previousStatus };
  2835. },
  2836. onSuccess: (_, on) => {
  2837. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2838. },
  2839. onError: (error: Error, _, context) => {
  2840. // Rollback on error
  2841. if (context?.previousStatus) {
  2842. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2843. }
  2844. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2845. },
  2846. });
  2847. // Print speed mutation with optimistic update
  2848. const printSpeedMutation = useMutation({
  2849. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2850. onMutate: async (mode) => {
  2851. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2852. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2853. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2854. ...old,
  2855. speed_level: mode,
  2856. }));
  2857. return { previousStatus };
  2858. },
  2859. onError: (error: Error, _, context) => {
  2860. if (context?.previousStatus) {
  2861. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2862. }
  2863. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2864. },
  2865. });
  2866. const airductMutation = useMutation({
  2867. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2868. onMutate: async (mode) => {
  2869. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2870. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2871. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2872. ...old,
  2873. airduct_mode: mode === 'cooling' ? 0 : 1,
  2874. }));
  2875. return { previousStatus };
  2876. },
  2877. onError: (error: Error, _, context) => {
  2878. if (context?.previousStatus) {
  2879. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2880. }
  2881. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2882. },
  2883. });
  2884. const bedJogMutation = useMutation({
  2885. mutationFn: ({ distance }: { distance: number }) =>
  2886. api.bedJog(printer.id, distance),
  2887. onError: (error: Error) =>
  2888. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2889. });
  2890. const xyJogMutation = useMutation({
  2891. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2892. api.xyJog(printer.id, x, y),
  2893. onError: (error: Error) =>
  2894. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2895. });
  2896. const extruderJogMutation = useMutation({
  2897. mutationFn: (distance: number) =>
  2898. api.extruderJog(printer.id, distance),
  2899. onError: (error: Error) =>
  2900. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2901. });
  2902. const homeAxesMutation = useMutation({
  2903. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2904. onSuccess: () => {
  2905. showToast(t('printers.bedJog.homingStarted'));
  2906. },
  2907. onError: (error: Error) =>
  2908. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2909. });
  2910. // Plate detection setting mutation
  2911. const plateDetectionMutation = useMutation({
  2912. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2913. onSuccess: () => {
  2914. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2915. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2916. },
  2917. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2918. });
  2919. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2920. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2921. // metrics, and the print picker — so flipping this flag puts the printer
  2922. // out of service across every consumer in one place. Used from the
  2923. // overflow menu and EditPrinterModal.
  2924. const maintenanceMutation = useMutation({
  2925. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2926. onSuccess: (_data, isActive) => {
  2927. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2928. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2929. showToast(
  2930. isActive
  2931. ? t('printers.maintenance.toastExited', { name: printer.name })
  2932. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2933. 'success',
  2934. );
  2935. },
  2936. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2937. });
  2938. // Confirm before entering maintenance on a printing printer (entering mode
  2939. // disconnects MQTT, which stops progress tracking + completion notifications
  2940. // for the in-flight job).
  2941. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2942. const handleEnterMaintenance = () => {
  2943. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2944. setConfirmMaintenanceEnter(true);
  2945. } else {
  2946. maintenanceMutation.mutate(false);
  2947. }
  2948. };
  2949. // Query for printable objects (for skip functionality)
  2950. // Fetch when printing with 2+ objects OR when modal is open
  2951. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2952. const { data: objectsData } = useQuery({
  2953. queryKey: ['printableObjects', printer.id],
  2954. queryFn: () => api.getPrintableObjects(printer.id),
  2955. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2956. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2957. });
  2958. // State for tracking which AMS slot is being refreshed
  2959. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2960. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2961. const seenBusyStateRef = useRef<boolean>(false);
  2962. // Fallback timeout ref
  2963. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2964. // Minimum display time passed
  2965. const minTimePassedRef = useRef<boolean>(false);
  2966. // AMS slot refresh mutation
  2967. const refreshAmsSlotMutation = useMutation({
  2968. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2969. api.refreshAmsSlot(printer.id, amsId, slotId),
  2970. onMutate: ({ amsId, slotId }) => {
  2971. // Clear any existing timeout
  2972. if (refreshTimeoutRef.current) {
  2973. clearTimeout(refreshTimeoutRef.current);
  2974. }
  2975. // Reset state
  2976. seenBusyStateRef.current = false;
  2977. minTimePassedRef.current = false;
  2978. setRefreshingSlot({ amsId, slotId });
  2979. // Minimum display time (2 seconds)
  2980. setTimeout(() => {
  2981. minTimePassedRef.current = true;
  2982. }, 2000);
  2983. // Fallback timeout (30 seconds max)
  2984. refreshTimeoutRef.current = setTimeout(() => {
  2985. setRefreshingSlot(null);
  2986. }, 30000);
  2987. },
  2988. onSuccess: (data) => {
  2989. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2990. },
  2991. onError: (error: Error) => {
  2992. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2993. if (refreshTimeoutRef.current) {
  2994. clearTimeout(refreshTimeoutRef.current);
  2995. }
  2996. setRefreshingSlot(null);
  2997. },
  2998. });
  2999. // AMS load/unload mutations (#891)
  3000. const loadAmsTrayMutation = useMutation({
  3001. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  3002. api.loadAmsTray(printer.id, trayId, extruderId),
  3003. onSuccess: (data) => {
  3004. setFeedDirectionRequest(null);
  3005. showToast(data.message || t('printers.toast.loadInitiated'));
  3006. },
  3007. onError: (error: Error) => {
  3008. setFeedDirectionRequest(null);
  3009. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3010. },
  3011. });
  3012. const unloadAmsMutation = useMutation({
  3013. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3014. onSuccess: (data) => {
  3015. showToast(data.message || t('printers.toast.unloadInitiated'));
  3016. },
  3017. onError: (error: Error) => {
  3018. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3019. },
  3020. });
  3021. // Pending "which hotend?" question, non-null only while the dialog is open.
  3022. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3023. // load command has to name one — see FeedDirectionModal.
  3024. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3025. trayId: number;
  3026. amsId: number;
  3027. slotId: number;
  3028. slotLabel: string;
  3029. } | null>(null);
  3030. // Whether a load from this printer has to ask which hotend to feed.
  3031. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3032. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3033. // The external holder needs no question: its two tray ids name the side
  3034. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3035. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3036. // external spool, because it would occupy an extruder channel permanently.
  3037. //
  3038. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3039. // carries does not address an HT unit, so the load is refused whatever the
  3040. // answer. Asking first would only put a dialog in front of the same error.
  3041. const isExternal = amsId === 255;
  3042. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3043. loadAmsTrayMutation.mutate({ trayId });
  3044. return;
  3045. }
  3046. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3047. // front rather than sending a command the firmware will drop. BambuStudio
  3048. // shows the same message and returns without publishing anything.
  3049. if (!status?.fila_switch?.ready) {
  3050. showToast(t('printers.ams.switchNotReady'), 'warning');
  3051. return;
  3052. }
  3053. setFeedDirectionRequest({
  3054. trayId,
  3055. amsId,
  3056. slotId,
  3057. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3058. });
  3059. };
  3060. // Plate references state
  3061. const [plateReferences, setPlateReferences] = useState<{
  3062. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3063. max_references: number;
  3064. } | null>(null);
  3065. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3066. // Fetch plate references
  3067. const fetchPlateReferences = async () => {
  3068. try {
  3069. const data = await api.getPlateReferences(printer.id);
  3070. setPlateReferences(data);
  3071. } catch {
  3072. // Ignore errors - references will show as empty
  3073. }
  3074. };
  3075. // Toggle plate detection enabled/disabled
  3076. const handleTogglePlateDetection = () => {
  3077. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3078. };
  3079. // Open plate detection management modal (for calibration/references)
  3080. const handleOpenPlateManagement = async () => {
  3081. setIsCheckingPlate(true);
  3082. setPlateCheckResult(null);
  3083. // Auto-turn on light if it's off
  3084. const lightWasOff = status?.chamber_light === false;
  3085. setPlateCheckLightWasOff(lightWasOff);
  3086. if (lightWasOff) {
  3087. await api.setChamberLight(printer.id, true);
  3088. // Wait for light to physically turn on and camera to adjust exposure
  3089. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3090. await new Promise(resolve => setTimeout(resolve, 2500));
  3091. }
  3092. try {
  3093. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3094. setPlateCheckResult(result);
  3095. fetchPlateReferences();
  3096. } catch (error) {
  3097. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3098. // Restore light if check failed
  3099. if (lightWasOff) {
  3100. await api.setChamberLight(printer.id, false);
  3101. setPlateCheckLightWasOff(false);
  3102. }
  3103. } finally {
  3104. setIsCheckingPlate(false);
  3105. }
  3106. };
  3107. // Close plate check modal and restore light state
  3108. const closePlateCheckModal = useCallback(async () => {
  3109. setPlateCheckResult(null);
  3110. // Restore light to original state if we turned it on
  3111. if (plateCheckLightWasOff) {
  3112. await api.setChamberLight(printer.id, false);
  3113. setPlateCheckLightWasOff(false);
  3114. }
  3115. }, [plateCheckLightWasOff, printer.id]);
  3116. // Calibrate plate detection handler
  3117. const handleCalibratePlate = async (label?: string) => {
  3118. setIsCalibrating(true);
  3119. try {
  3120. const result = await api.calibratePlateDetection(printer.id, { label });
  3121. if (result.success) {
  3122. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3123. // Refresh references and re-check
  3124. fetchPlateReferences();
  3125. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3126. setPlateCheckResult(checkResult);
  3127. } else {
  3128. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3129. }
  3130. } catch (error) {
  3131. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3132. } finally {
  3133. setIsCalibrating(false);
  3134. }
  3135. };
  3136. // Update reference label
  3137. const handleUpdateRefLabel = async (index: number, label: string) => {
  3138. try {
  3139. await api.updatePlateReferenceLabel(printer.id, index, label);
  3140. setEditingRefLabel(null);
  3141. fetchPlateReferences();
  3142. } catch (error) {
  3143. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3144. }
  3145. };
  3146. // Delete reference
  3147. const handleDeleteRef = async (index: number) => {
  3148. try {
  3149. await api.deletePlateReference(printer.id, index);
  3150. showToast(t('printers.toast.referenceDeleted'), 'success');
  3151. fetchPlateReferences();
  3152. // Re-check to update counts
  3153. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3154. setPlateCheckResult(checkResult);
  3155. } catch (error) {
  3156. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3157. }
  3158. };
  3159. // Save ROI settings
  3160. const handleSaveRoi = async () => {
  3161. if (!editingRoi) return;
  3162. setIsSavingRoi(true);
  3163. try {
  3164. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3165. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3166. setEditingRoi(null);
  3167. // Re-check to see new ROI in action
  3168. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3169. setPlateCheckResult(checkResult);
  3170. } catch (error) {
  3171. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3172. } finally {
  3173. setIsSavingRoi(false);
  3174. }
  3175. };
  3176. // Close plate check modal on Escape key
  3177. useEffect(() => {
  3178. const handleEscape = (e: KeyboardEvent) => {
  3179. if (e.key === 'Escape' && plateCheckResult) {
  3180. closePlateCheckModal();
  3181. }
  3182. };
  3183. window.addEventListener('keydown', handleEscape);
  3184. return () => window.removeEventListener('keydown', handleEscape);
  3185. }, [plateCheckResult, closePlateCheckModal]);
  3186. // Watch ams_status_main to detect when RFID read completes
  3187. // ams_status_main: 0=idle, 2=rfid_identifying
  3188. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3189. useEffect(() => {
  3190. if (!refreshingSlot) return;
  3191. const amsStatus = status?.ams_status_main ?? 0;
  3192. // Track when we see non-idle state (printer is working)
  3193. if (amsStatus !== 0) {
  3194. seenBusyStateRef.current = true;
  3195. // Cancel any deferred clear since we're back to busy
  3196. if (deferredClearRef.current) {
  3197. clearTimeout(deferredClearRef.current);
  3198. deferredClearRef.current = null;
  3199. }
  3200. }
  3201. // When we've seen busy and now idle, clear (with min time check)
  3202. if (seenBusyStateRef.current && amsStatus === 0) {
  3203. if (minTimePassedRef.current) {
  3204. // Min time passed - clear now
  3205. if (refreshTimeoutRef.current) {
  3206. clearTimeout(refreshTimeoutRef.current);
  3207. }
  3208. setRefreshingSlot(null);
  3209. } else {
  3210. // Schedule clear after min time (2 seconds from start)
  3211. if (!deferredClearRef.current) {
  3212. deferredClearRef.current = setTimeout(() => {
  3213. if (refreshTimeoutRef.current) {
  3214. clearTimeout(refreshTimeoutRef.current);
  3215. }
  3216. setRefreshingSlot(null);
  3217. }, 2000);
  3218. }
  3219. }
  3220. }
  3221. return () => {
  3222. if (deferredClearRef.current) {
  3223. clearTimeout(deferredClearRef.current);
  3224. }
  3225. };
  3226. }, [status?.ams_status_main, refreshingSlot]);
  3227. useEffect(() => {
  3228. if (!showMenu) return;
  3229. const handleClickOutside = (event: MouseEvent) => {
  3230. const target = event.target as Node;
  3231. if (!printerActionsMenuRef.current?.contains(target)) {
  3232. setShowMenu(false);
  3233. }
  3234. };
  3235. document.addEventListener('mousedown', handleClickOutside);
  3236. return () => document.removeEventListener('mousedown', handleClickOutside);
  3237. }, [showMenu]);
  3238. if (shouldHide) {
  3239. return null;
  3240. }
  3241. // Size-based styling helpers
  3242. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3243. // width, its thumbnail and the printer name, but every label inside the
  3244. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3245. // S one -- the disparity was worst exactly where someone asking for more
  3246. // room ends up. These custom properties carry the scaled sizes into the
  3247. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3248. // unless they reach for a size that is already asking for more space.
  3249. // Plain computation rather than useMemo: this sits after the card's early
  3250. // returns, where a hook would break the rules-of-hooks ordering, and
  3251. // building ten strings per render costs nothing.
  3252. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3253. const getImageSize = () => {
  3254. switch (cardSize) {
  3255. case 1: return 'w-10 h-10';
  3256. case 2: return 'w-14 h-14';
  3257. case 3: return 'w-16 h-16';
  3258. case 4: return 'w-20 h-20';
  3259. default: return 'w-14 h-14';
  3260. }
  3261. };
  3262. const getTitleSize = () => {
  3263. switch (cardSize) {
  3264. case 1: return 'text-base truncate';
  3265. case 2: return 'text-lg';
  3266. case 3: return 'text-xl';
  3267. case 4: return 'text-2xl';
  3268. default: return 'text-lg';
  3269. }
  3270. };
  3271. const getSpacing = () => {
  3272. switch (cardSize) {
  3273. case 1: return 'mb-2';
  3274. case 2: return 'mb-4';
  3275. case 3: return 'mb-5';
  3276. case 4: return 'mb-6';
  3277. default: return 'mb-4';
  3278. }
  3279. };
  3280. // A dropped file always becomes a queue item, so a printer that is busy,
  3281. // offline or mid-drying is no reason to refuse the drop — it only means the
  3282. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3283. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3284. // what this would have done for them.
  3285. //
  3286. // What remains is what the flow actually performs: upload the file, then
  3287. // create a queue item. It never touches printers:control, which is what this
  3288. // used to check — so someone holding that but neither of these had the file
  3289. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3290. // button below has always checked this pair.
  3291. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3292. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3293. // and the modal's own "will start later" toast cannot disagree.
  3294. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3295. const handleCardDragEnter = (e: React.DragEvent) => {
  3296. e.preventDefault();
  3297. dragCounterRef.current++;
  3298. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3299. };
  3300. const handleCardDragOver = (e: React.DragEvent) => {
  3301. e.preventDefault();
  3302. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3303. };
  3304. const handleCardDragLeave = (e: React.DragEvent) => {
  3305. e.preventDefault();
  3306. dragCounterRef.current--;
  3307. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3308. };
  3309. const handleCardDrop = async (e: React.DragEvent) => {
  3310. e.preventDefault();
  3311. dragCounterRef.current = 0;
  3312. setIsDraggingFile(false);
  3313. if (!canDrop) return;
  3314. const droppedFiles = Array.from(e.dataTransfer.files);
  3315. const file = droppedFiles[0];
  3316. if (!file) return;
  3317. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3318. const lower = file.name.toLowerCase();
  3319. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3320. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3321. return;
  3322. }
  3323. setIsDropUploading(true);
  3324. try {
  3325. const result = await api.uploadLibraryFile(file, null);
  3326. // Check printer compatibility if sliced_for_model is available in metadata
  3327. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3328. const printerModel = mapModelCode(printer.model);
  3329. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3330. await api.deleteLibraryFile(result.id).catch(() => {});
  3331. showToast(
  3332. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3333. 'error'
  3334. );
  3335. return;
  3336. }
  3337. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3338. } catch {
  3339. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3340. } finally {
  3341. setIsDropUploading(false);
  3342. }
  3343. };
  3344. const handleCardClick = (e: React.MouseEvent) => {
  3345. if (viewMode !== 'compact' || selectionMode) return;
  3346. const target = e.target as HTMLElement;
  3347. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3348. onOpenCompactCard?.(printer.id);
  3349. };
  3350. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3351. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3352. // Opening a camera in a given mode, without touching which mode is remembered
  3353. // -- the split button's two halves want the same action but disagree about
  3354. // whether the choice was deliberate enough to keep.
  3355. const openCameraIn = (mode: CameraViewMode) => {
  3356. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3357. onOpenEmbeddedCamera(printer.id, printer.name);
  3358. } else {
  3359. openCameraWindow(printer.id);
  3360. }
  3361. };
  3362. // Picking a mode both opens the camera that way and makes it the mode the
  3363. // plain icon uses from now on. A menu that only changed a preference would
  3364. // leave the user with a second click to do the thing they already asked for.
  3365. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3366. [
  3367. {
  3368. mode: 'window' as const,
  3369. icon: <ExternalLink className="w-4 h-4" />,
  3370. label: t('settings.newWindow'),
  3371. title: t('settings.cameraWindowDescription'),
  3372. },
  3373. {
  3374. mode: 'embedded' as const,
  3375. icon: <PictureInPicture2 className="w-4 h-4" />,
  3376. label: t('settings.embeddedOverlay'),
  3377. title: t('settings.cameraOverlayDescription'),
  3378. },
  3379. ]
  3380. ).map(({ mode, icon, label, title }) => ({
  3381. icon,
  3382. // The remembered mode is marked in the label itself: the icon slot already
  3383. // carries the mode's own icon, and a separate tick column would push both
  3384. // entries out of line with every other card menu.
  3385. label: mode === cameraViewMode ? `${label} ✓` : label,
  3386. title,
  3387. onClick: () => {
  3388. onSelectCameraViewMode?.(mode);
  3389. openCameraIn(mode);
  3390. },
  3391. }));
  3392. const renderAmsSlotActions = ({
  3393. amsId,
  3394. slotId,
  3395. loadTrayId,
  3396. isRefreshing,
  3397. includeRfid = true,
  3398. }: {
  3399. amsId: number;
  3400. slotId: number;
  3401. loadTrayId: number;
  3402. isRefreshing?: boolean;
  3403. includeRfid?: boolean;
  3404. }) => {
  3405. const printerBusy = status?.state === 'RUNNING';
  3406. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3407. // ams*4+slot, so the id this menu carries does not name it to the load and
  3408. // unload endpoints — they reject it. Sending no slot falls back to the
  3409. // printer-wide unload, which is what this menu did for every slot before
  3410. // the per-slot form existed. Load has never worked on an HT slot for the
  3411. // same addressing reason; fixing that is a separate change.
  3412. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3413. return (
  3414. <>
  3415. {includeRfid && (
  3416. <button
  3417. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3418. hasPermission('printers:ams_rfid')
  3419. ? 'text-white hover:bg-bambu-dark-tertiary'
  3420. : 'text-bambu-gray/50 cursor-not-allowed'
  3421. }`}
  3422. onClick={(e) => {
  3423. e.stopPropagation();
  3424. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3425. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3426. }}
  3427. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3428. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3429. >
  3430. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3431. {t('printers.rfid.reread')}
  3432. </button>
  3433. )}
  3434. <button
  3435. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3436. hasPermission('printers:control')
  3437. ? 'text-white hover:bg-bambu-dark-tertiary'
  3438. : 'text-bambu-gray/50 cursor-not-allowed'
  3439. }`}
  3440. onClick={(e) => {
  3441. e.stopPropagation();
  3442. if (printerBusy || !hasPermission('printers:control')) return;
  3443. startAmsLoad(amsId, slotId, loadTrayId);
  3444. }}
  3445. disabled={printerBusy || !hasPermission('printers:control')}
  3446. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3447. >
  3448. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3449. {t('printers.ams.load')}
  3450. </button>
  3451. <button
  3452. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3453. hasPermission('printers:control')
  3454. ? 'text-white hover:bg-bambu-dark-tertiary'
  3455. : 'text-bambu-gray/50 cursor-not-allowed'
  3456. }`}
  3457. onClick={(e) => {
  3458. e.stopPropagation();
  3459. if (printerBusy || !hasPermission('printers:control')) return;
  3460. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3461. }}
  3462. disabled={printerBusy || !hasPermission('printers:control')}
  3463. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3464. >
  3465. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3466. {t('printers.ams.unload')}
  3467. </button>
  3468. </>
  3469. );
  3470. };
  3471. const printerActionsMenu = (
  3472. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3473. <Button
  3474. variant="secondary"
  3475. size="sm"
  3476. onClick={() => setShowMenu(!showMenu)}
  3477. title={t('common.more', 'More')}
  3478. className={footerIconButtonClass}
  3479. >
  3480. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3481. </Button>
  3482. {showMenu && (
  3483. <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">
  3484. <button
  3485. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3486. hasPermission('printers:update')
  3487. ? 'hover:bg-bambu-dark-tertiary'
  3488. : 'opacity-50 cursor-not-allowed'
  3489. }`}
  3490. onClick={() => {
  3491. if (!hasPermission('printers:update')) return;
  3492. setShowEditModal(true);
  3493. setShowMenu(false);
  3494. }}
  3495. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3496. >
  3497. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3498. {t('common.edit')}
  3499. </button>
  3500. <button
  3501. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3502. onClick={() => {
  3503. setShowPrinterInfo(true);
  3504. setShowMenu(false);
  3505. }}
  3506. >
  3507. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3508. {t('printers.printerInformation')}
  3509. </button>
  3510. {authEnabled && isAdmin && (
  3511. <button
  3512. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3513. onClick={() => {
  3514. setShowMenu(false);
  3515. navigate(`/settings?tab=users&sub=printer-access&view=printers&printer=${printer.id}`);
  3516. }}
  3517. >
  3518. <KeyRound className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3519. {t('printerAccess.whoHasAccess')}
  3520. </button>
  3521. )}
  3522. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3523. <button
  3524. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3525. hasPermission('printers:update')
  3526. ? 'hover:bg-bambu-dark-tertiary'
  3527. : 'opacity-50 cursor-not-allowed'
  3528. }`}
  3529. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3530. onClick={() => {
  3531. if (!hasPermission('printers:update')) return;
  3532. setShowMenu(false);
  3533. if (printer.is_active !== false) {
  3534. handleEnterMaintenance();
  3535. } else {
  3536. maintenanceMutation.mutate(true);
  3537. }
  3538. }}
  3539. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3540. >
  3541. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3542. {printer.is_active !== false
  3543. ? t('printers.maintenance.menuEnter')
  3544. : t('printers.maintenance.menuExit')}
  3545. </button>
  3546. <button
  3547. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3548. onClick={() => {
  3549. connectMutation.mutate();
  3550. setShowMenu(false);
  3551. }}
  3552. >
  3553. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3554. {t('printers.reconnect')}
  3555. </button>
  3556. <button
  3557. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3558. disabled={forceRefreshMutation.isPending}
  3559. onClick={() => {
  3560. forceRefreshMutation.mutate();
  3561. setShowMenu(false);
  3562. }}
  3563. >
  3564. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3565. {t('printers.forceRefresh')}
  3566. </button>
  3567. <button
  3568. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3569. onClick={() => {
  3570. setShowMQTTDebug(true);
  3571. setShowMenu(false);
  3572. }}
  3573. >
  3574. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3575. {t('printers.mqttDebug')}
  3576. </button>
  3577. <button
  3578. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3579. onClick={() => {
  3580. setShowDiagnostic(true);
  3581. setShowMenu(false);
  3582. }}
  3583. >
  3584. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3585. {t('diagnostic.runButton')}
  3586. </button>
  3587. <button
  3588. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3589. hasPermission('printers:delete')
  3590. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3591. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3592. }`}
  3593. onClick={() => {
  3594. if (!hasPermission('printers:delete')) return;
  3595. setShowDeleteConfirm(true);
  3596. setShowMenu(false);
  3597. }}
  3598. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3599. >
  3600. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3601. {t('common.delete')}
  3602. </button>
  3603. </div>
  3604. )}
  3605. </div>
  3606. );
  3607. return (
  3608. <Card
  3609. id={`printer-card-${printer.id}`}
  3610. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3611. style={cardScaleStyle}
  3612. onClick={handleCardClick}
  3613. onDragEnter={handleCardDragEnter}
  3614. onDragOver={handleCardDragOver}
  3615. onDragLeave={handleCardDragLeave}
  3616. onDrop={handleCardDrop}
  3617. >
  3618. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3619. {selectionMode && (
  3620. <div
  3621. className="absolute inset-0 z-20 flex items-start p-2"
  3622. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3623. >
  3624. {isSelected ? (
  3625. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3626. ) : (
  3627. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3628. )}
  3629. </div>
  3630. )}
  3631. {/* Drop zone overlay */}
  3632. {(isDraggingFile || isDropUploading) && (
  3633. <div
  3634. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3635. isDropUploading
  3636. ? 'bg-bambu-green/10 border-bambu-green/50'
  3637. : canDrop
  3638. ? 'bg-bambu-green/10 border-bambu-green'
  3639. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3640. }`}
  3641. >
  3642. <div className="text-center">
  3643. {isDropUploading ? (
  3644. <>
  3645. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3646. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3647. </>
  3648. ) : canDrop ? (
  3649. <>
  3650. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3651. <p className="text-sm font-medium text-bambu-green">
  3652. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3653. </p>
  3654. </>
  3655. ) : (
  3656. <>
  3657. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3658. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3659. {!hasPermission('library:upload')
  3660. ? t('fileManager.noPermissionUpload')
  3661. : t('fileManager.noPermissionAddToQueue')}
  3662. </p>
  3663. </>
  3664. )}
  3665. </div>
  3666. </div>
  3667. )}
  3668. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3669. {/* Header */}
  3670. <div className={getSpacing()}>
  3671. {/* Top row: Image, Name, Menu */}
  3672. <div className="flex items-start justify-between gap-2">
  3673. <div className="flex items-center gap-3 min-w-0 flex-1">
  3674. {/* Printer Model Image */}
  3675. <img
  3676. src={getPrinterImage(printer.model)}
  3677. alt={printer.model || t('common.printer')}
  3678. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3679. />
  3680. <div className="min-w-0 flex-1">
  3681. <div className="flex items-center justify-between gap-2">
  3682. <div className="flex min-w-0 items-center gap-2">
  3683. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3684. {/* Connection indicator dot for compact mode */}
  3685. {viewMode === 'compact' && (() => {
  3686. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3687. const hasSevere = hmsErrors.some(isSevereHMSError);
  3688. const hasWarning = hmsErrors.length > 0;
  3689. const pipColor = !status?.connected
  3690. ? 'bg-status-error'
  3691. : hasSevere
  3692. ? 'bg-status-error'
  3693. : hasWarning
  3694. ? 'bg-status-warning'
  3695. : 'bg-status-ok';
  3696. const pipTitle = !status?.connected
  3697. ? t('printers.connection.offline')
  3698. : hasWarning
  3699. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3700. : t('printers.connection.connected');
  3701. return (
  3702. <div
  3703. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3704. title={pipTitle}
  3705. />
  3706. );
  3707. })()}
  3708. </div>
  3709. {viewMode === 'compact' && showClearPlateButton && (
  3710. <button
  3711. type="button"
  3712. onClick={() => clearPlateMutation.mutate()}
  3713. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3714. aria-label={t('printers.plateStatus.markCleared')}
  3715. className="inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-md bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-300 dark:border-yellow-400/40 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30 transition-colors disabled:opacity-50"
  3716. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3717. >
  3718. {clearPlateMutation.isPending ? (
  3719. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3720. ) : (
  3721. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3722. )}
  3723. </button>
  3724. )}
  3725. </div>
  3726. <p className="text-sm text-bambu-gray">
  3727. {printer.model || 'Unknown Model'}
  3728. {/* Nozzle Info - only in expanded. Every fitted size, not
  3729. just nozzles[0]: the array is indexed by extruder, so on a
  3730. dual-nozzle machine with two sizes fitted showing the
  3731. first entry alone named one hotend and implied it was the
  3732. whole printer. Deduplicated, so the usual matching pair
  3733. still reads as a single "0.4mm". */}
  3734. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3735. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3736. • {installedNozzleDiameters(status).join(' / ')}mm
  3737. </span>
  3738. )}
  3739. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3740. <span className="ml-2 text-bambu-gray">
  3741. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3742. {Math.round(maintenanceInfo.total_print_hours)}h
  3743. </span>
  3744. )}
  3745. </p>
  3746. </div>
  3747. </div>
  3748. </div>
  3749. {/* Badges row - only in expanded mode */}
  3750. {viewMode === 'expanded' && (
  3751. <div className="mt-2">
  3752. <div className="flex flex-wrap items-center gap-2">
  3753. {/* Connection status badge (or Maintenance pill when out of service).
  3754. Defensive: only swap when is_active is EXPLICITLY false. An
  3755. undefined / missing field defaults to "active" so the regular
  3756. pill renders — matches the backend default and prevents test
  3757. fixtures (or stale clients) from accidentally tripping the
  3758. maintenance UI. */}
  3759. {printer.is_active === false ? (
  3760. <span
  3761. className="flex items-center gap-1.5 px-2 py-1 rounded-full text-xs bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400"
  3762. title={t('printers.maintenance.subtitle')}
  3763. >
  3764. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3765. {t('printers.maintenance.pillLabel')}
  3766. </span>
  3767. ) : (
  3768. <span
  3769. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3770. status?.connected
  3771. ? 'bg-status-ok/20 text-status-ok'
  3772. : 'bg-status-error/20 text-status-error'
  3773. }`}
  3774. >
  3775. {status?.connected ? (
  3776. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3777. ) : (
  3778. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3779. )}
  3780. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3781. </span>
  3782. )}
  3783. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3784. {printer.is_active !== false && !status?.connected && (
  3785. <button
  3786. onClick={() => setShowDiagnostic(true)}
  3787. 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"
  3788. title={t('diagnostic.runButton')}
  3789. >
  3790. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3791. {t('diagnostic.runButton')}
  3792. </button>
  3793. )}
  3794. {/* Network connection indicator */}
  3795. {status?.connected && status?.wired_network && (
  3796. <span
  3797. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3798. title={t('printers.connection.ethernet', 'Ethernet')}
  3799. >
  3800. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3801. {t('printers.connection.ethernet', 'Ethernet')}
  3802. </span>
  3803. )}
  3804. {/* WiFi signal indicator */}
  3805. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3806. <span
  3807. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3808. wifiSignal >= -50
  3809. ? 'bg-status-ok/20 text-status-ok'
  3810. : wifiSignal >= -60
  3811. ? 'bg-status-ok/20 text-status-ok'
  3812. : wifiSignal >= -70
  3813. ? 'bg-status-warning/20 text-status-warning'
  3814. : wifiSignal >= -80
  3815. ? 'bg-orange-500/20 text-orange-600'
  3816. : 'bg-status-error/20 text-status-error'
  3817. }`}
  3818. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3819. >
  3820. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3821. {wifiSignal}dBm
  3822. </span>
  3823. )}
  3824. {/* HMS Status Indicator */}
  3825. {status?.connected && (() => {
  3826. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3827. return (
  3828. <button
  3829. onClick={() => setShowHMSModal(true)}
  3830. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3831. knownErrors.length > 0
  3832. ? knownErrors.some(isSevereHMSError)
  3833. ? 'bg-status-error/20 text-status-error'
  3834. : 'bg-status-warning/20 text-status-warning'
  3835. : 'bg-status-ok/20 text-status-ok'
  3836. }`}
  3837. title={t('printers.clickToViewHmsErrors')}
  3838. >
  3839. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3840. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3841. </button>
  3842. );
  3843. })()}
  3844. {/* AI failure detection badge (#1546) — always shown while detection
  3845. is enabled for this printer, like the other health badges. Gray
  3846. "Idle" outside a monitored print, class-colored during one. */}
  3847. {aiDetectionEnabled && (() => {
  3848. const cls = aiDetectionClass(aiDetection);
  3849. const colorClass =
  3850. cls === 'failure'
  3851. ? 'bg-status-error/20 text-status-error'
  3852. : cls === 'warning'
  3853. ? 'bg-status-warning/20 text-status-warning'
  3854. : cls === 'safe'
  3855. ? 'bg-status-ok/20 text-status-ok'
  3856. : cls === 'error'
  3857. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3858. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3859. // 'error' and 'unknown' have no score to quote — saying
  3860. // "Safe (0.000)" for a print nothing is looking at is the
  3861. // whole of #2952.
  3862. const title =
  3863. cls === 'error'
  3864. ? t('printers.aiDetection.tooltipError', {
  3865. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3866. })
  3867. : cls === 'unknown'
  3868. ? t('printers.aiDetection.tooltipUnknown')
  3869. : aiDetection
  3870. ? t('printers.aiDetection.tooltip', {
  3871. status: t(`printers.aiDetection.${cls}`),
  3872. score: aiDetection.score.toFixed(3),
  3873. })
  3874. : t('printers.aiDetection.tooltipIdle');
  3875. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3876. return (
  3877. <button
  3878. onClick={() => setShowAiModal(true)}
  3879. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3880. title={title}
  3881. >
  3882. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3883. {t(`printers.aiDetection.${cls}`)}
  3884. </button>
  3885. );
  3886. })()}
  3887. {/* Maintenance Status Indicator */}
  3888. {maintenanceInfo && (
  3889. <button
  3890. onClick={() => navigate('/maintenance')}
  3891. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3892. maintenanceInfo.due_count > 0
  3893. ? 'bg-status-error/20 text-status-error'
  3894. : maintenanceInfo.warning_count > 0
  3895. ? 'bg-status-warning/20 text-status-warning'
  3896. : 'bg-status-ok/20 text-status-ok'
  3897. }`}
  3898. title={
  3899. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3900. ? `${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`
  3901. : t('printers.maintenanceUpToDate')
  3902. }
  3903. >
  3904. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3905. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3906. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3907. : 'OK'}
  3908. </button>
  3909. )}
  3910. {/* Queue Count Badge */}
  3911. {queueCount > 0 && (
  3912. <button
  3913. onClick={() => navigate('/queue')}
  3914. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-indigo-100 dark:bg-indigo-500/20 text-indigo-700 dark:text-indigo-400 hover:opacity-80 transition-opacity"
  3915. title={t('printers.queue.inQueue', { count: queueCount })}
  3916. >
  3917. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3918. {queueCount}
  3919. </button>
  3920. )}
  3921. {/* Firmware Version Badge */}
  3922. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3923. <button
  3924. onClick={() => setShowFirmwareModal(true)}
  3925. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3926. firmwareInfo.update_available
  3927. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3928. : 'bg-status-ok/20 text-status-ok'
  3929. }`}
  3930. title={
  3931. firmwareInfo.update_available
  3932. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3933. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3934. }
  3935. >
  3936. {firmwareInfo.update_available ? <Download className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <CheckCircle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  3937. {firmwareInfo.current_version}
  3938. </button>
  3939. ) : status?.firmware_version ? (
  3940. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3941. {status.firmware_version}
  3942. </span>
  3943. ) : null}
  3944. {/* Enclosure Door Badge — models with an actual door sensor.
  3945. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3946. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3947. <span
  3948. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3949. status.door_open
  3950. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3951. : 'bg-status-ok/20 text-status-ok'
  3952. }`}
  3953. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3954. >
  3955. {status.door_open ? <DoorOpen className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <DoorClosed className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  3956. </span>
  3957. )}
  3958. </div>
  3959. </div>
  3960. )}
  3961. </div>
  3962. {/* Delete Confirmation */}
  3963. {showDeleteConfirm && (
  3964. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3965. <Card className="w-full max-w-md mx-4">
  3966. <CardContent>
  3967. <div className="flex items-start gap-3 mb-4">
  3968. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3969. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3970. </div>
  3971. <div>
  3972. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3973. <p className="text-sm text-bambu-gray mt-1">
  3974. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3975. </p>
  3976. </div>
  3977. </div>
  3978. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3979. <label className="flex items-start gap-3 cursor-pointer">
  3980. <input
  3981. type="checkbox"
  3982. checked={deleteArchives}
  3983. onChange={(e) => setDeleteArchives(e.target.checked)}
  3984. className="mt-0.5 w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  3985. />
  3986. <div>
  3987. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3988. <p className="text-xs text-bambu-gray mt-0.5">
  3989. {deleteArchives
  3990. ? t('printers.confirm.deleteArchivesNote')
  3991. : t('printers.confirm.keepArchivesNote')}
  3992. </p>
  3993. </div>
  3994. </label>
  3995. </div>
  3996. <div className="flex justify-end gap-2">
  3997. <Button
  3998. variant="secondary"
  3999. onClick={() => {
  4000. setShowDeleteConfirm(false);
  4001. setDeleteArchives(true);
  4002. }}
  4003. >
  4004. {t('common.cancel')}
  4005. </Button>
  4006. <Button
  4007. variant="danger"
  4008. onClick={() => {
  4009. deleteMutation.mutate({ deleteArchives });
  4010. setShowDeleteConfirm(false);
  4011. setDeleteArchives(true);
  4012. }}
  4013. >
  4014. Delete
  4015. </Button>
  4016. </div>
  4017. </CardContent>
  4018. </Card>
  4019. </div>
  4020. )}
  4021. {/* Status — see the equivalent defensive `=== false` check on the
  4022. header pill above for why this is not `!printer.is_active`. */}
  4023. {printer.is_active === false ? (
  4024. // Maintenance mode (#1476) — replaces the cover/progress container
  4025. // so the card keeps the same height. Renders for both compact and
  4026. // expanded view modes so the printer stays visible but plainly
  4027. // out-of-service.
  4028. <>
  4029. {viewMode === 'compact' ? (
  4030. <div className="mt-2 flex items-center gap-2 px-2 py-1.5 rounded-full bg-amber-50 dark:bg-amber-500/15 border border-amber-300 dark:border-amber-500/30">
  4031. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4032. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4033. {t('printers.maintenance.pillLabel')}
  4034. </span>
  4035. </div>
  4036. ) : (
  4037. <>
  4038. <div className="flex items-center gap-2 mb-2">
  4039. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4040. {t('printers.status.title', 'Status')}
  4041. </span>
  4042. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4043. </div>
  4044. <div className="p-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 rounded-[10px] flex items-center gap-3">
  4045. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4046. <div className="flex-1 min-w-0">
  4047. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4048. {t('printers.maintenance.title')}
  4049. </p>
  4050. <p className="text-xs text-bambu-gray mt-0.5">
  4051. {t('printers.maintenance.subtitle')}
  4052. </p>
  4053. </div>
  4054. <Button
  4055. variant="secondary"
  4056. size="sm"
  4057. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4058. onClick={() => maintenanceMutation.mutate(true)}
  4059. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4060. >
  4061. {t('printers.maintenance.exitButton')}
  4062. </Button>
  4063. </div>
  4064. </>
  4065. )}
  4066. </>
  4067. ) : status?.connected && (
  4068. <>
  4069. {/* Compact: Simple status bar */}
  4070. {viewMode === 'compact' ? (
  4071. (() => {
  4072. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4073. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4074. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4075. ? Math.max(0, Math.min(100, status.progress || 0))
  4076. : showClearPlateButton
  4077. ? 100
  4078. : hasProblem
  4079. ? 100
  4080. : 0;
  4081. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4082. const compactProgressClass = hasProblem
  4083. ? 'bg-status-error'
  4084. : status.state === 'PAUSE'
  4085. ? 'bg-status-warning'
  4086. : 'bg-bambu-green';
  4087. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4088. const hasCompactLayers =
  4089. isActiveCompactPrint &&
  4090. status.layer_num != null &&
  4091. status.total_layers != null &&
  4092. status.total_layers > 0;
  4093. return (
  4094. <>
  4095. <div className="relative mt-2 flex items-center gap-2">
  4096. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4097. <div
  4098. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4099. style={{ width: `${compactProgress}%` }}
  4100. />
  4101. </div>
  4102. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4103. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4104. </span>
  4105. </div>
  4106. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4107. enough to answer "which printer finishes first", which is what a
  4108. wall-mounted fleet view is for. One line of the metrics the
  4109. expanded card already renders, using the same formatters and the
  4110. same ETA styling so S and M read alike. The row keeps its height
  4111. when idle so cards don't shift as prints start and stop. */}
  4112. <div className="mt-1 flex min-h-[14px] items-center gap-2 overflow-hidden text-[length:var(--pc-t11,11px)] leading-none text-bambu-gray">
  4113. {hasCompactEta && (
  4114. <>
  4115. <span className="flex shrink-0 items-center gap-1">
  4116. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4117. {formatDuration(status.remaining_time! * 60)}
  4118. </span>
  4119. <span
  4120. className="shrink-0 font-medium text-bambu-green"
  4121. title={t('printers.estimatedCompletion')}
  4122. >
  4123. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4124. </span>
  4125. </>
  4126. )}
  4127. {hasCompactLayers && (
  4128. <span className="flex min-w-0 items-center gap-1 truncate">
  4129. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4130. {status.layer_num}/{status.total_layers}
  4131. </span>
  4132. )}
  4133. </div>
  4134. </>
  4135. );
  4136. })()
  4137. ) : (
  4138. /* Expanded: Full status section */
  4139. <>
  4140. <div className="flex items-center gap-2 mb-2">
  4141. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4142. {t('printers.status.title', 'Status')}
  4143. </span>
  4144. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4145. </div>
  4146. {/* Current Print or Idle Placeholder */}
  4147. {(() => {
  4148. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4149. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4150. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4151. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4152. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4153. // A running print always has at least one object, so a count of
  4154. // zero means "not loaded", not "nothing to skip" — after a
  4155. // restart mid-print the list is empty until something rebuilds
  4156. // it. Treating that as nothing-to-skip disabled the only
  4157. // control that opens the modal, and the modal's own fetch is
  4158. // what rebuilds the list, so the print could never get it back.
  4159. // Exactly one object is the real nothing-to-skip case.
  4160. const objectCount = status.printable_objects_count ?? 0;
  4161. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4162. return (
  4163. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4164. <button
  4165. onClick={() => setShowSkipObjectsModal(true)}
  4166. disabled={!canSkipObjects}
  4167. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4168. canSkipObjects
  4169. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4170. : 'text-bambu-gray/30 cursor-not-allowed'
  4171. }`}
  4172. title={
  4173. !hasPermission('printers:control')
  4174. ? t('printers.permission.noControl')
  4175. : !isActivePrint
  4176. ? t('printers.skipObjects.onlyWhilePrinting')
  4177. : objectCount === 1
  4178. ? t('printers.skipObjects.requiresMultiple')
  4179. : t('printers.skipObjects.tooltip')
  4180. }
  4181. >
  4182. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4183. {objectsData && objectsData.skipped_count > 0 && (
  4184. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[length:var(--pc-t10,10px)] font-bold bg-red-500 text-white rounded-full">
  4185. {objectsData.skipped_count}
  4186. </span>
  4187. )}
  4188. </button>
  4189. <div className="flex items-stretch gap-2">
  4190. <CoverImage
  4191. url={coverUrl}
  4192. printName={printName || undefined}
  4193. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4194. />
  4195. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4196. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4197. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4198. {plateStatusPill}
  4199. </div>
  4200. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4201. {printName || t('printers.noActiveJob', 'No active job')}
  4202. </p>
  4203. <div className="flex h-3 items-center gap-2 text-sm">
  4204. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4205. <div
  4206. 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`}
  4207. style={{ width: `${progress}%` }}
  4208. />
  4209. </div>
  4210. <span className={`w-9 shrink-0 pr-1 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  4211. </div>
  4212. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4213. {isActivePrint ? (
  4214. <>
  4215. {status.remaining_time != null && status.remaining_time > 0 && (
  4216. <>
  4217. <span className="flex items-center gap-1">
  4218. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4219. {formatDuration(status.remaining_time * 60)}
  4220. </span>
  4221. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4222. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4223. </span>
  4224. </>
  4225. )}
  4226. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4227. <span className="flex items-center gap-1">
  4228. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4229. {status.layer_num}/{status.total_layers}
  4230. </span>
  4231. )}
  4232. {currentPrintUser && (
  4233. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4234. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4235. {currentPrintUser}
  4236. </span>
  4237. )}
  4238. </>
  4239. ) : lastPrint ? (
  4240. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4241. Last: {lastPrint.print_name || lastPrint.filename}
  4242. {lastPrint.completed_at && (
  4243. <span className="ml-1 text-bambu-gray/60">
  4244. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4245. </span>
  4246. )}
  4247. </p>
  4248. ) : (
  4249. <span>{t('printers.readyToPrint')}</span>
  4250. )}
  4251. </div>
  4252. </div>
  4253. </div>
  4254. <PrinterQueueWidget
  4255. printerId={printer.id}
  4256. printerModel={printer.model}
  4257. loadedFilamentTypes={loadedFilamentTypes}
  4258. loadedFilaments={loadedFilaments}
  4259. loadedVariants={loadedVariants}
  4260. variant="panelExtension"
  4261. />
  4262. </div>
  4263. );
  4264. })()}
  4265. </>
  4266. )}
  4267. {/* Temperatures */}
  4268. {status.temperatures && viewMode === 'expanded' && (() => {
  4269. // Use actual heater states from MQTT stream
  4270. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4271. const bedHeating = status.temperatures.bed_heating || false;
  4272. const chamberHeating = status.temperatures.chamber_heating || false;
  4273. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4274. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4275. const kinds: HeaterSensorKind[] = ['nozzle'];
  4276. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4277. kinds.push('bed');
  4278. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4279. return kinds;
  4280. })();
  4281. // active_extruder: 0=right, 1=left
  4282. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4283. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4284. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4285. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4286. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4287. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4288. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4289. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4290. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4291. 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 ${
  4292. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4293. }`;
  4294. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4295. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4296. // the widget there is at best dead UI and at worst suggests a
  4297. // control that does nothing. Mirrors the enclosure-door badge
  4298. // gate above.
  4299. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4300. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4301. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4302. // show it only when the printer actually reports it (airduct part id 3,
  4303. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4304. // have a built-in chamber fan that's always present, so they keep the
  4305. // existing model-list gate and the "Chamber Fan" label.
  4306. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4307. const chamberFanLabel = isExhaustModel
  4308. ? t('printers.fans.exhaust')
  4309. : t('printers.fans.chamber');
  4310. // Composed rather than either/or so both lists stay live for
  4311. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4312. // where that fan is an add-on kit — actually report it. Written
  4313. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4314. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4315. // which reads as if removing them were safe.
  4316. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4317. const fanItems: {
  4318. key: string;
  4319. label: string;
  4320. value: number;
  4321. Icon: typeof Fan;
  4322. activeClass: string;
  4323. }[] = [
  4324. {
  4325. key: 'part',
  4326. label: t('printers.fans.partCooling'),
  4327. value: status.cooling_fan_speed ?? 0,
  4328. Icon: Fan,
  4329. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4330. },
  4331. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4332. // Only reported (non-null) when the firmware lists airduct part
  4333. // id 10, i.e. when the fan is physically installed. Placed
  4334. // before the right-hand auxiliary fan so the two aux badges read
  4335. // left-to-right in the same order as the physical hardware.
  4336. ...(status.left_aux_fan_speed != null
  4337. ? [
  4338. {
  4339. key: 'aux2',
  4340. label: t('printers.fans.leftAuxiliary'),
  4341. value: status.left_aux_fan_speed,
  4342. Icon: Wind,
  4343. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4344. },
  4345. ]
  4346. : []),
  4347. {
  4348. key: 'aux',
  4349. label: t('printers.fans.auxiliary'),
  4350. value: status.big_fan1_speed ?? 0,
  4351. Icon: Wind,
  4352. activeClass: 'text-blue-600 dark:text-blue-400',
  4353. },
  4354. ...(showChamberFan
  4355. ? [
  4356. {
  4357. key: 'chamber',
  4358. label: chamberFanLabel,
  4359. value: status.big_fan2_speed ?? 0,
  4360. Icon: AirVent,
  4361. activeClass: 'text-green-600 dark:text-green-400',
  4362. },
  4363. ]
  4364. : []),
  4365. ];
  4366. return (
  4367. <>
  4368. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4369. {/* Nozzle temp - combined for dual nozzle */}
  4370. <div
  4371. className={statusControlClass}
  4372. title={statusControlTitle}
  4373. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4374. >
  4375. <button
  4376. type="button"
  4377. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4378. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4379. onClick={(e) => {
  4380. e.stopPropagation();
  4381. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4382. }}
  4383. >
  4384. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4385. </button>
  4386. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4387. {status.temperatures.nozzle_2 !== undefined ? (
  4388. <>
  4389. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4390. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4391. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4392. </p>
  4393. </>
  4394. ) : singleNozzleSlot ? (
  4395. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4396. <div className="cursor-default">
  4397. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4398. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4399. {Math.round(status.temperatures.nozzle || 0)}°C
  4400. </p>
  4401. </div>
  4402. </NozzleSlotHoverCard>
  4403. ) : (
  4404. <>
  4405. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4406. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4407. {Math.round(status.temperatures.nozzle || 0)}°C
  4408. </p>
  4409. </>
  4410. )}
  4411. {statusControlMenu === 'nozzle-temp' && (
  4412. isDualNozzle ? (
  4413. <IndicatorControlPopover
  4414. title="Set Nozzle Temperatures"
  4415. widthClass="w-[300px]"
  4416. popoverWidth={300}
  4417. popoverHeight={260}
  4418. isPending={nozzleTemperatureMutation.isPending}
  4419. onClose={() => setStatusControlMenu(null)}
  4420. >
  4421. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4422. <NozzleTemperatureControlBox
  4423. label="Left Temp"
  4424. current={status.temperatures.nozzle}
  4425. target={status.temperatures.nozzle_target}
  4426. isActive={activeNozzle === 'L'}
  4427. isPending={nozzleTemperatureMutation.isPending}
  4428. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4429. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4430. />
  4431. <NozzleTemperatureControlBox
  4432. label="Right Temp"
  4433. current={status.temperatures.nozzle_2}
  4434. target={status.temperatures.nozzle_2_target}
  4435. isActive={activeNozzle === 'R'}
  4436. isPending={nozzleTemperatureMutation.isPending}
  4437. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4438. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4439. />
  4440. </div>
  4441. </IndicatorControlPopover>
  4442. ) : (
  4443. <IndicatorControlPopover
  4444. title="Set Nozzle Temperature"
  4445. unit="°C"
  4446. customMin={0}
  4447. customMax={320}
  4448. isPending={nozzleTemperatureMutation.isPending}
  4449. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4450. onClose={() => setStatusControlMenu(null)}
  4451. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4452. />
  4453. )
  4454. )}
  4455. </div>
  4456. <div
  4457. className={statusControlClass}
  4458. title={statusControlTitle}
  4459. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4460. >
  4461. <button
  4462. type="button"
  4463. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4464. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4465. onClick={(e) => {
  4466. e.stopPropagation();
  4467. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4468. }}
  4469. >
  4470. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4471. </button>
  4472. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4473. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4474. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4475. {Math.round(status.temperatures.bed || 0)}°C
  4476. </p>
  4477. {statusControlMenu === 'bed-temp' && (
  4478. <IndicatorControlPopover
  4479. title="Set Bed Temperature"
  4480. unit="°C"
  4481. customMin={0}
  4482. customMax={140}
  4483. isPending={bedTemperatureMutation.isPending}
  4484. options={buildPresetOptions(bedTempPresets, 'C')}
  4485. onClose={() => setStatusControlMenu(null)}
  4486. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4487. />
  4488. )}
  4489. </div>
  4490. {status.temperatures.chamber !== undefined && (() => {
  4491. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4492. // but can't act on M141, so we keep the card read-only there.
  4493. const hasChamberHeater = status.supports_chamber_heater === true;
  4494. return (
  4495. <div
  4496. className={hasChamberHeater
  4497. ? statusControlClass
  4498. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4499. title={hasChamberHeater ? statusControlTitle : undefined}
  4500. onClick={hasChamberHeater
  4501. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4502. : undefined}
  4503. >
  4504. <button
  4505. type="button"
  4506. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4507. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4508. onClick={(e) => {
  4509. e.stopPropagation();
  4510. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4511. }}
  4512. >
  4513. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4514. </button>
  4515. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4516. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4517. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4518. {Math.round(status.temperatures.chamber || 0)}°C
  4519. </p>
  4520. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4521. <IndicatorControlPopover
  4522. title="Set Chamber Temperature"
  4523. unit="°C"
  4524. customMin={0}
  4525. customMax={MAX_CHAMBER_TEMP_C}
  4526. isPending={chamberTemperatureMutation.isPending}
  4527. options={buildPresetOptions(chamberTempPresets, 'C')}
  4528. onClose={() => setStatusControlMenu(null)}
  4529. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4530. />
  4531. )}
  4532. </div>
  4533. );
  4534. })()}
  4535. {/* Active nozzle indicator for dual-nozzle printers */}
  4536. {isDualNozzle && (
  4537. <DualNozzleHoverCard
  4538. leftSlot={leftNozzleSlot}
  4539. rightSlot={rightNozzleSlot}
  4540. activeNozzle={activeNozzle}
  4541. filamentInfo={filamentInfo}
  4542. >
  4543. <div
  4544. 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 ${
  4545. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4546. }`}
  4547. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4548. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4549. >
  4550. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4551. <div className="flex items-center gap-2">
  4552. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4553. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4554. </span>
  4555. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4556. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4557. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4558. </span>
  4559. </div>
  4560. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4561. {statusControlMenu === 'nozzle-select' && (
  4562. <IndicatorControlPopover
  4563. title="Set Nozzle Selection"
  4564. widthClass="w-[300px]"
  4565. popoverWidth={300}
  4566. popoverHeight={140}
  4567. isPending={selectExtruderMutation.isPending}
  4568. options={[
  4569. { label: 'Left', value: 1 },
  4570. { label: 'Right', value: 0 },
  4571. ]}
  4572. onClose={() => setStatusControlMenu(null)}
  4573. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4574. />
  4575. )}
  4576. </div>
  4577. </DualNozzleHoverCard>
  4578. )}
  4579. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4580. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4581. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4582. )}
  4583. </div>
  4584. <div className="mt-2 flex items-center gap-1.5">
  4585. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4586. const active = value > 0;
  4587. return (
  4588. <div
  4589. key={key}
  4590. 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 ${
  4591. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4592. }`}
  4593. title={canUseStatusControls ? label : statusControlTitle}
  4594. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4595. >
  4596. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4597. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4598. {value}%
  4599. </span>
  4600. {statusControlMenu === `fan-${key}` && (
  4601. <IndicatorControlPopover
  4602. title={`Set ${label} Speed`}
  4603. unit="%"
  4604. customMin={0}
  4605. customMax={100}
  4606. isPending={fanSpeedMutation.isPending}
  4607. options={buildPresetOptions(fanSpeedPresets, '%')}
  4608. onClose={() => setStatusControlMenu(null)}
  4609. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4610. />
  4611. )}
  4612. </div>
  4613. );
  4614. })}
  4615. </div>
  4616. </>
  4617. );
  4618. })()}
  4619. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4620. {/* Controls */}
  4621. {viewMode === 'expanded' && (() => {
  4622. // Determine print state for control buttons
  4623. const isRunning = status.state === 'RUNNING';
  4624. const isPaused = status.state === 'PAUSE';
  4625. const isPrinting = isRunning || isPaused;
  4626. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4627. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4628. 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';
  4629. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4630. return (
  4631. <div className="mt-3">
  4632. {/* Section Header */}
  4633. <div className="flex items-center gap-2 mb-2">
  4634. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4635. {t('printers.controls')}
  4636. </span>
  4637. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4638. </div>
  4639. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4640. {/* Left: Secondary controls */}
  4641. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4642. <button
  4643. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4644. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4645. className={`${iconControlClass} ${
  4646. status.chamber_light
  4647. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4648. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4649. }`}
  4650. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4651. >
  4652. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4653. </button>
  4654. {/* Airduct Mode (P2S / X2D / H2*) */}
  4655. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4656. const isHeating = status.airduct_mode === 1;
  4657. const Icon = isHeating ? Flame : Snowflake;
  4658. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4659. const bg = isHeating ? 'bg-orange-50 dark:bg-orange-500/10 text-orange-700 dark:text-orange-400 hover:bg-orange-500/20' : 'bg-sky-50 dark:bg-sky-500/10 text-sky-700 dark:text-sky-400 hover:bg-sky-500/20';
  4660. return (
  4661. <div className="relative">
  4662. <button
  4663. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4664. disabled={!hasPermission('printers:control')}
  4665. className={`${iconControlClass} ${bg}`}
  4666. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4667. >
  4668. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4669. </button>
  4670. {showAirductMenu === printer.id && (
  4671. <>
  4672. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4673. <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]">
  4674. {([
  4675. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4676. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4677. ] as const).map(({ mode, label, modeId }) => (
  4678. <button
  4679. key={mode}
  4680. onClick={() => {
  4681. airductMutation.mutate(mode);
  4682. setShowAirductMenu(null);
  4683. }}
  4684. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4685. status.airduct_mode === modeId
  4686. ? 'text-bambu-green bg-bambu-green/10'
  4687. : 'text-white hover:bg-bambu-dark-tertiary'
  4688. }`}
  4689. >
  4690. {mode === 'heating' ? <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Snowflake className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4691. {label}
  4692. </button>
  4693. ))}
  4694. </div>
  4695. </>
  4696. )}
  4697. </div>
  4698. );
  4699. })()}
  4700. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4701. {(() => {
  4702. const canControl = hasPermission('printers:control');
  4703. const disabled = isPrinting || !canControl;
  4704. const jogButtonClass = 'flex h-8 w-8 items-center justify-center rounded bg-indigo-100 dark:bg-indigo-500/15 text-indigo-700 dark:text-indigo-300 transition-colors hover:bg-indigo-200 dark:hover:bg-indigo-500/30 disabled:cursor-not-allowed disabled:opacity-50';
  4705. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4706. // nozzle-bed gap that means the same thing on every printer, so the
  4707. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4708. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4709. // plate toward the nozzle and closes it.
  4710. const zMovesToolhead = isBedSlinger(printer.model);
  4711. const requestZJog = (arrow: 'up' | 'down') => {
  4712. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4713. // No not-homed gate here, and no endstop bypass to gate either:
  4714. // since #2579 the jog is a bare move that never touches M211. That
  4715. // does not make it clamped — the firmware ignores soft endstops on
  4716. // MQTT G-code entirely, which is what the banner above warns about.
  4717. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4718. };
  4719. const requestXyJog = (x: number, y: number) => {
  4720. xyJogMutation.mutate({ x, y });
  4721. };
  4722. const requestExtruderJog = (distance: number) => {
  4723. extruderJogMutation.mutate(distance);
  4724. };
  4725. return (
  4726. <div className="relative">
  4727. <button
  4728. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4729. disabled={disabled}
  4730. className={`${iconControlClass} ${
  4731. disabled
  4732. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4733. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4734. }`}
  4735. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4736. >
  4737. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4738. </button>
  4739. {showBedJogMenu === printer.id && (
  4740. <>
  4741. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4742. <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">
  4743. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4744. {t('printers.bedJog.title')}
  4745. </div>
  4746. <div className="h-px bg-bambu-dark-tertiary" />
  4747. {/* #2579: Bambu firmware does not enforce soft endstops on
  4748. G-code sent over MQTT, so manual moves can drive past the
  4749. travel limits and cause a collision. Not fixable from our
  4750. side — warn prominently. */}
  4751. <div className="flex items-start gap-1.5 bg-yellow-500/10 px-3 py-2 text-[length:var(--pc-t11,11px)] leading-snug text-yellow-700 dark:text-yellow-400">
  4752. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4753. <span>{t('printers.bedJog.limitWarning')}</span>
  4754. </div>
  4755. <div className="h-px bg-bambu-dark-tertiary" />
  4756. <div className="flex justify-center px-3 py-2.5">
  4757. <div className="flex items-center justify-center gap-3">
  4758. <div className="grid grid-cols-3 gap-1">
  4759. <div />
  4760. <button
  4761. onClick={() => requestXyJog(0, bedJogStep)}
  4762. disabled={xyJogMutation.isPending}
  4763. className={jogButtonClass}
  4764. aria-label="Move Y forward"
  4765. >
  4766. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4767. </button>
  4768. <div />
  4769. <button
  4770. onClick={() => requestXyJog(-bedJogStep, 0)}
  4771. disabled={xyJogMutation.isPending}
  4772. className={jogButtonClass}
  4773. aria-label="Move X left"
  4774. >
  4775. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4776. </button>
  4777. <button
  4778. onClick={() => {
  4779. setShowBedJogMenu(null);
  4780. homeAxesMutation.mutate('all');
  4781. }}
  4782. disabled={homeAxesMutation.isPending}
  4783. className={jogButtonClass}
  4784. aria-label={t('printers.bedJog.homeZ')}
  4785. >
  4786. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4787. </button>
  4788. <button
  4789. onClick={() => requestXyJog(bedJogStep, 0)}
  4790. disabled={xyJogMutation.isPending}
  4791. className={jogButtonClass}
  4792. aria-label="Move X right"
  4793. >
  4794. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4795. </button>
  4796. <div />
  4797. <button
  4798. onClick={() => requestXyJog(0, -bedJogStep)}
  4799. disabled={xyJogMutation.isPending}
  4800. className={jogButtonClass}
  4801. aria-label="Move Y back"
  4802. >
  4803. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4804. </button>
  4805. <div />
  4806. </div>
  4807. <div className="flex flex-col items-center gap-1">
  4808. <button
  4809. onClick={() => requestZJog('up')}
  4810. disabled={bedJogMutation.isPending}
  4811. className={jogButtonClass}
  4812. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4813. >
  4814. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4815. </button>
  4816. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4817. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4818. </div>
  4819. <button
  4820. onClick={() => requestZJog('down')}
  4821. disabled={bedJogMutation.isPending}
  4822. className={jogButtonClass}
  4823. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4824. >
  4825. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4826. </button>
  4827. </div>
  4828. <div className="flex flex-col items-center gap-1">
  4829. <button
  4830. onClick={() => requestExtruderJog(-bedJogStep)}
  4831. disabled={extruderJogMutation.isPending}
  4832. className={jogButtonClass}
  4833. aria-label="Retract filament"
  4834. >
  4835. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4836. </button>
  4837. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4838. <span className="text-sm font-semibold leading-none">E</span>
  4839. </div>
  4840. <button
  4841. onClick={() => requestExtruderJog(bedJogStep)}
  4842. disabled={extruderJogMutation.isPending}
  4843. className={jogButtonClass}
  4844. aria-label="Extrude filament"
  4845. >
  4846. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4847. </button>
  4848. </div>
  4849. </div>
  4850. </div>
  4851. <div className="h-px bg-bambu-dark-tertiary" />
  4852. <div className="px-3 pt-2.5 pb-3">
  4853. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4854. {t('printers.bedJog.step')}
  4855. </div>
  4856. <div className="flex gap-1">
  4857. {[1, 10, 50].map((step) => (
  4858. <button
  4859. key={step}
  4860. onClick={() => setBedJogStep(step)}
  4861. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4862. bedJogStep === step
  4863. ? 'bg-bambu-green/20 text-bambu-green'
  4864. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4865. }`}
  4866. >
  4867. {step}
  4868. </button>
  4869. ))}
  4870. </div>
  4871. </div>
  4872. </div>
  4873. </>
  4874. )}
  4875. </div>
  4876. );
  4877. })()}
  4878. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4879. <button
  4880. onClick={handleTogglePlateDetection}
  4881. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4882. className={`${iconControlClass} rounded-r-none ${
  4883. printer.plate_detection_enabled
  4884. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4885. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4886. }`}
  4887. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4888. >
  4889. {plateDetectionMutation.isPending ? (
  4890. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4891. ) : (
  4892. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4893. )}
  4894. </button>
  4895. <button
  4896. onClick={handleOpenPlateManagement}
  4897. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4898. 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 ${
  4899. printer.plate_detection_enabled
  4900. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4901. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4902. }`}
  4903. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4904. >
  4905. {isCheckingPlate ? (
  4906. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4907. ) : (
  4908. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4909. )}
  4910. </button>
  4911. </div>
  4912. {/* Print Speed */}
  4913. {(() => (
  4914. <div className="relative">
  4915. <button
  4916. data-testid="speed-control"
  4917. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4918. disabled={!isPrinting || !hasPermission('printers:control')}
  4919. className={`${iconControlClass} ${
  4920. isPrinting
  4921. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4922. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4923. }`}
  4924. title={isPrinting ? t('printers.speed.title') : undefined}
  4925. >
  4926. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4927. </button>
  4928. {showSpeedMenu === printer.id && (
  4929. <>
  4930. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4931. <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]">
  4932. {([
  4933. { mode: 1, label: t('printers.speed.silent') },
  4934. { mode: 2, label: t('printers.speed.standard') },
  4935. { mode: 3, label: t('printers.speed.sport') },
  4936. { mode: 4, label: t('printers.speed.ludicrous') },
  4937. ] as const).map(({ mode, label }) => (
  4938. <button
  4939. key={mode}
  4940. onClick={() => {
  4941. printSpeedMutation.mutate(mode);
  4942. setShowSpeedMenu(null);
  4943. }}
  4944. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4945. status.speed_level === mode
  4946. ? 'text-bambu-green bg-bambu-green/10'
  4947. : 'text-white hover:bg-bambu-dark-tertiary'
  4948. }`}
  4949. >
  4950. {label}
  4951. </button>
  4952. ))}
  4953. </div>
  4954. </>
  4955. )}
  4956. </div>
  4957. ))()}
  4958. </div>
  4959. {/* Right: Print Control Buttons */}
  4960. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4961. {/* Pause/Resume button */}
  4962. {(() => {
  4963. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4964. return (
  4965. <button
  4966. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4967. disabled={pauseUnavailable}
  4968. className={`
  4969. ${printControlClass}
  4970. ${pauseUnavailable
  4971. ? unavailablePrintActionClass
  4972. : isPaused
  4973. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4974. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4975. }
  4976. `}
  4977. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4978. >
  4979. {isPaused ? <Play className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Pause className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4980. {isPaused ? t('printers.resume') : t('printers.pause')}
  4981. </button>
  4982. );
  4983. })()}
  4984. {/* Stop button */}
  4985. {(() => {
  4986. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4987. return (
  4988. <button
  4989. onClick={() => setShowStopConfirm(true)}
  4990. disabled={stopUnavailable}
  4991. className={`
  4992. ${printControlClass}
  4993. ${stopUnavailable
  4994. ? unavailablePrintActionClass
  4995. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4996. }
  4997. `}
  4998. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4999. >
  5000. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5001. {t('printers.stop')}
  5002. </button>
  5003. );
  5004. })()}
  5005. </div>
  5006. </div>
  5007. </div>
  5008. );
  5009. })()}
  5010. {/* AMS Units - 2-Column Grid Layout */}
  5011. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  5012. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  5013. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  5014. const htAms = amsData.filter(ams => ams.tray.length === 1);
  5015. // The external spool can only be hidden while some AMS remains to
  5016. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  5017. // filament section, so the toggle is not offered there and a stored
  5018. // preference from a printer that later lost its AMS cannot blank the
  5019. // row either — both read through canHideExternalSpool.
  5020. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  5021. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5022. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5023. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5024. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5025. // floating point, and that lands verbatim in the DOM.
  5026. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5027. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5028. // already grow to fill the row, so the 3.5rem is a floor they sit
  5029. // well above in practice -- raising it just costs a unit its place
  5030. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5031. // its line, and flex-grow stretches its single slot across the whole
  5032. // card. The AMS-HT's own width does scale, below, because its
  5033. // readings sit beside the slot rather than under it.
  5034. const slotMinWidth = '3.5rem';
  5035. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5036. // The AMS-HT holds a single spool, and its slot is the only thing
  5037. // on that row able to grow -- so it swallowed every spare pixel and
  5038. // shoved the temperature and humidity hard against the card's edge.
  5039. // Capping it at roughly two ordinary slots keeps the readings clear
  5040. // of the edge; the cap scales because the text inside the slot does.
  5041. const htSlotStyle: React.CSSProperties = {
  5042. minWidth: slotMinWidth,
  5043. maxWidth: scaledRem(7.25),
  5044. };
  5045. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5046. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5047. });
  5048. // #1762 (comment 2): while a print is running/paused, overlay a small
  5049. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5050. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5051. // staged to a printer with mismatched filament: the wrong-slot pill
  5052. // is visible the instant printing starts.
  5053. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5054. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5055. ? status.ams_mapping
  5056. : [];
  5057. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5058. const boundedSlotCount = Math.max(1, slotCount);
  5059. const gapCount = Math.max(0, boundedSlotCount - 1);
  5060. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5061. return {
  5062. flex: `1 1 ${minWidth}`,
  5063. minWidth,
  5064. };
  5065. };
  5066. return (
  5067. <div className="mt-3">
  5068. {/* Section Header */}
  5069. <div className="flex items-center gap-2 mb-2">
  5070. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5071. {t('printers.filaments')}
  5072. </span>
  5073. <AmsBackupBadge
  5074. state={status.ams_filament_backup}
  5075. onClick={() => setAmsBackupModalOpen(true)}
  5076. />
  5077. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5078. {/* Offered only when an AMS is present: on a printer that
  5079. feeds from the external spool alone, hiding it would
  5080. empty the row entirely (#1782). */}
  5081. {canHideExternalSpool && (
  5082. <>
  5083. <ExternalSpoolToggle
  5084. hidden={externalSpoolHidden}
  5085. onClick={toggleExternalSpool}
  5086. />
  5087. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5088. </>
  5089. )}
  5090. </div>
  5091. {/* AMS Content */}
  5092. <div className="flex flex-wrap gap-2">
  5093. {/* Regular AMS units */}
  5094. {regularAms.map((ams) => {
  5095. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5096. return (
  5097. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5098. {/* Header: Label + Stats (no icon) */}
  5099. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5100. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5101. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5102. <AmsNameHoverCard
  5103. ams={ams}
  5104. printerId={printer.id}
  5105. label={getAmsLabel(ams.id, ams.tray.length)}
  5106. amsLabels={amsLabels}
  5107. canEdit={hasPermission('printers:update')}
  5108. onSaved={refetchAmsLabels}
  5109. >
  5110. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5111. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5112. </span>
  5113. </AmsNameHoverCard>
  5114. {sideBadge?.kind === 'inlet' ? (
  5115. <InletBadge
  5116. inlet={sideBadge.inlet}
  5117. title={t('printers.amsSwitchInletTooltip', {
  5118. inlet: sideBadge.inlet,
  5119. side: FTS_INLET_SIDE[sideBadge.inlet],
  5120. })}
  5121. />
  5122. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5123. <NozzleBadge side={sideBadge.side} />
  5124. ) : null}
  5125. </div>
  5126. {(ams.humidity != null || ams.temp != null) && (
  5127. <div className="flex shrink-0 items-center gap-1.5">
  5128. {ams.humidity != null && (
  5129. <HumidityIndicator
  5130. humidity={ams.humidity}
  5131. goodThreshold={amsThresholds?.humidityGood}
  5132. fairThreshold={amsThresholds?.humidityFair}
  5133. onClick={() => setAmsHistoryModal({
  5134. amsId: ams.id,
  5135. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5136. mode: 'humidity',
  5137. })}
  5138. compact
  5139. />
  5140. )}
  5141. {ams.temp != null && (
  5142. <div className="mr-1">
  5143. <TemperatureIndicator
  5144. temp={ams.temp}
  5145. goodThreshold={amsThresholds?.tempGood}
  5146. fairThreshold={amsThresholds?.tempFair}
  5147. onClick={() => setAmsHistoryModal({
  5148. amsId: ams.id,
  5149. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5150. mode: 'temperature',
  5151. })}
  5152. compact
  5153. />
  5154. </div>
  5155. )}
  5156. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5157. Screen-only models (P1 series) keep the control but can't
  5158. be commanded: it stays disabled and says why (#2533). */}
  5159. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5160. <button
  5161. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5162. onClick={(e) => {
  5163. if (ams.dry_time > 0) {
  5164. stopDryingMutation.mutate(ams.id);
  5165. } else if (dryingPopoverAmsId === ams.id) {
  5166. setDryingPopoverAmsId(null);
  5167. } else {
  5168. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5169. }
  5170. }}
  5171. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5172. ams.dry_time > 0
  5173. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5174. : status.drying_screen_only || ams.dry_sf_reason?.length
  5175. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5176. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5177. }`}
  5178. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t(dryingBlockedKey(ams.dry_sf_reason)) : t('printers.drying.start')}
  5179. >
  5180. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5181. </button>
  5182. )}
  5183. </div>
  5184. )}
  5185. </div>
  5186. {/* Drying status bar. A dry_time whose countdown is not
  5187. ticking, with no active drying phase (a parked command —
  5188. e.g. an H2D mid-print already powering other drying — or
  5189. a paused cycle), is shown as "not running", not as an
  5190. active cycle: the amber badge claiming a running dry
  5191. that the AMS never began is how this was found. */}
  5192. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5193. <div className="flex items-center gap-2 rounded-lg bg-slate-100 dark:bg-slate-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]" title={t('printers.drying.notRunningHint')}>
  5194. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5195. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5196. {ams.dry_filament && (
  5197. <span className="text-slate-500/90 dark:text-slate-400/80">
  5198. {ams.dry_target_temp != null
  5199. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5200. : ams.dry_filament}
  5201. </span>
  5202. )}
  5203. {!status.drying_screen_only && (
  5204. <button
  5205. onClick={() => stopDryingMutation.mutate(ams.id)}
  5206. disabled={stopDryingMutation.isPending}
  5207. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5208. title={t('printers.drying.stop')}
  5209. >
  5210. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5211. </button>
  5212. )}
  5213. </div>
  5214. )}
  5215. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5216. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
  5217. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5218. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5219. {/* The temperature is only ever known from the target we
  5220. cached when sending the command — the filament can also
  5221. be read off a uniformly loaded unit, so it can outlive
  5222. the temperature (#2759). */}
  5223. {ams.dry_filament && (
  5224. <span className="text-amber-700/80 dark:text-amber-300/70">
  5225. {ams.dry_target_temp != null
  5226. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5227. : ams.dry_filament}
  5228. </span>
  5229. )}
  5230. <span className="text-amber-700/80 dark:text-amber-300/70">
  5231. {t('printers.drying.timeRemaining', {
  5232. time: ams.dry_time >= 60
  5233. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5234. : `${ams.dry_time}m`
  5235. })}
  5236. </span>
  5237. {/* A cycle on a screen-only model was started at the printer
  5238. and can only be stopped there (#2533). */}
  5239. {!status.drying_screen_only && (
  5240. <button
  5241. onClick={() => stopDryingMutation.mutate(ams.id)}
  5242. disabled={stopDryingMutation.isPending}
  5243. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5244. title={t('printers.drying.stop')}
  5245. >
  5246. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5247. </button>
  5248. )}
  5249. </div>
  5250. )}
  5251. {/* Slots grid: 4 columns - always render 4 slots */}
  5252. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5253. {[0, 1, 2, 3].map((slotIdx) => {
  5254. // Find tray data for this slot (may be undefined if data incomplete)
  5255. // Use array index if available, as tray.id may not always be set
  5256. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5257. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5258. const isEmpty = !tray?.tray_type;
  5259. const emptyKind = getEmptySlotKind(tray);
  5260. // Check if this is the currently loaded tray
  5261. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5262. const globalTrayId = ams.id * 4 + slotIdx;
  5263. const isActive = effectiveTrayNow === globalTrayId;
  5264. // Runout guidance (#2587): the slot the paused print now
  5265. // expects filament in, and the slot that ran out.
  5266. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5267. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5268. // Get cloud preset info if available
  5269. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5270. // Get saved slot preset mapping (for user-configured slots)
  5271. const slotPreset = slotPresets?.[globalTrayId];
  5272. // Only trusted while it still describes what the printer reports in the
  5273. // slot: the row survives a spool swap, and the display chain below puts
  5274. // it ahead of the live filament id (see slotPresetDescribesTray).
  5275. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5276. ? slotPreset?.preset_name
  5277. : undefined;
  5278. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5279. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5280. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5281. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5282. // Slot-assigned-only spool fill (no tag link required)
  5283. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5284. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5285. : undefined;
  5286. const slotSpoolForFill = slotAssignmentForFill
  5287. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5288. : undefined;
  5289. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5290. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5291. : null;
  5292. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5293. const inventoryFill = (() => {
  5294. const sp = inventoryAssignment?.spool;
  5295. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5296. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5297. }
  5298. return null;
  5299. })();
  5300. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5301. // (inventory weight_used may be stale or over-counted — #676)
  5302. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5303. ? null : inventoryFill;
  5304. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5305. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5306. : resolvedInventoryFill !== null ? 'inventory' as const
  5307. : hasFillLevel ? 'ams' as const
  5308. : undefined;
  5309. // Build filament data for hover card
  5310. const filamentData = tray?.tray_type ? {
  5311. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5312. // Spoolman spool name wins over cloud lookup so a slot bound to
  5313. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5314. // Design PLA") instead of whatever the printer's filament_id
  5315. // resolves to in the cloud catalog (often "Generic PLA" for
  5316. // P-prefix local presets). Spoolman's filament.name is just the
  5317. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5318. // the hover card shows "Devil Design PLA Basic" rather than the
  5319. // vendor-less form. Strip the "@<printer>..." suffix that
  5320. // BambuStudio appends to user-preset names.
  5321. profile: slotPresetName || (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,
  5322. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5323. colorHex: tray.tray_color || null,
  5324. kFactor: formatKValue(tray.k),
  5325. fillLevel: effectiveFill,
  5326. trayUuid: tray.tray_uuid || null,
  5327. tagUid: tray.tag_uid || null,
  5328. fillSource,
  5329. } : null;
  5330. // Check if this specific slot is being refreshed
  5331. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5332. refreshingSlot?.slotId === slotIdx;
  5333. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5334. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5335. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5336. ? `P${activePrintSlotIdx + 1}`
  5337. : null;
  5338. // Slot visual content (goes inside hover card)
  5339. const slotVisual = (
  5340. <div
  5341. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5342. isExpectedSlot
  5343. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5344. : isRanOutSlot
  5345. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5346. : isActive
  5347. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5348. : ''
  5349. }`}
  5350. >
  5351. {isExpectedSlot && (
  5352. <span
  5353. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5354. title={t('printers.expectedSlot.title')}
  5355. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  5356. >
  5357. ↓
  5358. </span>
  5359. )}
  5360. {activePrintSlotLabel && (
  5361. <span
  5362. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5363. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5364. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  5365. >
  5366. {activePrintSlotLabel}
  5367. </span>
  5368. )}
  5369. {/* Filament color circle with 1-based slot number centered inside */}
  5370. <FilamentSlotCircle
  5371. trayColor={tray?.tray_color}
  5372. trayType={tray?.tray_type}
  5373. isEmpty={isEmpty}
  5374. emptyKind={emptyKind}
  5375. slotNumber={slotIdx + 1}
  5376. />
  5377. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5378. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5379. </div>
  5380. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5381. {/* Fill bar */}
  5382. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5383. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5384. <div
  5385. className="h-full rounded-full transition-all"
  5386. style={{
  5387. width: `${effectiveFill}%`,
  5388. backgroundColor: getFillBarColor(effectiveFill),
  5389. }}
  5390. />
  5391. )}
  5392. </div>
  5393. </div>
  5394. );
  5395. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5396. return (
  5397. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5398. {/* Loading overlay during RFID re-read */}
  5399. {isRefreshing && (
  5400. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5401. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5402. </div>
  5403. )}
  5404. {/* Hover card wraps only the visual content */}
  5405. {filamentData ? (
  5406. <FilamentHoverCard
  5407. data={filamentData}
  5408. actions={renderAmsSlotActions({
  5409. amsId: ams.id,
  5410. slotId: slotIdx,
  5411. loadTrayId: ams.id * 4 + slotIdx,
  5412. isRefreshing,
  5413. })}
  5414. spoolman={{
  5415. enabled: spoolmanEnabled,
  5416. // #1457: slot assignment is the user's most explicit action — it must
  5417. // outrank the tag-link, which can be stale when a non-RFID slot's
  5418. // fallback tag is still attached to a previous spool in Spoolman.
  5419. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5420. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5421. spoolmanUrl,
  5422. syncMode: spoolmanSyncMode,
  5423. // Suppress Link button when slot is already occupied by ANY assignment
  5424. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5425. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5426. // still appearing on slots with a local Devil Design PLA assigned.
  5427. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5428. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5429. setLinkSpoolModal({
  5430. tagUid: filamentData.tagUid || linkTag,
  5431. trayUuid: filamentData.trayUuid || '',
  5432. printerId: printer.id,
  5433. amsId: ams.id,
  5434. trayId: slotIdx,
  5435. });
  5436. } : undefined,
  5437. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5438. }}
  5439. inventory={(() => {
  5440. if (spoolmanEnabled) {
  5441. if (spoolmanLoading) return undefined;
  5442. const slotAssignment = slotAssignmentForFill;
  5443. const spoolmanSpool = slotSpoolForFill;
  5444. return {
  5445. assignedSpool: spoolmanSpool ? {
  5446. id: spoolmanSpool.id,
  5447. material: spoolmanSpool.material,
  5448. subtype: spoolmanSpool.subtype,
  5449. brand: spoolmanSpool.brand ?? null,
  5450. color_name: spoolmanSpool.color_name ?? null,
  5451. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5452. // The spool's own swatch (#2967). Spoolman carries the
  5453. // extra stops but has no effect field at all, so those
  5454. // rolls gradient and never shimmer.
  5455. rgba: spoolmanSpool.rgba ?? null,
  5456. extra_colors: spoolmanSpool.extra_colors ?? null,
  5457. effect_type: spoolmanSpool.effect_type ?? null,
  5458. remainingWeightGrams: spoolmanSpool.label_weight
  5459. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5460. : undefined,
  5461. } : null,
  5462. onAssignSpool: () => setAssignSpoolModal({
  5463. printerId: printer.id,
  5464. amsId: ams.id,
  5465. trayId: slotIdx,
  5466. trayInfo: {
  5467. type: tray?.tray_type || filamentData.profile,
  5468. material: tray?.tray_type ?? undefined,
  5469. profile: filamentData.profile,
  5470. color: filamentData.colorHex || '',
  5471. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5472. },
  5473. }),
  5474. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5475. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5476. };
  5477. }
  5478. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5479. return {
  5480. assignedSpool: assignment?.spool ? {
  5481. id: assignment.spool.id,
  5482. material: assignment.spool.material,
  5483. subtype: assignment.spool.subtype,
  5484. brand: assignment.spool.brand,
  5485. color_name: assignment.spool.color_name,
  5486. // The spool's own swatch (#2967).
  5487. rgba: assignment.spool.rgba ?? null,
  5488. extra_colors: assignment.spool.extra_colors ?? null,
  5489. effect_type: assignment.spool.effect_type ?? null,
  5490. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5491. } : null,
  5492. onAssignSpool: () => setAssignSpoolModal({
  5493. printerId: printer.id,
  5494. amsId: ams.id,
  5495. trayId: slotIdx,
  5496. trayInfo: {
  5497. type: tray?.tray_type || filamentData.profile,
  5498. material: tray?.tray_type ?? undefined,
  5499. profile: filamentData.profile,
  5500. color: filamentData.colorHex || '',
  5501. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5502. },
  5503. }),
  5504. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5505. isAssigned: !!assignment || isBambuLabSpool(tray),
  5506. };
  5507. })()}
  5508. configureSlot={{
  5509. enabled: hasPermission('printers:control'),
  5510. onConfigure: () => setConfigureSlotModal({
  5511. amsId: ams.id,
  5512. trayId: slotIdx,
  5513. trayCount: ams.tray.length,
  5514. trayType: tray?.tray_type || undefined,
  5515. trayColor: tray?.tray_color || undefined,
  5516. traySubBrands: tray?.tray_sub_brands || undefined,
  5517. trayInfoIdx: tray?.tray_info_idx || undefined,
  5518. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5519. caliIdx: tray?.cali_idx,
  5520. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5521. }),
  5522. }}
  5523. >
  5524. {slotVisual}
  5525. </FilamentHoverCard>
  5526. ) : (
  5527. <EmptySlotHoverCard
  5528. kind={emptyKind ?? undefined}
  5529. actions={renderAmsSlotActions({
  5530. amsId: ams.id,
  5531. slotId: slotIdx,
  5532. loadTrayId: ams.id * 4 + slotIdx,
  5533. isRefreshing,
  5534. })}
  5535. configureSlot={{
  5536. enabled: hasPermission('printers:control'),
  5537. onConfigure: () => setConfigureSlotModal({
  5538. amsId: ams.id,
  5539. trayId: slotIdx,
  5540. trayCount: ams.tray.length,
  5541. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5542. }),
  5543. }}
  5544. onAssignSpool={() => setAssignSpoolModal({
  5545. printerId: printer.id,
  5546. amsId: ams.id,
  5547. trayId: slotIdx,
  5548. trayInfo: {
  5549. type: '',
  5550. material: undefined,
  5551. profile: '',
  5552. color: '',
  5553. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5554. },
  5555. })}
  5556. >
  5557. {slotVisual}
  5558. </EmptySlotHoverCard>
  5559. )}
  5560. </div>
  5561. );
  5562. })}
  5563. </div>
  5564. </div>
  5565. );
  5566. })}
  5567. {/* HT AMS units */}
  5568. {htAms.map((ams) => {
  5569. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5570. const tray = ams.tray[0];
  5571. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5572. const isEmpty = !tray?.tray_type;
  5573. const emptyKind = getEmptySlotKind(tray);
  5574. // Check if this is the currently loaded tray
  5575. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5576. const isActive = effectiveTrayNow === globalTrayId;
  5577. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5578. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5579. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5580. // Get cloud preset info if available
  5581. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5582. // Get saved slot preset mapping (for user-configured slots)
  5583. const slotPreset = slotPresets?.[globalTrayId];
  5584. // Only trusted while it still describes what the printer reports in the
  5585. // slot: the row survives a spool swap, and the display chain below puts
  5586. // it ahead of the live filament id (see slotPresetDescribesTray).
  5587. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5588. ? slotPreset?.preset_name
  5589. : undefined;
  5590. const htSlotId = tray?.id ?? 0;
  5591. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5592. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5593. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5594. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5595. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5596. const htInventoryFill = (() => {
  5597. const sp = htInventoryAssignment?.spool;
  5598. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5599. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5600. }
  5601. return null;
  5602. })();
  5603. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5604. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5605. ? null : htInventoryFill;
  5606. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5607. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5608. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5609. : undefined;
  5610. const htSlotSpoolForFill = htSlotAssignmentForFill
  5611. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5612. : undefined;
  5613. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5614. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5615. : null;
  5616. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5617. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5618. : htResolvedInventoryFill !== null ? 'inventory' as const
  5619. : hasFillLevel ? 'ams' as const
  5620. : undefined;
  5621. // Build filament data for hover card
  5622. const filamentData = tray?.tray_type ? {
  5623. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5624. profile: slotPresetName || (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,
  5625. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5626. colorHex: tray.tray_color || null,
  5627. kFactor: formatKValue(tray.k),
  5628. fillLevel: htEffectiveFill,
  5629. trayUuid: tray.tray_uuid || null,
  5630. tagUid: tray.tag_uid || null,
  5631. fillSource: htFillSource,
  5632. } : null;
  5633. // Check if this specific slot is being refreshed
  5634. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5635. refreshingSlot?.slotId === htSlotId;
  5636. // #1762 (comment 2): active print-slot index for this HT slot.
  5637. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5638. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5639. ? `P${htActivePrintSlotIdx + 1}`
  5640. : null;
  5641. // Slot visual content (goes inside hover card)
  5642. const slotVisual = (
  5643. <div
  5644. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5645. isExpectedSlot
  5646. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5647. : isRanOutSlot
  5648. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5649. : isActive
  5650. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5651. : ''
  5652. }`}
  5653. >
  5654. {isExpectedSlot && (
  5655. <span
  5656. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5657. title={t('printers.expectedSlot.title')}
  5658. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  5659. >
  5660. ↓
  5661. </span>
  5662. )}
  5663. {htActivePrintSlotLabel && (
  5664. <span
  5665. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5666. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5667. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  5668. >
  5669. {htActivePrintSlotLabel}
  5670. </span>
  5671. )}
  5672. {/* Filament color circle with 1-based slot number centered inside */}
  5673. <FilamentSlotCircle
  5674. trayColor={tray?.tray_color}
  5675. trayType={tray?.tray_type}
  5676. isEmpty={isEmpty}
  5677. emptyKind={emptyKind}
  5678. slotNumber={1}
  5679. />
  5680. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5681. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5682. </div>
  5683. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5684. {/* Fill bar */}
  5685. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5686. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5687. <div
  5688. className="h-full rounded-full transition-all"
  5689. style={{
  5690. width: `${htEffectiveFill}%`,
  5691. backgroundColor: getFillBarColor(htEffectiveFill),
  5692. }}
  5693. />
  5694. )}
  5695. </div>
  5696. </div>
  5697. );
  5698. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5699. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5700. // Without this override, the L view squishes HT into a sliver next to the
  5701. // 4-slot AMS neighbors.
  5702. // 11rem holds one slot plus the temperature/humidity
  5703. // column beside it; both grow with the body scale.
  5704. const htCardWidth = scaledRem(11);
  5705. const htCardStyle: React.CSSProperties = {
  5706. flex: `1 1 ${htCardWidth}`,
  5707. minWidth: htCardWidth,
  5708. // An AMS-HT is never wider than a full AMS. Without a
  5709. // ceiling, a unit that wraps onto a line of its own is
  5710. // the only flex item there and grow stretches its single
  5711. // slot across the entire card, leaving the readings
  5712. // stranded at the far edge.
  5713. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5714. };
  5715. return (
  5716. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5717. {/* Row 1: Label + Nozzle + Drying */}
  5718. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5719. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5720. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5721. <AmsNameHoverCard
  5722. ams={ams}
  5723. printerId={printer.id}
  5724. label={getAmsLabel(ams.id, ams.tray.length)}
  5725. amsLabels={amsLabels}
  5726. canEdit={hasPermission('printers:update')}
  5727. onSaved={refetchAmsLabels}
  5728. >
  5729. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5730. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5731. </span>
  5732. </AmsNameHoverCard>
  5733. {sideBadge?.kind === 'inlet' ? (
  5734. <InletBadge
  5735. inlet={sideBadge.inlet}
  5736. title={t('printers.amsSwitchInletTooltip', {
  5737. inlet: sideBadge.inlet,
  5738. side: FTS_INLET_SIDE[sideBadge.inlet],
  5739. })}
  5740. />
  5741. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5742. <NozzleBadge side={sideBadge.side} />
  5743. ) : null}
  5744. </div>
  5745. {/* Drying button for HT AMS */}
  5746. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5747. <div className="relative ml-auto">
  5748. <button
  5749. disabled={status.drying_screen_only}
  5750. onClick={(e) => {
  5751. if (ams.dry_time > 0) {
  5752. stopDryingMutation.mutate(ams.id);
  5753. } else if (dryingPopoverAmsId === ams.id) {
  5754. setDryingPopoverAmsId(null);
  5755. } else {
  5756. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5757. }
  5758. }}
  5759. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5760. ams.dry_time > 0
  5761. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5762. : status.drying_screen_only
  5763. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5764. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5765. }`}
  5766. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5767. >
  5768. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5769. </button>
  5770. </div>
  5771. )}
  5772. </div>
  5773. {/* HT AMS drying status bar. Same not-running split as the
  5774. standard-AMS bar above: a frozen countdown is not a
  5775. running cycle. */}
  5776. {ams.dry_time > 0 && (
  5777. <div className={`flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg px-2 py-1 text-[length:var(--pc-t9,9px)] ${ams.dry_countdown_stalled ? 'bg-slate-100 dark:bg-slate-500/10' : 'bg-amber-50 dark:bg-amber-500/10'}`} title={ams.dry_countdown_stalled ? t('printers.drying.notRunningHint') : undefined}>
  5778. {ams.dry_countdown_stalled
  5779. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5780. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5781. {ams.dry_countdown_stalled && (
  5782. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5783. )}
  5784. {ams.dry_filament && (
  5785. <span className={`${ams.dry_countdown_stalled ? 'text-slate-500/90 dark:text-slate-400/80' : 'text-amber-700/80 dark:text-amber-300/70'} text-[length:var(--pc-t8,8px)] truncate`}>
  5786. {ams.dry_target_temp != null
  5787. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5788. : ams.dry_filament}
  5789. </span>
  5790. )}
  5791. {!ams.dry_countdown_stalled && (
  5792. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5793. {ams.dry_time >= 60
  5794. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5795. : `${ams.dry_time}m`}
  5796. </span>
  5797. )}
  5798. {!status.drying_screen_only && (
  5799. <button
  5800. onClick={() => stopDryingMutation.mutate(ams.id)}
  5801. disabled={stopDryingMutation.isPending}
  5802. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0"
  5803. title={t('printers.drying.stop')}
  5804. >
  5805. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5806. </button>
  5807. )}
  5808. </div>
  5809. )}
  5810. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5811. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5812. {/* Slot wrapper with loading overlay */}
  5813. <div className="relative group flex-1" style={htSlotStyle}>
  5814. {/* Loading overlay during RFID re-read */}
  5815. {isHtRefreshing && (
  5816. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5817. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5818. </div>
  5819. )}
  5820. {/* Hover card wraps only the visual content */}
  5821. {filamentData ? (
  5822. <FilamentHoverCard
  5823. data={filamentData}
  5824. actions={renderAmsSlotActions({
  5825. amsId: ams.id,
  5826. slotId: htSlotId,
  5827. loadTrayId: ams.id * 4 + htSlotId,
  5828. isRefreshing: isHtRefreshing,
  5829. })}
  5830. spoolman={{
  5831. enabled: spoolmanEnabled,
  5832. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5833. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5834. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5835. spoolmanUrl,
  5836. syncMode: spoolmanSyncMode,
  5837. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5838. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5839. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5840. setLinkSpoolModal({
  5841. tagUid: filamentData.tagUid || linkTag,
  5842. trayUuid: filamentData.trayUuid || '',
  5843. printerId: printer.id,
  5844. amsId: ams.id,
  5845. trayId: htSlotId,
  5846. });
  5847. } : undefined,
  5848. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5849. }}
  5850. inventory={(() => {
  5851. if (spoolmanEnabled) {
  5852. if (spoolmanLoading) return undefined;
  5853. const slotAssignment = htSlotAssignmentForFill;
  5854. const spoolmanSpool = htSlotSpoolForFill;
  5855. return {
  5856. assignedSpool: spoolmanSpool ? {
  5857. id: spoolmanSpool.id,
  5858. material: spoolmanSpool.material,
  5859. subtype: spoolmanSpool.subtype,
  5860. brand: spoolmanSpool.brand ?? null,
  5861. color_name: spoolmanSpool.color_name ?? null,
  5862. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5863. // The spool's own swatch (#2967). Spoolman carries the
  5864. // extra stops but has no effect field at all, so those
  5865. // rolls gradient and never shimmer.
  5866. rgba: spoolmanSpool.rgba ?? null,
  5867. extra_colors: spoolmanSpool.extra_colors ?? null,
  5868. effect_type: spoolmanSpool.effect_type ?? null,
  5869. remainingWeightGrams: spoolmanSpool.label_weight
  5870. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5871. : undefined,
  5872. } : null,
  5873. onAssignSpool: () => setAssignSpoolModal({
  5874. printerId: printer.id,
  5875. amsId: ams.id,
  5876. trayId: htSlotId,
  5877. trayInfo: {
  5878. type: tray?.tray_type || filamentData.profile,
  5879. material: tray?.tray_type ?? undefined,
  5880. profile: filamentData.profile,
  5881. color: filamentData.colorHex || '',
  5882. location: getAmsLabel(ams.id, ams.tray.length),
  5883. },
  5884. }),
  5885. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5886. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5887. };
  5888. }
  5889. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5890. return {
  5891. assignedSpool: assignment?.spool ? {
  5892. id: assignment.spool.id,
  5893. material: assignment.spool.material,
  5894. subtype: assignment.spool.subtype,
  5895. brand: assignment.spool.brand,
  5896. color_name: assignment.spool.color_name,
  5897. // The spool's own swatch (#2967).
  5898. rgba: assignment.spool.rgba ?? null,
  5899. extra_colors: assignment.spool.extra_colors ?? null,
  5900. effect_type: assignment.spool.effect_type ?? null,
  5901. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5902. } : null,
  5903. onAssignSpool: () => setAssignSpoolModal({
  5904. printerId: printer.id,
  5905. amsId: ams.id,
  5906. trayId: htSlotId,
  5907. trayInfo: {
  5908. type: tray?.tray_type || filamentData.profile,
  5909. material: tray?.tray_type ?? undefined,
  5910. profile: filamentData.profile,
  5911. color: filamentData.colorHex || '',
  5912. location: getAmsLabel(ams.id, ams.tray.length),
  5913. },
  5914. }),
  5915. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5916. isAssigned: !!assignment || isBambuLabSpool(tray),
  5917. };
  5918. })()}
  5919. configureSlot={{
  5920. enabled: hasPermission('printers:control'),
  5921. onConfigure: () => setConfigureSlotModal({
  5922. amsId: ams.id,
  5923. trayId: htSlotId,
  5924. trayCount: ams.tray.length,
  5925. trayType: tray?.tray_type || undefined,
  5926. trayColor: tray?.tray_color || undefined,
  5927. traySubBrands: tray?.tray_sub_brands || undefined,
  5928. trayInfoIdx: tray?.tray_info_idx || undefined,
  5929. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5930. caliIdx: tray?.cali_idx,
  5931. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5932. }),
  5933. }}
  5934. >
  5935. {slotVisual}
  5936. </FilamentHoverCard>
  5937. ) : (
  5938. <EmptySlotHoverCard
  5939. kind={emptyKind ?? undefined}
  5940. actions={renderAmsSlotActions({
  5941. amsId: ams.id,
  5942. slotId: htSlotId,
  5943. loadTrayId: ams.id * 4 + htSlotId,
  5944. isRefreshing: isHtRefreshing,
  5945. })}
  5946. configureSlot={{
  5947. enabled: hasPermission('printers:control'),
  5948. onConfigure: () => setConfigureSlotModal({
  5949. amsId: ams.id,
  5950. trayId: htSlotId,
  5951. trayCount: ams.tray.length,
  5952. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5953. }),
  5954. }}
  5955. onAssignSpool={() => setAssignSpoolModal({
  5956. printerId: printer.id,
  5957. amsId: ams.id,
  5958. trayId: htSlotId,
  5959. trayInfo: {
  5960. type: '',
  5961. material: undefined,
  5962. profile: '',
  5963. color: '',
  5964. location: getAmsLabel(ams.id, ams.tray.length),
  5965. },
  5966. })}
  5967. >
  5968. {slotVisual}
  5969. </EmptySlotHoverCard>
  5970. )}
  5971. </div>
  5972. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5973. {(ams.humidity != null || ams.temp != null) && (
  5974. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5975. {ams.temp != null && (
  5976. <TemperatureIndicator
  5977. temp={ams.temp}
  5978. goodThreshold={amsThresholds?.tempGood}
  5979. fairThreshold={amsThresholds?.tempFair}
  5980. onClick={() => setAmsHistoryModal({
  5981. amsId: ams.id,
  5982. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5983. mode: 'temperature',
  5984. })}
  5985. compact
  5986. />
  5987. )}
  5988. {ams.humidity != null && (
  5989. <HumidityIndicator
  5990. humidity={ams.humidity}
  5991. goodThreshold={amsThresholds?.humidityGood}
  5992. fairThreshold={amsThresholds?.humidityFair}
  5993. onClick={() => setAmsHistoryModal({
  5994. amsId: ams.id,
  5995. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5996. mode: 'humidity',
  5997. })}
  5998. compact
  5999. />
  6000. )}
  6001. </div>
  6002. )}
  6003. </div>
  6004. </div>
  6005. );
  6006. })}
  6007. {/* External spool(s) - grouped in one card like regular AMS */}
  6008. {status.vt_tray.length > 0 && showExternalSpool && (
  6009. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  6010. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  6011. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  6012. </div>
  6013. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  6014. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  6015. const extTrayId = extTray.id ?? 254;
  6016. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  6017. // generically — use active_extruder to determine L vs R:
  6018. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  6019. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  6020. ? (extTrayId === 254 && status.active_extruder === 1) ||
  6021. (extTrayId === 255 && status.active_extruder === 0)
  6022. : effectiveTrayNow === extTrayId;
  6023. const slotTrayId = extTrayId - 254; // 0 or 1
  6024. const extLabel = isDualNozzle
  6025. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6026. : '';
  6027. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6028. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6029. // Only trusted while it still describes what the printer reports in the
  6030. // slot: the row survives a spool swap, and the display chain below puts
  6031. // it ahead of the live filament id (see slotPresetDescribesTray).
  6032. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx)
  6033. ? extSlotPreset?.preset_name
  6034. : undefined;
  6035. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6036. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6037. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6038. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6039. const extInventoryFill = (() => {
  6040. const sp = extInventoryAssignment?.spool;
  6041. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6042. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6043. }
  6044. return null;
  6045. })();
  6046. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6047. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6048. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6049. ? null : extInventoryFill;
  6050. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6051. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6052. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6053. : undefined;
  6054. const extSlotSpoolForFill = extSlotAssignmentForFill
  6055. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6056. : undefined;
  6057. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6058. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6059. : null;
  6060. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6061. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6062. : extResolvedInventoryFill !== null ? 'inventory' as const
  6063. : extHasFillLevel ? 'ams' as const
  6064. : undefined;
  6065. const extFilamentData = {
  6066. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6067. profile: extSlotPresetName || (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',
  6068. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6069. colorHex: extTray.tray_color || null,
  6070. kFactor: formatKValue(extTray.k),
  6071. fillLevel: extEffectiveFill,
  6072. trayUuid: extTray.tray_uuid || null,
  6073. tagUid: extTray.tag_uid || null,
  6074. fillSource: extFillSource,
  6075. };
  6076. const isEmpty = !extTray.tray_type;
  6077. const emptyKind = getEmptySlotKind(extTray);
  6078. const extSlotContent = (
  6079. <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' : ''}`}>
  6080. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6081. the separate Ext-L/Ext-R caption that made the row taller than
  6082. regular AMS slots), 1-based slot number on single-nozzle. */}
  6083. <FilamentSlotCircle
  6084. trayColor={extTray.tray_color}
  6085. trayType={extTray.tray_type}
  6086. isEmpty={isEmpty}
  6087. emptyKind={emptyKind}
  6088. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6089. />
  6090. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6091. {extTray.tray_type || t('ams.slotEmpty')}
  6092. </div>
  6093. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6094. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6095. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6096. <div
  6097. className="h-full rounded-full transition-all"
  6098. style={{
  6099. width: `${extEffectiveFill}%`,
  6100. backgroundColor: getFillBarColor(extEffectiveFill),
  6101. }}
  6102. />
  6103. )}
  6104. </div>
  6105. </div>
  6106. );
  6107. return (
  6108. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6109. {!isEmpty ? (
  6110. <FilamentHoverCard
  6111. data={extFilamentData}
  6112. actions={renderAmsSlotActions({
  6113. amsId: 255,
  6114. slotId: slotTrayId,
  6115. loadTrayId: extTrayId,
  6116. includeRfid: false,
  6117. })}
  6118. spoolman={{
  6119. enabled: spoolmanEnabled,
  6120. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6121. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6122. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6123. spoolmanUrl,
  6124. syncMode: spoolmanSyncMode,
  6125. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6126. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6127. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6128. setLinkSpoolModal({
  6129. tagUid: extFilamentData.tagUid || linkTag,
  6130. trayUuid: extFilamentData.trayUuid || '',
  6131. printerId: printer.id,
  6132. amsId: 255,
  6133. trayId: slotTrayId,
  6134. });
  6135. } : undefined,
  6136. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6137. }}
  6138. inventory={(() => {
  6139. if (spoolmanEnabled) {
  6140. if (spoolmanLoading) return undefined;
  6141. const slotAssignment = extSlotAssignmentForFill;
  6142. const spoolmanSpool = extSlotSpoolForFill;
  6143. return {
  6144. assignedSpool: spoolmanSpool ? {
  6145. id: spoolmanSpool.id,
  6146. material: spoolmanSpool.material,
  6147. subtype: spoolmanSpool.subtype,
  6148. brand: spoolmanSpool.brand ?? null,
  6149. color_name: spoolmanSpool.color_name ?? null,
  6150. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6151. // The spool's own swatch (#2967). Spoolman carries the
  6152. // extra stops but has no effect field at all, so those
  6153. // rolls gradient and never shimmer.
  6154. rgba: spoolmanSpool.rgba ?? null,
  6155. extra_colors: spoolmanSpool.extra_colors ?? null,
  6156. effect_type: spoolmanSpool.effect_type ?? null,
  6157. remainingWeightGrams: spoolmanSpool.label_weight
  6158. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6159. : undefined,
  6160. } : null,
  6161. onAssignSpool: () => setAssignSpoolModal({
  6162. printerId: printer.id,
  6163. amsId: 255,
  6164. trayId: slotTrayId,
  6165. trayInfo: {
  6166. type: extTray.tray_type || extFilamentData.profile,
  6167. material: extTray.tray_type ?? undefined,
  6168. profile: extFilamentData.profile,
  6169. color: extFilamentData.colorHex || '',
  6170. location: extLabel || t('printers.external'),
  6171. },
  6172. }),
  6173. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6174. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6175. };
  6176. }
  6177. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6178. return {
  6179. assignedSpool: assignment?.spool ? {
  6180. id: assignment.spool.id,
  6181. material: assignment.spool.material,
  6182. subtype: assignment.spool.subtype,
  6183. brand: assignment.spool.brand,
  6184. color_name: assignment.spool.color_name,
  6185. // The spool's own swatch (#2967).
  6186. rgba: assignment.spool.rgba ?? null,
  6187. extra_colors: assignment.spool.extra_colors ?? null,
  6188. effect_type: assignment.spool.effect_type ?? null,
  6189. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6190. } : null,
  6191. onAssignSpool: () => setAssignSpoolModal({
  6192. printerId: printer.id,
  6193. amsId: 255,
  6194. trayId: slotTrayId,
  6195. trayInfo: {
  6196. type: extTray.tray_type || extFilamentData.profile,
  6197. material: extTray.tray_type ?? undefined,
  6198. profile: extFilamentData.profile,
  6199. color: extFilamentData.colorHex || '',
  6200. location: extLabel || t('printers.external'),
  6201. },
  6202. }),
  6203. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6204. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6205. };
  6206. })()}
  6207. configureSlot={{
  6208. enabled: hasPermission('printers:control'),
  6209. onConfigure: () => setConfigureSlotModal({
  6210. amsId: 255,
  6211. trayId: slotTrayId,
  6212. trayCount: 1,
  6213. trayType: extTray.tray_type || undefined,
  6214. trayColor: extTray.tray_color || undefined,
  6215. traySubBrands: extTray.tray_sub_brands || undefined,
  6216. trayInfoIdx: extTray.tray_info_idx || undefined,
  6217. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6218. caliIdx: extTray.cali_idx,
  6219. savedPresetId: slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx) ? extSlotPreset?.preset_id : undefined,
  6220. }),
  6221. }}
  6222. >
  6223. {extSlotContent}
  6224. </FilamentHoverCard>
  6225. ) : (
  6226. <EmptySlotHoverCard
  6227. kind={emptyKind ?? undefined}
  6228. actions={renderAmsSlotActions({
  6229. amsId: 255,
  6230. slotId: slotTrayId,
  6231. loadTrayId: extTrayId,
  6232. includeRfid: false,
  6233. })}
  6234. configureSlot={{
  6235. enabled: hasPermission('printers:control'),
  6236. onConfigure: () => setConfigureSlotModal({
  6237. amsId: 255,
  6238. trayId: slotTrayId,
  6239. trayCount: 1,
  6240. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6241. }),
  6242. }}
  6243. onAssignSpool={() => setAssignSpoolModal({
  6244. printerId: printer.id,
  6245. amsId: 255,
  6246. trayId: slotTrayId,
  6247. trayInfo: {
  6248. type: '',
  6249. material: undefined,
  6250. profile: '',
  6251. color: '',
  6252. location: `External Slot ${slotTrayId + 1}`,
  6253. },
  6254. })}
  6255. >
  6256. {extSlotContent}
  6257. </EmptySlotHoverCard>
  6258. )}
  6259. </div>
  6260. );
  6261. })}
  6262. </div>
  6263. </div>
  6264. )}
  6265. </div>
  6266. </div>
  6267. );
  6268. })()}
  6269. </>
  6270. )}
  6271. {/* Powered-down printer with a dirty plate: the status block above renders
  6272. nothing without a live connection, so the plate-clear control gets its own
  6273. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6274. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6275. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6276. expandedClearPlateButton
  6277. )}
  6278. {/* Bottom block (power row + action bar). Wrapped together so the
  6279. power row hugs the action bar at the card bottom instead of
  6280. floating up when there's less filament content above. */}
  6281. {viewMode === 'expanded' && (
  6282. <div className="mt-auto">
  6283. {smartPlug && (
  6284. <div className="pt-3">
  6285. <div className="flex items-center gap-2 mb-2">
  6286. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6287. {t('printers.power', 'Power')}
  6288. </span>
  6289. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6290. </div>
  6291. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6292. {/* Plug name + current power */}
  6293. <div className="flex items-center gap-2 min-w-0 pl-1">
  6294. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6295. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6296. <span
  6297. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[length:var(--pc-t10,10px)] font-medium flex-shrink-0"
  6298. title={t('smartPlugs.power')}
  6299. >
  6300. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6301. </span>
  6302. </div>
  6303. {/* Spacer */}
  6304. <div className="flex-1" />
  6305. <div className="flex items-center gap-2">
  6306. {/* Auto-off */}
  6307. <button
  6308. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6309. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6310. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6311. 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 ${
  6312. !hasPermission('smart_plugs:control')
  6313. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6314. : smartPlug.auto_off || smartPlug.auto_off_executed
  6315. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6316. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6317. }`}
  6318. >
  6319. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6320. </button>
  6321. <button
  6322. onClick={() => {
  6323. if (plugStatus?.state === 'ON') {
  6324. setShowPowerOffConfirm(true);
  6325. } else {
  6326. setShowPowerOnConfirm(true);
  6327. }
  6328. }}
  6329. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6330. 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 ${
  6331. !hasPermission('smart_plugs:control')
  6332. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6333. : plugStatus?.state === 'ON'
  6334. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6335. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6336. }`}
  6337. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6338. >
  6339. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6340. </button>
  6341. </div>
  6342. </div>
  6343. {/* HA entity buttons row */}
  6344. {scriptPlugs && scriptPlugs.length > 0 && (
  6345. <div className="flex items-center gap-2 mt-2">
  6346. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6347. <span className="text-xs text-bambu-gray">HA:</span>
  6348. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6349. <div className="flex flex-wrap gap-1">
  6350. {scriptPlugs.map(script => {
  6351. const isScript = script.ha_entity_id?.startsWith('script.');
  6352. return (
  6353. <button
  6354. key={script.id}
  6355. onClick={() => {
  6356. if (isScript) {
  6357. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6358. } else {
  6359. setHaToggleConfirm(script);
  6360. }
  6361. }}
  6362. disabled={runScriptMutation.isPending}
  6363. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6364. className="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1"
  6365. >
  6366. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6367. {script.name}
  6368. </button>
  6369. );
  6370. })}
  6371. </div>
  6372. </div>
  6373. )}
  6374. </div>
  6375. )}
  6376. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6377. a printer can have an enclosure door contact without having a plug,
  6378. and nesting it there would hide the row on exactly those setups. */}
  6379. <PrinterHASensorRow printerId={printer.id} />
  6380. {/* Connection Info & Actions */}
  6381. <div className="pt-4">
  6382. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6383. <div className="flex items-center justify-between gap-2">
  6384. {printerActionsMenu}
  6385. <div className="flex items-center justify-end gap-2 flex-wrap">
  6386. {/* Camera split button: the icon opens whichever view was used
  6387. last, the caret picks between the two and remembers it.
  6388. Replaces the old Settings > General > Camera switch, which
  6389. made choosing between an overlay and a window a trip to
  6390. another page for something you decide per camera. */}
  6391. <div className="flex items-center flex-shrink-0">
  6392. <Button
  6393. variant="secondary"
  6394. size="sm"
  6395. onClick={() => openCameraIn(cameraViewMode)}
  6396. disabled={!status?.connected || !hasPermission('camera:view')}
  6397. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6398. className={`${footerIconButtonClass} !rounded-r-none`}
  6399. >
  6400. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6401. </Button>
  6402. <Button
  6403. variant="secondary"
  6404. size="sm"
  6405. onClick={(e) => {
  6406. // No open/close toggle: the menu's own outside-mousedown
  6407. // handler has already dismissed it by the time this lands.
  6408. const rect = e.currentTarget.getBoundingClientRect();
  6409. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6410. }}
  6411. disabled={!status?.connected || !hasPermission('camera:view')}
  6412. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6413. aria-label={t('settings.cameraViewMode')}
  6414. // Not footerIconButtonClass plus an override: both widths
  6415. // would carry !important and the stylesheet's own order,
  6416. // not this one, would decide which won.
  6417. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6418. >
  6419. <ChevronDown className="w-3 h-3" />
  6420. </Button>
  6421. </div>
  6422. {cameraMenuAnchor && (
  6423. <ContextMenu
  6424. x={cameraMenuAnchor.x}
  6425. y={cameraMenuAnchor.y}
  6426. items={cameraViewModeMenuItems}
  6427. onClose={() => setCameraMenuAnchor(null)}
  6428. />
  6429. )}
  6430. <Button
  6431. variant="secondary"
  6432. size="sm"
  6433. onClick={() => setShowFileManager(true)}
  6434. disabled={!hasPermission('printers:files')}
  6435. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6436. className={footerIconButtonClass}
  6437. >
  6438. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6439. </Button>
  6440. {/* Shown whatever the printer is doing (#2849): this uploads a
  6441. file and queues it, which a busy or offline printer is no
  6442. reason to refuse -- it only means the item waits. Hiding it
  6443. while the drop zone accepted the same file would have left
  6444. the two routes into this flow disagreeing. */}
  6445. <Button
  6446. size="sm"
  6447. onClick={() => setShowUploadForPrint(true)}
  6448. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6449. title={
  6450. !hasPermission('library:upload')
  6451. ? t('fileManager.noPermissionUpload')
  6452. : !hasPermission('queue:create')
  6453. ? t('fileManager.noPermissionAddToQueue')
  6454. : t('common.print')
  6455. }
  6456. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6457. >
  6458. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6459. {t('common.print')}
  6460. </Button>
  6461. </div>
  6462. </div>
  6463. </div>
  6464. </div>
  6465. )}
  6466. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6467. card's horizontal padding instead of running full-bleed into the
  6468. rounded bottom edge. */}
  6469. <ScheduledDryingBanner
  6470. printerId={printer.id}
  6471. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6472. timeFormat={timeFormat}
  6473. />
  6474. </CardContent>
  6475. {/* File Manager Modal */}
  6476. {showFileManager && (
  6477. <FileManagerModal
  6478. printerId={printer.id}
  6479. printerName={printer.name}
  6480. onClose={() => setShowFileManager(false)}
  6481. />
  6482. )}
  6483. {/* Upload for Print Modal */}
  6484. {showUploadForPrint && (
  6485. <FileUploadModal
  6486. folderId={null}
  6487. onClose={() => setShowUploadForPrint(false)}
  6488. onUploadComplete={() => {}}
  6489. autoUpload
  6490. accept=".gcode,.3mf"
  6491. validateFile={(file) => {
  6492. const lower = file.name.toLowerCase();
  6493. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6494. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6495. }
  6496. }}
  6497. onFileUploaded={(uploadedFile) => {
  6498. // Check printer compatibility if sliced_for_model is available in metadata
  6499. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6500. const printerModel = mapModelCode(printer.model);
  6501. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6502. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6503. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6504. }
  6505. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6506. }}
  6507. />
  6508. )}
  6509. {/* Print Modal (after upload) */}
  6510. {printAfterUpload && (
  6511. <PrintModal
  6512. mode="create"
  6513. libraryFileId={printAfterUpload.id}
  6514. archiveName={printAfterUpload.filename}
  6515. initialSelectedPrinterIds={[printer.id]}
  6516. onClose={() => setPrintAfterUpload(null)}
  6517. onSuccess={() => setPrintAfterUpload(null)}
  6518. cleanupLibraryAfterDispatch
  6519. />
  6520. )}
  6521. {/* MQTT Debug Modal */}
  6522. {showMQTTDebug && (
  6523. <MQTTDebugModal
  6524. printerId={printer.id}
  6525. printerName={printer.name}
  6526. onClose={() => setShowMQTTDebug(false)}
  6527. />
  6528. )}
  6529. {showDiagnostic && (
  6530. <ConnectionDiagnosticModal
  6531. printerId={printer.id}
  6532. printerName={printer.name}
  6533. onClose={() => setShowDiagnostic(false)}
  6534. />
  6535. )}
  6536. {showPrinterInfo && (
  6537. <PrinterInfoModal
  6538. printer={printer}
  6539. status={status}
  6540. totalPrintHours={maintenanceInfo?.total_print_hours}
  6541. onClose={closePrinterInfo}
  6542. />
  6543. )}
  6544. {/* Plate Check Result Modal */}
  6545. {plateCheckResult && (
  6546. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6547. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6548. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6549. <div className="flex items-center gap-2">
  6550. {plateCheckResult.needs_calibration ? (
  6551. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6552. ) : plateCheckResult.is_empty ? (
  6553. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6554. ) : (
  6555. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6556. )}
  6557. <h2 className="text-lg font-semibold text-white">
  6558. Build Plate Check
  6559. </h2>
  6560. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6561. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6562. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6563. </span>
  6564. )}
  6565. </div>
  6566. <button
  6567. onClick={() => closePlateCheckModal()}
  6568. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6569. >
  6570. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6571. </button>
  6572. </div>
  6573. <div className="p-4 space-y-4">
  6574. {plateCheckResult.needs_calibration ? (
  6575. <>
  6576. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6577. <p className="font-medium text-blue-700 dark:text-blue-400">
  6578. {t('printers.plateDetection.calibrationRequired')}
  6579. </p>
  6580. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6581. </div>
  6582. <div className="text-sm text-bambu-gray space-y-2">
  6583. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6584. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6585. </div>
  6586. </>
  6587. ) : (
  6588. <>
  6589. <div className={`p-3 rounded-lg ${plateCheckResult.is_empty ? 'bg-green-100 dark:bg-green-500/20 border border-green-300 dark:border-green-500/50' : 'bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-300 dark:border-yellow-500/50'}`}>
  6590. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6591. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6592. </p>
  6593. <p className="text-sm text-bambu-gray mt-1">
  6594. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6595. </p>
  6596. </div>
  6597. {plateCheckResult.debug_image_url && (
  6598. <div>
  6599. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6600. <img
  6601. src={plateCheckResult.debug_image_url}
  6602. alt={t('printers.plateDetection.analysisPreview')}
  6603. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6604. />
  6605. <p className="text-xs text-bambu-gray mt-2">
  6606. {t('printers.plateDetection.analysisLegend')}
  6607. </p>
  6608. </div>
  6609. )}
  6610. <p className="text-xs text-bambu-gray">
  6611. {plateCheckResult.message}
  6612. </p>
  6613. </>
  6614. )}
  6615. {/* Saved References Grid */}
  6616. {plateReferences && plateReferences.references.length > 0 && (
  6617. <div className="mt-4">
  6618. <div className="flex items-center gap-2 mb-2">
  6619. <p className="text-sm font-medium text-white shrink-0">
  6620. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6621. </p>
  6622. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6623. </div>
  6624. <div className="grid grid-cols-5 gap-2">
  6625. {plateReferences.references.map((ref) => (
  6626. <div key={ref.index} className="relative group">
  6627. <img
  6628. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6629. alt={ref.label || `Reference ${ref.index + 1}`}
  6630. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6631. />
  6632. {/* Delete button */}
  6633. <button
  6634. onClick={() => handleDeleteRef(ref.index)}
  6635. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded can-hover:opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
  6636. title={t('printers.plateDetection.deleteReference')}
  6637. >
  6638. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6639. </button>
  6640. {/* Label */}
  6641. {editingRefLabel?.index === ref.index ? (
  6642. <input
  6643. type="text"
  6644. value={editingRefLabel.label}
  6645. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6646. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6647. onKeyDown={(e) => {
  6648. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6649. if (e.key === 'Escape') setEditingRefLabel(null);
  6650. }}
  6651. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6652. autoFocus
  6653. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6654. />
  6655. ) : (
  6656. <p
  6657. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6658. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6659. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6660. >
  6661. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6662. </p>
  6663. )}
  6664. {/* Timestamp */}
  6665. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6666. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6667. </p>
  6668. </div>
  6669. ))}
  6670. </div>
  6671. </div>
  6672. )}
  6673. {/* ROI Editor */}
  6674. {!plateCheckResult.needs_calibration && (
  6675. <div className="mt-4">
  6676. <div className="flex items-center justify-between mb-2">
  6677. <div className="flex min-w-0 flex-1 items-center gap-2">
  6678. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6679. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6680. </div>
  6681. {!editingRoi ? (
  6682. <Button
  6683. variant="ghost"
  6684. size="sm"
  6685. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6686. >
  6687. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6688. {t('common.edit')}
  6689. </Button>
  6690. ) : (
  6691. <div className="flex gap-1">
  6692. <Button
  6693. variant="ghost"
  6694. size="sm"
  6695. onClick={() => setEditingRoi(null)}
  6696. disabled={isSavingRoi}
  6697. >
  6698. {t('common.cancel')}
  6699. </Button>
  6700. <Button
  6701. size="sm"
  6702. onClick={handleSaveRoi}
  6703. disabled={isSavingRoi}
  6704. >
  6705. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6706. </Button>
  6707. </div>
  6708. )}
  6709. </div>
  6710. {editingRoi ? (
  6711. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6712. <div className="grid grid-cols-2 gap-3">
  6713. <div>
  6714. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6715. <input
  6716. type="range"
  6717. min="0"
  6718. max="0.9"
  6719. step="0.01"
  6720. value={editingRoi.x}
  6721. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6722. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6723. />
  6724. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6725. </div>
  6726. <div>
  6727. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6728. <input
  6729. type="range"
  6730. min="0"
  6731. max="0.9"
  6732. step="0.01"
  6733. value={editingRoi.y}
  6734. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6735. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6736. />
  6737. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6738. </div>
  6739. <div>
  6740. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6741. <input
  6742. type="range"
  6743. min="0.1"
  6744. max="1"
  6745. step="0.01"
  6746. value={editingRoi.w}
  6747. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6748. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6749. />
  6750. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6751. </div>
  6752. <div>
  6753. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6754. <input
  6755. type="range"
  6756. min="0.1"
  6757. max="1"
  6758. step="0.01"
  6759. value={editingRoi.h}
  6760. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6761. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6762. />
  6763. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6764. </div>
  6765. </div>
  6766. <p className="text-xs text-bambu-gray">
  6767. {t('printers.roi.instruction')}
  6768. </p>
  6769. </div>
  6770. ) : (
  6771. <p className="text-xs text-bambu-gray">
  6772. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6773. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6774. </p>
  6775. )}
  6776. </div>
  6777. )}
  6778. </div>
  6779. <div className="flex justify-end gap-2 p-4">
  6780. {plateCheckResult.needs_calibration ? (
  6781. <>
  6782. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6783. {t('common.cancel')}
  6784. </Button>
  6785. <Button
  6786. onClick={() => handleCalibratePlate()}
  6787. disabled={isCalibrating}
  6788. >
  6789. {isCalibrating ? (
  6790. <>
  6791. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6792. Calibrating...
  6793. </>
  6794. ) : (
  6795. 'Calibrate Empty Plate'
  6796. )}
  6797. </Button>
  6798. </>
  6799. ) : (
  6800. <>
  6801. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6802. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6803. </Button>
  6804. <Button onClick={() => closePlateCheckModal()}>
  6805. Close
  6806. </Button>
  6807. </>
  6808. )}
  6809. </div>
  6810. </div>
  6811. </div>
  6812. )}
  6813. {/* Power On Confirmation */}
  6814. {showPowerOnConfirm && smartPlug && (
  6815. <ConfirmModal
  6816. title={t('printers.confirm.powerOnTitle')}
  6817. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6818. confirmText={t('printers.confirm.powerOnButton')}
  6819. variant="default"
  6820. onConfirm={() => {
  6821. powerControlMutation.mutate('on');
  6822. setShowPowerOnConfirm(false);
  6823. }}
  6824. onCancel={() => setShowPowerOnConfirm(false)}
  6825. />
  6826. )}
  6827. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6828. disconnects MQTT, which stops progress tracking + completion
  6829. notifications for the in-flight job. Idle / FINISH / FAILED states
  6830. skip this dialog and toggle directly. */}
  6831. {confirmMaintenanceEnter && (
  6832. <ConfirmModal
  6833. title={t('printers.maintenance.confirmMidPrintTitle')}
  6834. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6835. confirmText={t('printers.maintenance.menuEnter')}
  6836. variant="danger"
  6837. onConfirm={() => {
  6838. maintenanceMutation.mutate(false);
  6839. setConfirmMaintenanceEnter(false);
  6840. }}
  6841. onCancel={() => setConfirmMaintenanceEnter(false)}
  6842. />
  6843. )}
  6844. {/* Power Off Confirmation */}
  6845. {showPowerOffConfirm && smartPlug && (
  6846. <ConfirmModal
  6847. title={t('printers.confirm.powerOffTitle')}
  6848. message={
  6849. status?.state === 'RUNNING'
  6850. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6851. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6852. }
  6853. confirmText={t('printers.confirm.powerOffButton')}
  6854. variant="danger"
  6855. onConfirm={() => {
  6856. powerControlMutation.mutate('off');
  6857. setShowPowerOffConfirm(false);
  6858. }}
  6859. onCancel={() => setShowPowerOffConfirm(false)}
  6860. />
  6861. )}
  6862. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6863. {haToggleConfirm && (
  6864. <ConfirmModal
  6865. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6866. message={
  6867. status?.state === 'RUNNING'
  6868. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6869. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6870. }
  6871. confirmText={t('printers.confirm.haToggleButton')}
  6872. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6873. onConfirm={() => {
  6874. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6875. setHaToggleConfirm(null);
  6876. }}
  6877. onCancel={() => setHaToggleConfirm(null)}
  6878. />
  6879. )}
  6880. {/* Stop Print Confirmation */}
  6881. {showStopConfirm && (
  6882. <ConfirmModal
  6883. title={t('printers.confirm.stopTitle')}
  6884. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6885. confirmText={t('printers.confirm.stopButton')}
  6886. variant="danger"
  6887. onConfirm={() => {
  6888. stopPrintMutation.mutate();
  6889. setShowStopConfirm(false);
  6890. }}
  6891. onCancel={() => setShowStopConfirm(false)}
  6892. />
  6893. )}
  6894. {/* Pause Print Confirmation */}
  6895. {showPauseConfirm && (
  6896. <ConfirmModal
  6897. title={t('printers.confirm.pauseTitle')}
  6898. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6899. confirmText={t('printers.confirm.pauseButton')}
  6900. variant="default"
  6901. onConfirm={() => {
  6902. pausePrintMutation.mutate();
  6903. setShowPauseConfirm(false);
  6904. }}
  6905. onCancel={() => setShowPauseConfirm(false)}
  6906. />
  6907. )}
  6908. {/* Resume Print Confirmation */}
  6909. {showResumeConfirm && (
  6910. <ConfirmModal
  6911. title={t('printers.confirm.resumeTitle')}
  6912. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6913. confirmText={t('printers.confirm.resumeButton')}
  6914. variant="default"
  6915. onConfirm={() => {
  6916. resumePrintMutation.mutate();
  6917. setShowResumeConfirm(false);
  6918. }}
  6919. onCancel={() => setShowResumeConfirm(false)}
  6920. />
  6921. )}
  6922. {/* Skip Objects Modal */}
  6923. <SkipObjectsModal
  6924. printerId={printer.id}
  6925. isOpen={showSkipObjectsModal}
  6926. onClose={() => setShowSkipObjectsModal(false)}
  6927. />
  6928. {/* HMS Error Modal */}
  6929. {showHMSModal && (
  6930. <HMSErrorModal
  6931. printerName={printer.name}
  6932. errors={status?.hms_errors || []}
  6933. onClose={() => setShowHMSModal(false)}
  6934. printerId={printer.id}
  6935. hasPermission={hasPermission}
  6936. runoutGuidance={runoutGuidance}
  6937. />
  6938. )}
  6939. {/* AI failure detection modal (#1546) */}
  6940. {showAiModal && (
  6941. <AiDetectionModal
  6942. printerName={printer.name}
  6943. detection={aiDetection}
  6944. lastError={aiLastError}
  6945. onClose={() => setShowAiModal(false)}
  6946. />
  6947. )}
  6948. {/* AMS Filament Backup status / control modal (#1762) */}
  6949. {amsBackupModalOpen && status && (
  6950. <AmsBackupModal
  6951. isOpen={amsBackupModalOpen}
  6952. state={status.ams_filament_backup}
  6953. amsUnits={status.ams}
  6954. amsExtruderMap={status.ams_extruder_map}
  6955. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6956. canToggle={hasPermission('printers:control')}
  6957. pending={setAmsBackupMutation.isPending}
  6958. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6959. onClose={() => setAmsBackupModalOpen(false)}
  6960. />
  6961. )}
  6962. {/* AMS History Modal */}
  6963. {amsHistoryModal && (
  6964. <AMSHistoryModal
  6965. isOpen={!!amsHistoryModal}
  6966. onClose={() => setAmsHistoryModal(null)}
  6967. printerId={printer.id}
  6968. printerName={printer.name}
  6969. amsId={amsHistoryModal.amsId}
  6970. amsLabel={amsHistoryModal.amsLabel}
  6971. initialMode={amsHistoryModal.mode}
  6972. thresholds={amsThresholds}
  6973. />
  6974. )}
  6975. {/* Heater History Modal (nozzle / bed / chamber) */}
  6976. {heaterHistoryModal && (
  6977. <HeaterHistoryModal
  6978. isOpen={!!heaterHistoryModal}
  6979. onClose={() => setHeaterHistoryModal(null)}
  6980. printerId={printer.id}
  6981. printerName={printer.name}
  6982. initialKind={heaterHistoryModal.initialKind}
  6983. availableKinds={heaterHistoryModal.availableKinds}
  6984. />
  6985. )}
  6986. {/* Link Spool Modal */}
  6987. {linkSpoolModal && (
  6988. <LinkSpoolModal
  6989. isOpen={!!linkSpoolModal}
  6990. onClose={() => setLinkSpoolModal(null)}
  6991. tagUid={linkSpoolModal.tagUid}
  6992. trayUuid={linkSpoolModal.trayUuid}
  6993. printerId={linkSpoolModal.printerId}
  6994. amsId={linkSpoolModal.amsId}
  6995. trayId={linkSpoolModal.trayId}
  6996. />
  6997. )}
  6998. {/* Assign Spool Modal */}
  6999. {assignSpoolModal && (
  7000. <AssignSpoolModal
  7001. isOpen={!!assignSpoolModal}
  7002. onClose={() => setAssignSpoolModal(null)}
  7003. printerId={assignSpoolModal.printerId}
  7004. amsId={assignSpoolModal.amsId}
  7005. trayId={assignSpoolModal.trayId}
  7006. trayInfo={assignSpoolModal.trayInfo}
  7007. spoolmanEnabled={!!spoolmanEnabled}
  7008. />
  7009. )}
  7010. {/* Configure AMS Slot Modal */}
  7011. {configureSlotModal && (
  7012. <ConfigureAmsSlotModal
  7013. isOpen={!!configureSlotModal}
  7014. onClose={() => setConfigureSlotModal(null)}
  7015. printerId={printer.id}
  7016. slotInfo={configureSlotModal}
  7017. printerModel={mapModelCode(printer.model) || undefined}
  7018. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  7019. onSuccess={() => {
  7020. // Refresh slot presets to show updated profile name
  7021. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7022. // Printer status will update automatically via WebSocket when AMS data changes
  7023. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7024. }}
  7025. />
  7026. )}
  7027. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7028. {feedDirectionRequest && (
  7029. <FeedDirectionModal
  7030. slotLabel={feedDirectionRequest.slotLabel}
  7031. amsId={feedDirectionRequest.amsId}
  7032. slotId={feedDirectionRequest.slotId}
  7033. extruderSlots={status?.extruder_slots ?? {}}
  7034. isLoading={loadAmsTrayMutation.isPending}
  7035. onConfirm={(extruderId) =>
  7036. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7037. }
  7038. onCancel={() => setFeedDirectionRequest(null)}
  7039. />
  7040. )}
  7041. {/* Edit Printer Modal */}
  7042. {showEditModal && (
  7043. <EditPrinterModal
  7044. printer={printer}
  7045. onClose={() => setShowEditModal(false)}
  7046. />
  7047. )}
  7048. {/* Firmware Update Modal */}
  7049. {showFirmwareModal && firmwareInfo && (
  7050. <FirmwareUpdateModal
  7051. printer={printer}
  7052. firmwareInfo={firmwareInfo}
  7053. onClose={() => setShowFirmwareModal(false)}
  7054. />
  7055. )}
  7056. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7057. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7058. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7059. const sliderMin = 35;
  7060. const sliderMax = maxTemp + 10;
  7061. return (
  7062. <>
  7063. {/* Backdrop */}
  7064. <div
  7065. className="fixed inset-0 z-[100]"
  7066. data-testid="drying-popover-backdrop"
  7067. onMouseDown={() => {
  7068. // The click that dismisses the native datetime picker lands
  7069. // here; it must not close the popover. The input is still
  7070. // focused at mousedown, so remember that and swallow the
  7071. // matching click.
  7072. dryingBackdropSkipCloseRef.current =
  7073. dryingAtTimeInputRef.current !== null &&
  7074. document.activeElement === dryingAtTimeInputRef.current;
  7075. }}
  7076. onClick={() => {
  7077. if (dryingBackdropSkipCloseRef.current) {
  7078. dryingBackdropSkipCloseRef.current = false;
  7079. return;
  7080. }
  7081. setDryingPopoverAmsId(null);
  7082. }}
  7083. />
  7084. {/* An 'above' popover is anchored by its bottom edge (CSS
  7085. bottom) so late-appearing content grows it upward, staying on
  7086. screen and glued to the trigger. maxHeight caps to the space
  7087. on the anchored side; when the viewport is too short the body
  7088. scrolls and the footer stays pinned. dvh so iOS Safari's
  7089. bottom toolbar doesn't clip the footer. */}
  7090. <div
  7091. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7092. style={{
  7093. left: dryingPopoverPos.left,
  7094. ...(dryingPopoverPos.placement === 'above'
  7095. ? {
  7096. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7097. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7098. }
  7099. : {
  7100. top: dryingPopoverPos.top,
  7101. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7102. }),
  7103. }}
  7104. onClick={e => e.stopPropagation()}
  7105. >
  7106. {/* Header */}
  7107. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7108. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7109. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7110. </div>
  7111. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7112. {/* Body */}
  7113. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7114. {/* Filament type select */}
  7115. <div>
  7116. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7117. <ToolbarDropdown
  7118. value={dryingFilament}
  7119. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7120. onChange={fil => {
  7121. setDryingFilament(fil);
  7122. const preset = dryingPresets[fil];
  7123. if (preset) {
  7124. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7125. setDryingTemp(preset[key]);
  7126. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7127. }
  7128. }}
  7129. fullWidth
  7130. />
  7131. </div>
  7132. {/* Temperature */}
  7133. <div>
  7134. <div className="flex items-center justify-between mb-1">
  7135. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7136. <div className="flex items-center gap-1">
  7137. <NumberInput
  7138. min={45}
  7139. max={maxTemp}
  7140. value={dryingTemp}
  7141. onChange={setDryingTemp}
  7142. fallback={45}
  7143. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  7144. />
  7145. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7146. </div>
  7147. </div>
  7148. <input
  7149. type="range"
  7150. min={sliderMin}
  7151. max={sliderMax}
  7152. value={dryingTemp}
  7153. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7154. className="w-full h-1 accent-bambu-green cursor-pointer"
  7155. />
  7156. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7157. <span>45°C</span>
  7158. <span>{maxTemp}°C</span>
  7159. </div>
  7160. </div>
  7161. {/* Duration */}
  7162. <div>
  7163. <div className="flex items-center justify-between mb-1">
  7164. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7165. <div className="flex items-center gap-1">
  7166. <NumberInput
  7167. min={1}
  7168. max={24}
  7169. value={dryingDuration}
  7170. onChange={setDryingDuration}
  7171. fallback={1}
  7172. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  7173. />
  7174. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7175. </div>
  7176. </div>
  7177. <input
  7178. type="range"
  7179. min={1}
  7180. max={24}
  7181. value={dryingDuration}
  7182. onChange={e => setDryingDuration(Number(e.target.value))}
  7183. className="w-full h-1 accent-bambu-green cursor-pointer"
  7184. />
  7185. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7186. <span>1h</span>
  7187. <span>24h</span>
  7188. </div>
  7189. </div>
  7190. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7191. filament threaded out into the feed tube. The whole AMS
  7192. rotates as one mechanism (all 4 spools turn together), so a
  7193. single loaded slot locks the entire unit. Bambu per-tray
  7194. `state`: 9 = empty, 10 = spool present but not loaded
  7195. (rotation possible), 11 = loaded into tube (rotation impossible).
  7196. Catches both mid-print (active feed) AND idle-with-threaded-
  7197. filament — the H2D's post-print state leaves filament in the
  7198. tube but tray_now resets to 255, which a tray_now-only check
  7199. would silently miss. */}
  7200. {(() => {
  7201. const targetAms = dryingPopoverAmsId !== null
  7202. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7203. : undefined;
  7204. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7205. tray => tray.state === 11,
  7206. );
  7207. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7208. return (
  7209. <button
  7210. type="button"
  7211. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7212. aria-pressed={rotateChecked}
  7213. disabled={trayLoadedInThisAms}
  7214. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7215. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7216. rotateChecked
  7217. ? 'bg-bambu-green border-bambu-green text-white'
  7218. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7219. }`}
  7220. >
  7221. {t('printers.drying.rotateTray')}
  7222. </button>
  7223. );
  7224. })()}
  7225. {/* Start mode: now / after delay / at time (#2638) */}
  7226. <div>
  7227. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7228. <div className="grid grid-cols-3 gap-1">
  7229. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7230. <button
  7231. key={mode}
  7232. type="button"
  7233. onClick={() => setDryingStartMode(mode)}
  7234. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7235. dryingStartMode === mode
  7236. ? 'bg-bambu-green border-bambu-green text-white'
  7237. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7238. }`}
  7239. >
  7240. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7241. </button>
  7242. ))}
  7243. </div>
  7244. {dryingStartMode === 'delay' && (
  7245. // Inline chips: a dropdown menu would be clipped by
  7246. // the popover's scrollable body.
  7247. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7248. {DRYING_DELAY_OPTIONS.map(min => (
  7249. <button
  7250. key={min}
  7251. type="button"
  7252. aria-pressed={dryingDelayMinutes === min}
  7253. onClick={() => setDryingDelayMinutes(min)}
  7254. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7255. dryingDelayMinutes === min
  7256. ? 'bg-bambu-green border-bambu-green text-white'
  7257. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7258. }`}
  7259. >
  7260. {formatDurationFromHours(min / 60)}
  7261. </button>
  7262. ))}
  7263. </div>
  7264. )}
  7265. {dryingStartMode === 'at_time' && (
  7266. <input
  7267. ref={dryingAtTimeInputRef}
  7268. type="datetime-local"
  7269. data-testid="drying-start-at"
  7270. value={dryingStartAt}
  7271. onChange={e => setDryingStartAt(e.target.value)}
  7272. className="mt-1.5 w-full px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] focus:outline-none focus:border-bambu-green [color-scheme:dark]"
  7273. />
  7274. )}
  7275. </div>
  7276. </div>
  7277. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7278. {/* Footer */}
  7279. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7280. <button
  7281. onClick={() => {
  7282. if (dryingPopoverAmsId !== null) {
  7283. // Clamp rotateTray off when any tray in this AMS is loaded into
  7284. // the tube — the rotate UI is disabled there, but the state may
  7285. // linger as `true` from a previous AMS, or a print may have
  7286. // started while the popover was open. Without this clamp the
  7287. // Start payload would carry rotate_tray=true and firmware would
  7288. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7289. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7290. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7291. tray => tray.state === 11,
  7292. );
  7293. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7294. if (dryingStartMode === 'now') {
  7295. startDryingMutation.mutate({
  7296. amsId: dryingPopoverAmsId,
  7297. temp: dryingTemp,
  7298. duration: dryingDuration,
  7299. filament: dryingFilament,
  7300. rotateTray: rotate,
  7301. });
  7302. } else {
  7303. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7304. if (startAfter) {
  7305. scheduleDryingMutation.mutate({
  7306. amsId: dryingPopoverAmsId,
  7307. temp: dryingTemp,
  7308. duration: dryingDuration,
  7309. filament: dryingFilament,
  7310. rotateTray: rotate,
  7311. startAfter,
  7312. });
  7313. }
  7314. }
  7315. }
  7316. }}
  7317. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7318. data-testid="drying-start-confirm"
  7319. 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"
  7320. >
  7321. {dryingStartMode === 'now'
  7322. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7323. : t('printers.drying.schedule')}
  7324. </button>
  7325. </div>
  7326. </div>
  7327. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7328. since the popover clips its own overflow. */}
  7329. <div
  7330. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7331. style={{
  7332. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7333. top: dryingPopoverPos.anchorY - 5,
  7334. ...(dryingPopoverPos.placement === 'above'
  7335. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7336. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7337. }}
  7338. />
  7339. </>
  7340. );
  7341. })()}
  7342. </Card>
  7343. );
  7344. }
  7345. export function AddPrinterModal({
  7346. onClose,
  7347. onAdd,
  7348. existingSerials,
  7349. }: {
  7350. onClose: () => void;
  7351. onAdd: (data: PrinterCreate) => void;
  7352. existingSerials: string[];
  7353. }) {
  7354. const { t } = useTranslation();
  7355. const [form, setForm] = useState<PrinterCreate>({
  7356. name: '',
  7357. serial_number: '',
  7358. ip_address: '',
  7359. access_code: '',
  7360. model: '',
  7361. location: '',
  7362. auto_archive: true,
  7363. });
  7364. // Discovery state
  7365. const [discovering, setDiscovering] = useState(false);
  7366. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7367. const [discoveryError, setDiscoveryError] = useState('');
  7368. const [hasScanned, setHasScanned] = useState(false);
  7369. const [isDocker, setIsDocker] = useState(false);
  7370. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7371. const [subnet, setSubnet] = useState('');
  7372. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7373. // text input so users can scan a subnet Bambuddy isn't directly on
  7374. // (printer behind a router on a different L3 segment — SSDP multicast
  7375. // won't cross that boundary, only an active unicast scan will). #1564
  7376. const [customSubnet, setCustomSubnet] = useState('');
  7377. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7378. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7379. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7380. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7381. // (not block) when checks fail, so the user doesn't add a printer that
  7382. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7383. // failed result awaiting an explicit "save anyway".
  7384. const [checkingSave, setCheckingSave] = useState(false);
  7385. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7386. // Fetch discovery info on mount + restore the last custom CIDR the user
  7387. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7388. // time they open this modal).
  7389. useEffect(() => {
  7390. discoveryApi.getInfo().then(info => {
  7391. setIsDocker(info.is_docker);
  7392. if (info.subnets.length > 0) {
  7393. setDetectedSubnets(info.subnets);
  7394. setSubnet(info.subnets[0]);
  7395. }
  7396. }).catch(() => {
  7397. // Ignore errors, assume not Docker
  7398. });
  7399. try {
  7400. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7401. if (saved) setCustomSubnet(saved);
  7402. } catch {
  7403. // localStorage unavailable (private mode, quota); recall is opportunistic
  7404. }
  7405. }, []);
  7406. // Filter out already-added printers
  7407. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7408. const handleAddSubmit = async (e: React.FormEvent) => {
  7409. e.preventDefault();
  7410. setCheckingSave(true);
  7411. try {
  7412. const result = await api.diagnoseConnection({
  7413. ip_address: form.ip_address.trim(),
  7414. serial_number: form.serial_number.trim() || undefined,
  7415. access_code: form.access_code || undefined,
  7416. });
  7417. if (result.checks.some((c) => c.status === 'fail')) {
  7418. setSaveWarning(result);
  7419. return;
  7420. }
  7421. } catch {
  7422. // Diagnostic infrastructure failed — never block the save on it.
  7423. } finally {
  7424. setCheckingSave(false);
  7425. }
  7426. onAdd(form);
  7427. };
  7428. const startDiscovery = async () => {
  7429. setDiscoveryError('');
  7430. setDiscovered([]);
  7431. setDiscovering(true);
  7432. setHasScanned(false);
  7433. setScanProgress({ scanned: 0, total: 0 });
  7434. // Native installs fall back to subnet scanning when the user picks
  7435. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7436. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7437. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7438. const wantsSubnetScan = isDocker || useCustomSubnet;
  7439. if (wantsSubnetScan && useCustomSubnet) {
  7440. try {
  7441. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7442. } catch {
  7443. // localStorage write best-effort; user just retypes next time
  7444. }
  7445. }
  7446. try {
  7447. if (wantsSubnetScan) {
  7448. await discoveryApi.startSubnetScan(scanCidr);
  7449. // Poll for scan status and results
  7450. const pollInterval = setInterval(async () => {
  7451. try {
  7452. const status = await discoveryApi.getScanStatus();
  7453. setScanProgress({ scanned: status.scanned, total: status.total });
  7454. const printers = await discoveryApi.getDiscoveredPrinters();
  7455. setDiscovered(printers);
  7456. if (!status.running) {
  7457. clearInterval(pollInterval);
  7458. setDiscovering(false);
  7459. setHasScanned(true);
  7460. }
  7461. } catch (e) {
  7462. console.error('Failed to get scan status:', e);
  7463. }
  7464. }, 500);
  7465. } else {
  7466. // Use SSDP discovery for native installs
  7467. await discoveryApi.startDiscovery(10);
  7468. // Poll for discovered printers every second
  7469. const pollInterval = setInterval(async () => {
  7470. try {
  7471. const printers = await discoveryApi.getDiscoveredPrinters();
  7472. setDiscovered(printers);
  7473. } catch (e) {
  7474. console.error('Failed to get discovered printers:', e);
  7475. }
  7476. }, 1000);
  7477. // Stop after 10 seconds
  7478. setTimeout(async () => {
  7479. clearInterval(pollInterval);
  7480. try {
  7481. await discoveryApi.stopDiscovery();
  7482. } catch {
  7483. // Ignore stop errors
  7484. }
  7485. setDiscovering(false);
  7486. setHasScanned(true);
  7487. // Final fetch
  7488. try {
  7489. const printers = await discoveryApi.getDiscoveredPrinters();
  7490. setDiscovered(printers);
  7491. } catch (e) {
  7492. console.error('Failed to get final discovered printers:', e);
  7493. }
  7494. }, 10000);
  7495. }
  7496. } catch (e) {
  7497. console.error('Failed to start discovery:', e);
  7498. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7499. setDiscovering(false);
  7500. setHasScanned(true);
  7501. }
  7502. };
  7503. // Reuse module-level mapModelCode
  7504. const selectPrinter = (printer: DiscoveredPrinter) => {
  7505. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7506. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7507. setForm({
  7508. ...form,
  7509. name: printer.name || '',
  7510. serial_number: serialNumber,
  7511. ip_address: printer.ip_address,
  7512. model: mapModelCode(printer.model),
  7513. });
  7514. // Clear discovery results after selection
  7515. setDiscovered([]);
  7516. };
  7517. // Cleanup discovery on unmount
  7518. useEffect(() => {
  7519. return () => {
  7520. discoveryApi.stopDiscovery().catch(() => {});
  7521. discoveryApi.stopSubnetScan().catch(() => {});
  7522. };
  7523. }, []);
  7524. // Close on Escape key
  7525. useEffect(() => {
  7526. const handleKeyDown = (e: KeyboardEvent) => {
  7527. if (e.key === 'Escape') onClose();
  7528. };
  7529. window.addEventListener('keydown', handleKeyDown);
  7530. return () => window.removeEventListener('keydown', handleKeyDown);
  7531. }, [onClose]);
  7532. return (
  7533. <>
  7534. <div
  7535. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7536. onClick={onClose}
  7537. >
  7538. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7539. <CardContent>
  7540. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7541. {/* Discovery Section */}
  7542. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7543. {/* Subnet picker — always visible. The dropdown lists detected
  7544. interface subnets and a "Custom..." sentinel that reveals
  7545. a CIDR text input for printers on a different L3 segment
  7546. (router, VLAN, etc.). #1564 */}
  7547. <div className="mb-3">
  7548. <label className="block text-sm text-bambu-gray mb-1">
  7549. {t('printers.discovery.subnetToScan')}
  7550. </label>
  7551. {detectedSubnets.length > 0 ? (
  7552. <select
  7553. 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"
  7554. value={useCustomSubnet ? '__custom__' : subnet}
  7555. onChange={(e) => {
  7556. if (e.target.value === '__custom__') {
  7557. setUseCustomSubnet(true);
  7558. } else {
  7559. setUseCustomSubnet(false);
  7560. setSubnet(e.target.value);
  7561. }
  7562. }}
  7563. disabled={discovering}
  7564. >
  7565. {detectedSubnets.map(s => (
  7566. <option key={s} value={s}>{s}</option>
  7567. ))}
  7568. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7569. </select>
  7570. ) : (
  7571. <input
  7572. type="text"
  7573. 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"
  7574. value={subnet}
  7575. onChange={(e) => setSubnet(e.target.value)}
  7576. placeholder="192.168.1.0/24"
  7577. disabled={discovering}
  7578. />
  7579. )}
  7580. {useCustomSubnet && (
  7581. <input
  7582. type="text"
  7583. aria-label={t('printers.discovery.customSubnetLabel')}
  7584. 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"
  7585. value={customSubnet}
  7586. onChange={(e) => setCustomSubnet(e.target.value)}
  7587. placeholder="10.1.1.0/24"
  7588. disabled={discovering}
  7589. />
  7590. )}
  7591. <p className="mt-1 text-xs text-bambu-gray">
  7592. {isDocker
  7593. ? t('printers.discovery.dockerNote')
  7594. : t('printers.discovery.customSubnetNote')}
  7595. </p>
  7596. </div>
  7597. <Button
  7598. type="button"
  7599. variant="secondary"
  7600. onClick={startDiscovery}
  7601. disabled={discovering}
  7602. className="w-full"
  7603. >
  7604. {discovering ? (
  7605. <>
  7606. <Loader2 className="w-4 h-4 animate-spin" />
  7607. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7608. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7609. : t('printers.discovery.scanning')}
  7610. </>
  7611. ) : (
  7612. <>
  7613. <Search className="w-4 h-4" />
  7614. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7615. </>
  7616. )}
  7617. </Button>
  7618. {discoveryError && (
  7619. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7620. )}
  7621. {newPrinters.length > 0 && (
  7622. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7623. {newPrinters.map((printer) => (
  7624. <div
  7625. key={printer.serial}
  7626. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7627. onClick={() => selectPrinter(printer)}
  7628. >
  7629. <div className="min-w-0 flex-1">
  7630. <p className="font-medium text-white text-sm truncate">
  7631. {printer.name || printer.serial}
  7632. </p>
  7633. <p className="text-xs text-bambu-gray truncate">
  7634. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7635. {printer.serial.startsWith('unknown-') && (
  7636. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7637. )}
  7638. </p>
  7639. </div>
  7640. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7641. </div>
  7642. ))}
  7643. </div>
  7644. )}
  7645. {discovering && (
  7646. <p className="mt-2 text-sm text-bambu-gray text-center">
  7647. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7648. </p>
  7649. )}
  7650. {hasScanned && !discovering && discovered.length === 0 && (
  7651. <p className="mt-2 text-sm text-bambu-gray text-center">
  7652. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7653. </p>
  7654. )}
  7655. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7656. <p className="mt-2 text-sm text-bambu-gray text-center">
  7657. {t('printers.discovery.allConfigured')}
  7658. </p>
  7659. )}
  7660. </div>
  7661. <form onSubmit={handleAddSubmit} className="space-y-4">
  7662. <div>
  7663. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7664. <input
  7665. type="text"
  7666. required
  7667. 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"
  7668. value={form.name}
  7669. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7670. placeholder={t('printers.modal.myPrinter')}
  7671. />
  7672. </div>
  7673. <div>
  7674. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7675. <input
  7676. type="text"
  7677. required
  7678. 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])?)*)"
  7679. 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"
  7680. value={form.ip_address}
  7681. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7682. placeholder="192.168.1.100 or printer.local"
  7683. />
  7684. </div>
  7685. <div>
  7686. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7687. <input
  7688. type="text"
  7689. required
  7690. 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"
  7691. value={form.serial_number}
  7692. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7693. placeholder="01P00A000000000"
  7694. />
  7695. </div>
  7696. <div>
  7697. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7698. <input
  7699. type="password"
  7700. required
  7701. 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"
  7702. value={form.access_code}
  7703. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7704. placeholder={t('printers.modal.fromPrinterSettings')}
  7705. />
  7706. </div>
  7707. <div>
  7708. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7709. <select
  7710. 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"
  7711. value={form.model || ''}
  7712. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7713. >
  7714. <option value="">{t('printers.modal.selectModel')}</option>
  7715. <optgroup label="A1 Series">
  7716. <option value="A1">A1</option>
  7717. <option value="A1 Mini">A1 Mini</option>
  7718. </optgroup>
  7719. <optgroup label="A2 Series">
  7720. <option value="A2L">A2L</option>
  7721. </optgroup>
  7722. <optgroup label="H2 Series">
  7723. <option value="H2C">H2C</option>
  7724. <option value="H2D">H2D</option>
  7725. <option value="H2D Pro">H2D Pro</option>
  7726. <option value="H2S">H2S</option>
  7727. </optgroup>
  7728. <optgroup label="P Series">
  7729. <option value="P1P">P1P</option>
  7730. <option value="P1S">P1S</option>
  7731. <option value="P2S">P2S</option>
  7732. </optgroup>
  7733. <optgroup label="X1 Series">
  7734. <option value="X1">X1</option>
  7735. <option value="X1C">X1 Carbon</option>
  7736. <option value="X1E">X1E</option>
  7737. </optgroup>
  7738. <optgroup label="X2 Series">
  7739. <option value="X2D">X2D</option>
  7740. </optgroup>
  7741. </select>
  7742. </div>
  7743. <div>
  7744. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7745. <input
  7746. type="text"
  7747. 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"
  7748. value={form.location || ''}
  7749. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7750. placeholder={t('printers.modal.locationPlaceholder')}
  7751. maxLength={100}
  7752. />
  7753. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7754. </div>
  7755. <div className="flex items-center gap-2">
  7756. <input
  7757. type="checkbox"
  7758. id="auto_archive"
  7759. checked={form.auto_archive}
  7760. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7761. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7762. />
  7763. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7764. {t('printers.modal.autoArchiveLabel')}
  7765. </label>
  7766. </div>
  7767. <button
  7768. type="button"
  7769. onClick={() => setShowDiagnostic(true)}
  7770. disabled={!form.ip_address.trim()}
  7771. 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"
  7772. >
  7773. <Stethoscope className="w-4 h-4" />
  7774. {t('diagnostic.runButton')}
  7775. </button>
  7776. {saveWarning ? (
  7777. <div className="rounded-lg bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 p-3 space-y-3">
  7778. <div className="flex items-start gap-2">
  7779. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7780. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7781. </div>
  7782. <DiagnosticChecklist result={saveWarning} />
  7783. <div className="flex gap-3">
  7784. <Button
  7785. type="button"
  7786. variant="secondary"
  7787. onClick={() => setSaveWarning(null)}
  7788. className="flex-1"
  7789. >
  7790. {t('printers.addPreflight.back')}
  7791. </Button>
  7792. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7793. {t('printers.addPreflight.saveAnyway')}
  7794. </Button>
  7795. </div>
  7796. </div>
  7797. ) : (
  7798. <div className="flex gap-3 pt-2">
  7799. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7800. {t('common.cancel')}
  7801. </Button>
  7802. <Button type="submit" disabled={checkingSave} className="flex-1">
  7803. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7804. </Button>
  7805. </div>
  7806. )}
  7807. </form>
  7808. </CardContent>
  7809. </Card>
  7810. </div>
  7811. {showDiagnostic && (
  7812. <ConnectionDiagnosticModal
  7813. connection={{
  7814. ip_address: form.ip_address.trim(),
  7815. serial_number: form.serial_number.trim() || undefined,
  7816. access_code: form.access_code || undefined,
  7817. }}
  7818. printerName={form.name || null}
  7819. onClose={() => setShowDiagnostic(false)}
  7820. />
  7821. )}
  7822. </>
  7823. );
  7824. }
  7825. function FirmwareUpdateModal({
  7826. printer,
  7827. firmwareInfo,
  7828. onClose,
  7829. }: {
  7830. printer: Printer;
  7831. firmwareInfo: FirmwareUpdateInfo;
  7832. onClose: () => void;
  7833. }) {
  7834. const { t } = useTranslation();
  7835. const queryClient = useQueryClient();
  7836. const { showToast } = useToast();
  7837. const { hasPermission } = useAuth();
  7838. const canUpdate = hasPermission('firmware:update');
  7839. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7840. const [isUploading, setIsUploading] = useState(false);
  7841. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7842. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7843. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7844. );
  7845. // Prepare check query — runs when a version is selected and user can update
  7846. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7847. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7848. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7849. staleTime: 30000,
  7850. enabled: !!selectedVersion && canUpdate && !isUploading,
  7851. });
  7852. // Start upload mutation
  7853. const uploadMutation = useMutation({
  7854. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7855. onSuccess: () => {
  7856. setIsUploading(true);
  7857. // Start polling for status
  7858. const interval = setInterval(async () => {
  7859. try {
  7860. const status = await firmwareApi.getUploadStatus(printer.id);
  7861. setUploadStatus(status);
  7862. if (status.status === 'complete' || status.status === 'error') {
  7863. clearInterval(interval);
  7864. setPollInterval(null);
  7865. setIsUploading(false);
  7866. if (status.status === 'complete') {
  7867. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7868. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7869. }
  7870. }
  7871. } catch {
  7872. // Ignore errors during polling
  7873. }
  7874. }, 2000);
  7875. setPollInterval(interval);
  7876. },
  7877. onError: (error: Error) => {
  7878. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7879. setIsUploading(false);
  7880. },
  7881. });
  7882. // Cleanup on unmount
  7883. useEffect(() => {
  7884. return () => {
  7885. if (pollInterval) clearInterval(pollInterval);
  7886. };
  7887. }, [pollInterval]);
  7888. const handleStartUpload = () => {
  7889. setUploadStatus(null);
  7890. uploadMutation.mutate();
  7891. };
  7892. return (
  7893. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7894. <Card className="w-full max-w-md mx-4">
  7895. <CardContent>
  7896. <div className="flex items-start gap-3 mb-4">
  7897. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7898. {firmwareInfo.update_available
  7899. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7900. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7901. </div>
  7902. <div className="flex-1">
  7903. <h3 className="text-lg font-semibold text-white">
  7904. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7905. </h3>
  7906. <p className="text-sm text-bambu-gray mt-1">
  7907. {printer.name}
  7908. </p>
  7909. </div>
  7910. </div>
  7911. {/* Version Info */}
  7912. {(() => {
  7913. const selectedEntry = selectedVersion
  7914. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7915. : null;
  7916. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7917. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7918. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7919. return (
  7920. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7921. <div className="flex justify-between items-center text-sm">
  7922. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7923. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7924. {firmwareInfo.current_version || t('common.unknown')}
  7925. </span>
  7926. </div>
  7927. {showSecondLine && (
  7928. <div className="flex justify-between items-center text-sm mt-1">
  7929. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7930. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7931. </div>
  7932. )}
  7933. {displayNotes && (
  7934. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7935. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7936. {t('printers.firmwareModal.releaseNotes')}
  7937. </summary>
  7938. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7939. {displayNotes}
  7940. </div>
  7941. </details>
  7942. )}
  7943. </div>
  7944. );
  7945. })()}
  7946. {/* Available versions list */}
  7947. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7948. <div className="mb-4">
  7949. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7950. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7951. {firmwareInfo.available_versions.map((v) => {
  7952. const isCurrent = firmwareInfo.current_version === v.version;
  7953. const isSelected = selectedVersion === v.version;
  7954. const cmp = firmwareInfo.current_version
  7955. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7956. : 0;
  7957. const relLabel = isCurrent
  7958. ? t('printers.firmwareModal.currentBadge')
  7959. : cmp > 0
  7960. ? t('printers.firmwareModal.newerBadge')
  7961. : t('printers.firmwareModal.olderBadge');
  7962. const relClass = isCurrent
  7963. ? 'text-bambu-gray'
  7964. : cmp > 0
  7965. ? 'text-orange-700 dark:text-orange-400'
  7966. : 'text-blue-700 dark:text-blue-400';
  7967. return (
  7968. <button
  7969. key={v.version}
  7970. type="button"
  7971. disabled={!v.file_available || !canUpdate || isCurrent}
  7972. onClick={() => setSelectedVersion(v.version)}
  7973. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7974. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7975. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7976. >
  7977. <div className="flex items-center gap-2 min-w-0">
  7978. <span className="font-mono text-white">{v.version}</span>
  7979. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7980. </div>
  7981. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7982. isCurrent
  7983. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7984. : v.file_available
  7985. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7986. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7987. }`}>
  7988. {isCurrent
  7989. ? t('printers.firmwareModal.installed')
  7990. : v.file_available
  7991. ? t('printers.firmwareModal.usable')
  7992. : t('printers.firmwareModal.unavailable')}
  7993. </span>
  7994. </button>
  7995. );
  7996. })}
  7997. </div>
  7998. </div>
  7999. )}
  8000. {/* Status / Progress (only when a version is selected) */}
  8001. {!selectedVersion ? null : isPreparing ? (
  8002. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  8003. <Loader2 className="w-4 h-4 animate-spin" />
  8004. {t('printers.firmwareModal.checkingPrereqs')}
  8005. </div>
  8006. ) : prepareInfo && !isUploading && !uploadStatus ? (
  8007. <div className="mb-4">
  8008. {prepareInfo.can_proceed ? (
  8009. <div className="flex items-center gap-2 text-bambu-green text-sm">
  8010. <Box className="w-4 h-4" />
  8011. {t('printers.firmwareModal.sdCardReady')}
  8012. </div>
  8013. ) : (
  8014. <div className="space-y-1">
  8015. {prepareInfo.errors.map((error, i) => (
  8016. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  8017. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  8018. {error}
  8019. </div>
  8020. ))}
  8021. </div>
  8022. )}
  8023. </div>
  8024. ) : null}
  8025. {/* Upload Progress */}
  8026. {(isUploading || uploadStatus) && uploadStatus && (
  8027. <div className="mb-4">
  8028. <div className="flex items-center justify-between text-sm mb-1">
  8029. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8030. <span className="text-white">{uploadStatus.progress}%</span>
  8031. </div>
  8032. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8033. <div
  8034. className={`h-2 rounded-full transition-all ${
  8035. uploadStatus.status === 'error' ? 'bg-status-error' :
  8036. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8037. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8038. style={{ width: `${uploadStatus.progress}%` }}
  8039. />
  8040. </div>
  8041. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8042. {uploadStatus.error && (
  8043. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8044. )}
  8045. </div>
  8046. )}
  8047. {/* Success Message */}
  8048. {uploadStatus?.status === 'complete' && (
  8049. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8050. <p className="text-sm text-bambu-green font-medium mb-2">
  8051. {t('printers.firmwareModal.uploadedSuccess')}
  8052. </p>
  8053. <p className="text-xs text-bambu-gray">
  8054. {t('printers.firmwareModal.applyInstructions')}
  8055. </p>
  8056. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8057. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8058. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8059. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8060. <li>{t('printers.firmwareModal.step4')}</li>
  8061. </ol>
  8062. </div>
  8063. )}
  8064. {/* Buttons */}
  8065. <div className="flex gap-2 justify-end">
  8066. <Button variant="secondary" onClick={onClose}>
  8067. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8068. </Button>
  8069. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8070. <Button
  8071. onClick={handleStartUpload}
  8072. disabled={uploadMutation.isPending}
  8073. >
  8074. {uploadMutation.isPending ? (
  8075. <>
  8076. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8077. {t('printers.firmwareModal.starting')}
  8078. </>
  8079. ) : (
  8080. <>
  8081. <Download className="w-4 h-4 mr-2" />
  8082. {t('printers.firmwareModal.uploadFirmware')}
  8083. </>
  8084. )}
  8085. </Button>
  8086. )}
  8087. </div>
  8088. </CardContent>
  8089. </Card>
  8090. </div>
  8091. );
  8092. }
  8093. function EditPrinterModal({
  8094. printer,
  8095. onClose,
  8096. }: {
  8097. printer: Printer;
  8098. onClose: () => void;
  8099. }) {
  8100. const { t } = useTranslation();
  8101. const queryClient = useQueryClient();
  8102. const { showToast } = useToast();
  8103. const { authEnabled, isAdmin } = useAuth();
  8104. const [form, setForm] = useState({
  8105. name: printer.name,
  8106. ip_address: printer.ip_address,
  8107. access_code: '',
  8108. model: printer.model || '',
  8109. location: printer.location || '',
  8110. auto_archive: printer.auto_archive,
  8111. is_active: printer.is_active,
  8112. wear_cost_per_hour: printer.wear_cost_per_hour ? String(printer.wear_cost_per_hour) : '',
  8113. });
  8114. const { data: settings } = useQuery({ queryKey: ['settings'], queryFn: api.getSettings });
  8115. const currency = getCurrencySymbol(settings?.currency || 'USD');
  8116. // Groups can be given a location (#1727), so a move changes who can use the
  8117. // printer. Non-admins can't read groups; the server refuses their move instead.
  8118. const { data: groups } = useQuery({
  8119. queryKey: ['groups'],
  8120. queryFn: () => api.getGroups(),
  8121. enabled: authEnabled && isAdmin,
  8122. });
  8123. const newLocation = form.location.trim();
  8124. const accessChangedFor =
  8125. newLocation !== (printer.location || '')
  8126. ? (groups ?? [])
  8127. .filter(
  8128. (g) =>
  8129. g.restrict_printers &&
  8130. (g.locations ?? []).some((loc) => loc === printer.location || loc === newLocation)
  8131. )
  8132. .map((g) => g.name)
  8133. : [];
  8134. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8135. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8136. const [checkingSave, setCheckingSave] = useState(false);
  8137. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8138. const updateMutation = useMutation({
  8139. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8140. onSuccess: () => {
  8141. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8142. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8143. onClose();
  8144. },
  8145. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8146. });
  8147. // Close on Escape key
  8148. useEffect(() => {
  8149. const handleKeyDown = (e: KeyboardEvent) => {
  8150. if (e.key === 'Escape') onClose();
  8151. };
  8152. window.addEventListener('keydown', handleKeyDown);
  8153. return () => window.removeEventListener('keydown', handleKeyDown);
  8154. }, [onClose]);
  8155. const doSave = () => {
  8156. const data: Partial<PrinterCreate> = {
  8157. name: form.name,
  8158. ip_address: form.ip_address,
  8159. model: form.model || undefined,
  8160. // null clears it; leaving it out kept the old location
  8161. location: form.location.trim() || null,
  8162. auto_archive: form.auto_archive,
  8163. is_active: form.is_active,
  8164. // Empty or 0 turns wear cost off for this printer (#694)
  8165. wear_cost_per_hour: Number(form.wear_cost_per_hour) > 0 ? Number(form.wear_cost_per_hour) : null,
  8166. };
  8167. // Only include access_code if it was changed
  8168. if (form.access_code) {
  8169. data.access_code = form.access_code;
  8170. }
  8171. updateMutation.mutate(data);
  8172. };
  8173. const handleSubmit = async (e: React.FormEvent) => {
  8174. e.preventDefault();
  8175. setCheckingSave(true);
  8176. try {
  8177. const result = await api.diagnoseConnection({
  8178. ip_address: form.ip_address.trim(),
  8179. serial_number: printer.serial_number,
  8180. access_code: form.access_code || undefined,
  8181. });
  8182. if (result.checks.some((c) => c.status === 'fail')) {
  8183. setSaveWarning(result);
  8184. return;
  8185. }
  8186. } catch {
  8187. // Diagnostic infrastructure failed — never block the save on it.
  8188. } finally {
  8189. setCheckingSave(false);
  8190. }
  8191. doSave();
  8192. };
  8193. return (
  8194. <div
  8195. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8196. onClick={onClose}
  8197. >
  8198. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8199. <CardContent>
  8200. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8201. <form onSubmit={handleSubmit} className="space-y-4">
  8202. <div>
  8203. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8204. <input
  8205. type="text"
  8206. required
  8207. 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"
  8208. value={form.name}
  8209. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8210. placeholder={t('printers.modal.myPrinter')}
  8211. />
  8212. </div>
  8213. <div>
  8214. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8215. <input
  8216. type="text"
  8217. required
  8218. 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])?)*)"
  8219. 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"
  8220. value={form.ip_address}
  8221. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8222. placeholder="192.168.1.100 or printer.local"
  8223. />
  8224. </div>
  8225. <div>
  8226. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8227. <input
  8228. type="text"
  8229. disabled
  8230. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8231. value={printer.serial_number}
  8232. />
  8233. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8234. </div>
  8235. <div>
  8236. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8237. <input
  8238. type="password"
  8239. 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"
  8240. value={form.access_code}
  8241. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8242. placeholder={t('printers.accessCodePlaceholder')}
  8243. />
  8244. </div>
  8245. <div>
  8246. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8247. <select
  8248. 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"
  8249. value={form.model}
  8250. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8251. >
  8252. <option value="">{t('printers.modal.selectModel')}</option>
  8253. <optgroup label="A1 Series">
  8254. <option value="A1">A1</option>
  8255. <option value="A1 Mini">A1 Mini</option>
  8256. </optgroup>
  8257. <optgroup label="A2 Series">
  8258. <option value="A2L">A2L</option>
  8259. </optgroup>
  8260. <optgroup label="H2 Series">
  8261. <option value="H2C">H2C</option>
  8262. <option value="H2D">H2D</option>
  8263. <option value="H2D Pro">H2D Pro</option>
  8264. <option value="H2S">H2S</option>
  8265. </optgroup>
  8266. <optgroup label="P Series">
  8267. <option value="P1P">P1P</option>
  8268. <option value="P1S">P1S</option>
  8269. <option value="P2S">P2S</option>
  8270. </optgroup>
  8271. <optgroup label="X1 Series">
  8272. <option value="X1">X1</option>
  8273. <option value="X1C">X1 Carbon</option>
  8274. <option value="X1E">X1E</option>
  8275. </optgroup>
  8276. <optgroup label="X2 Series">
  8277. <option value="X2D">X2D</option>
  8278. </optgroup>
  8279. </select>
  8280. </div>
  8281. <div>
  8282. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8283. <input
  8284. type="text"
  8285. 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"
  8286. value={form.location}
  8287. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8288. placeholder={t('printers.modal.locationPlaceholder')}
  8289. maxLength={100}
  8290. />
  8291. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8292. {accessChangedFor.length > 0 && (
  8293. <p className="flex items-start gap-1.5 text-xs text-yellow-700 dark:text-yellow-400 mt-1">
  8294. <AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-px" />
  8295. {t('printerAccess.moveWarning', { groups: accessChangedFor.join(', ') })}
  8296. </p>
  8297. )}
  8298. </div>
  8299. <div className="flex items-center gap-2">
  8300. <input
  8301. type="checkbox"
  8302. id="edit_auto_archive"
  8303. checked={form.auto_archive}
  8304. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8305. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8306. />
  8307. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8308. {t('printers.modal.autoArchiveLabel')}
  8309. </label>
  8310. </div>
  8311. <div>
  8312. <label htmlFor="edit_wear_cost" className="block text-sm text-bambu-gray mb-1">
  8313. {t('printers.modal.wearCostLabel', { currency })}
  8314. </label>
  8315. <input
  8316. id="edit_wear_cost"
  8317. type="number"
  8318. min={0}
  8319. step="0.01"
  8320. inputMode="decimal"
  8321. 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"
  8322. value={form.wear_cost_per_hour}
  8323. onChange={(e) => setForm({ ...form, wear_cost_per_hour: e.target.value })}
  8324. placeholder="0.00"
  8325. />
  8326. <p className="text-xs text-bambu-gray mt-1">{t('printers.modal.wearCostHelp')}</p>
  8327. </div>
  8328. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8329. is_active because the user-facing concept is "is this printer
  8330. in maintenance" not "is it active". */}
  8331. <div>
  8332. <div className="flex items-center gap-2">
  8333. <input
  8334. type="checkbox"
  8335. id="edit_maintenance_mode"
  8336. checked={!form.is_active}
  8337. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8338. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8339. />
  8340. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8341. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8342. {t('printers.maintenance.editFieldLabel')}
  8343. </label>
  8344. </div>
  8345. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8346. {t('printers.maintenance.editFieldHelp')}
  8347. </p>
  8348. </div>
  8349. {saveWarning ? (
  8350. <div className="rounded-lg bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 p-3 space-y-3">
  8351. <div className="flex items-start gap-2">
  8352. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8353. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8354. </div>
  8355. <DiagnosticChecklist result={saveWarning} />
  8356. <div className="flex gap-3">
  8357. <Button
  8358. type="button"
  8359. variant="secondary"
  8360. onClick={() => setSaveWarning(null)}
  8361. className="flex-1"
  8362. >
  8363. {t('printers.addPreflight.back')}
  8364. </Button>
  8365. <Button
  8366. type="button"
  8367. onClick={doSave}
  8368. className="flex-1"
  8369. disabled={updateMutation.isPending}
  8370. >
  8371. {t('printers.addPreflight.saveAnyway')}
  8372. </Button>
  8373. </div>
  8374. </div>
  8375. ) : (
  8376. <div className="flex gap-3 pt-4">
  8377. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8378. {t('common.cancel')}
  8379. </Button>
  8380. <Button
  8381. type="submit"
  8382. className="flex-1"
  8383. disabled={updateMutation.isPending || checkingSave}
  8384. >
  8385. {checkingSave
  8386. ? t('printers.addPreflight.checking')
  8387. : updateMutation.isPending
  8388. ? t('common.saving')
  8389. : t('printers.modal.saveChanges')}
  8390. </Button>
  8391. </div>
  8392. )}
  8393. </form>
  8394. </CardContent>
  8395. </Card>
  8396. </div>
  8397. );
  8398. }
  8399. // Component to check if a printer is offline (for power dropdown)
  8400. function usePrinterOfflineStatus(printerId: number) {
  8401. const { data: status } = useQuery({
  8402. queryKey: ['printerStatus', printerId],
  8403. queryFn: () => api.getPrinterStatus(printerId),
  8404. refetchInterval: 30000,
  8405. });
  8406. return !status?.connected;
  8407. }
  8408. // Power dropdown item for an offline printer
  8409. function PowerDropdownItem({
  8410. printer,
  8411. plug,
  8412. onPowerOn,
  8413. isPowering,
  8414. }: {
  8415. printer: Printer;
  8416. plug: { id: number; name: string };
  8417. onPowerOn: (plugId: number) => void;
  8418. isPowering: boolean;
  8419. }) {
  8420. const isOffline = usePrinterOfflineStatus(printer.id);
  8421. // Fetch plug status
  8422. const { data: plugStatus } = useQuery({
  8423. queryKey: ['smartPlugStatus', plug.id],
  8424. queryFn: () => api.getSmartPlugStatus(plug.id),
  8425. refetchInterval: 10000,
  8426. });
  8427. // Only show if printer is offline
  8428. if (!isOffline) {
  8429. return null;
  8430. }
  8431. return (
  8432. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8433. <div className="flex items-center gap-2 min-w-0">
  8434. <span className="text-sm text-white truncate">{printer.name}</span>
  8435. {plugStatus && (
  8436. <span
  8437. className={`text-xs px-1.5 py-0.5 rounded ${
  8438. plugStatus.state === 'ON'
  8439. ? 'bg-bambu-green/20 text-bambu-green'
  8440. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8441. }`}
  8442. >
  8443. {plugStatus.state || '?'}
  8444. </span>
  8445. )}
  8446. </div>
  8447. <button
  8448. onClick={() => onPowerOn(plug.id)}
  8449. disabled={isPowering || plugStatus?.state === 'ON'}
  8450. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8451. plugStatus?.state === 'ON'
  8452. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8453. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8454. }`}
  8455. >
  8456. <Power className="w-3 h-3" />
  8457. {isPowering ? '...' : 'On'}
  8458. </button>
  8459. </div>
  8460. );
  8461. }
  8462. export function PrintersPage() {
  8463. const { t } = useTranslation();
  8464. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8465. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8466. const accentButtonClass = {
  8467. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8468. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8469. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8470. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8471. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8472. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8473. }[activeAccent];
  8474. const [showAddModal, setShowAddModal] = useState(false);
  8475. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8476. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8477. });
  8478. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8479. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8480. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8481. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8482. });
  8483. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8484. return localStorage.getItem('printerSortAsc') !== 'false';
  8485. });
  8486. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8487. const [cardSize, setCardSize] = useState<number>(() => {
  8488. const saved = localStorage.getItem('printerCardSize');
  8489. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8490. });
  8491. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8492. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8493. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8494. });
  8495. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8496. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8497. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8498. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8499. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8500. });
  8501. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8502. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8503. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8504. });
  8505. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8506. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8507. // Defaulting to 'full' because the cards already show this info — users who
  8508. // pick cam-wall view still want to glance the same details without flipping.
  8509. // Kept apart from the card size: S on the cards also means the compact
  8510. // layout, and a wall of 2 cameras wants big tiles next to small cards (#2735).
  8511. const [camWallTileSize, setCamWallTileSize] = useState<number>(() => {
  8512. const saved = parseInt(localStorage.getItem('camWallTileSize') || '', 10);
  8513. return saved >= 1 && saved <= 4 ? saved : DEFAULT_CAM_WALL_TILE_SIZE;
  8514. });
  8515. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8516. const saved = localStorage.getItem('camWallStatusMode');
  8517. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8518. });
  8519. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8520. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8521. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8522. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8523. requestAnimationFrame(() => {
  8524. requestAnimationFrame(() => {
  8525. const card = document.getElementById(`printer-card-${printerId}`);
  8526. if (!card) return;
  8527. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8528. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8529. window.scrollTo({
  8530. top: Math.max(0, top),
  8531. behavior: 'smooth',
  8532. });
  8533. });
  8534. });
  8535. }, []);
  8536. const openCompactCard = useCallback((printerId: number) => {
  8537. setCompactDrilldownPrinterId(printerId);
  8538. setCardSize(2);
  8539. localStorage.setItem('printerCardSize', '2');
  8540. scrollPrinterIntoView(printerId);
  8541. }, [scrollPrinterIntoView]);
  8542. const returnToCompactCards = useCallback(() => {
  8543. const printerId = compactDrilldownPrinterId;
  8544. setCompactDrilldownPrinterId(null);
  8545. setCardSize(1);
  8546. localStorage.setItem('printerCardSize', '1');
  8547. if (printerId != null) {
  8548. scrollPrinterIntoView(printerId);
  8549. }
  8550. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8551. const [search, setSearch] = useState('');
  8552. // Both filters persist like every other preference on this page (#2833).
  8553. // `search` deliberately does not: a box that silently refills itself on
  8554. // return is more surprising than a dropdown that remembers.
  8555. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8556. // Validated on read: a value the dropdown no longer offers would filter
  8557. // every printer out, and nothing would explain why.
  8558. const saved = localStorage.getItem('printerStatusFilter');
  8559. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8560. });
  8561. const [locationFilter, setLocationFilter] = useState<string>(
  8562. () => localStorage.getItem('printerLocationFilter') || 'all'
  8563. );
  8564. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8565. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8566. try {
  8567. const saved = localStorage.getItem('printerCollapsedSections');
  8568. return saved ? JSON.parse(saved) : {};
  8569. } catch { return {}; }
  8570. });
  8571. const queryClient = useQueryClient();
  8572. const { showToast } = useToast();
  8573. const { hasPermission } = useAuth();
  8574. // Which way the camera buttons open a stream. Chosen per click from the
  8575. // button's own menu; null until this browser has made a choice, so the
  8576. // stored setting below can act as the default a fresh browser starts from.
  8577. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8578. () => readStoredCameraViewMode()
  8579. );
  8580. // Embedded camera viewer state - supports multiple simultaneous viewers
  8581. // Persisted to localStorage so cameras reopen after navigation
  8582. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8583. const saved = localStorage.getItem('openEmbeddedCameras');
  8584. if (saved) {
  8585. try {
  8586. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8587. return new Map(cameras.map(c => [c.id, c]));
  8588. } catch {
  8589. return new Map();
  8590. }
  8591. }
  8592. return new Map();
  8593. });
  8594. // Persist open cameras to localStorage when they change
  8595. useEffect(() => {
  8596. const cameras = Array.from(embeddedCameraPrinters.values());
  8597. if (cameras.length > 0) {
  8598. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8599. } else {
  8600. localStorage.removeItem('openEmbeddedCameras');
  8601. }
  8602. }, [embeddedCameraPrinters]);
  8603. const { data: printers, isLoading } = useQuery({
  8604. queryKey: ['printers'],
  8605. queryFn: api.getPrinters,
  8606. });
  8607. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8608. // so users with printers:read but no settings:read still get the values needed
  8609. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8610. const { data: settings } = useQuery({
  8611. queryKey: ['ui-preferences'],
  8612. queryFn: api.getUiPreferences,
  8613. });
  8614. // Only once the preferences are in: deciding on `undefined` meant a check
  8615. // switched off still went out once per printer on every page load.
  8616. const firmwareChecksOn = settings !== undefined && settings.check_printer_firmware !== false;
  8617. // Parse user-configured temperature/fan presets once, with defensive fallback
  8618. // to built-in defaults on parse failure (validators on the backend already
  8619. // reject malformed writes, so this is just forward-compat).
  8620. const effectiveNozzleTempPresets = useMemo(
  8621. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8622. [settings?.nozzle_temp_presets],
  8623. );
  8624. const effectiveBedTempPresets = useMemo(
  8625. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8626. [settings?.bed_temp_presets],
  8627. );
  8628. const effectiveChamberTempPresets = useMemo(
  8629. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8630. [settings?.chamber_temp_presets],
  8631. );
  8632. const effectiveFanSpeedPresets = useMemo(
  8633. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8634. [settings?.fan_speed_presets],
  8635. );
  8636. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8637. const effectiveDryingPresets = useMemo(() => {
  8638. if (settings?.drying_presets) {
  8639. try {
  8640. const userPresets = JSON.parse(settings.drying_presets);
  8641. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8642. return { ...DRYING_PRESETS, ...userPresets };
  8643. }
  8644. } catch { /* ignore parse errors, use defaults */ }
  8645. }
  8646. return DRYING_PRESETS;
  8647. }, [settings?.drying_presets]);
  8648. // The local choice wins over the stored one: someone without settings:update
  8649. // cannot write their pick back, and a preference that silently reverted on
  8650. // the next render would be worse than none at all.
  8651. const cameraViewMode: CameraViewMode =
  8652. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8653. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8654. storeCameraViewMode(mode);
  8655. setChosenCameraViewMode(mode);
  8656. // Best effort, and only a default for other browsers -- the choice is
  8657. // already in effect here. Users below settings:update simply keep theirs
  8658. // locally, which is why the failure is logged rather than surfaced.
  8659. if (hasPermission('settings:update')) {
  8660. api.updateSettings({ camera_view_mode: mode })
  8661. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8662. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8663. }
  8664. }, [hasPermission, queryClient]);
  8665. // Fetch all smart plugs to know which printers have them
  8666. const { data: smartPlugs } = useQuery({
  8667. queryKey: ['smart-plugs'],
  8668. queryFn: api.getSmartPlugs,
  8669. });
  8670. // Fetch maintenance overview for all printers to show badges
  8671. const { data: maintenanceOverview } = useQuery({
  8672. queryKey: ['maintenanceOverview'],
  8673. queryFn: api.getMaintenanceOverview,
  8674. staleTime: 60 * 1000, // 1 minute
  8675. });
  8676. // Live AI failure detection state for the card badges (#1546). Matches the
  8677. // 10s refetch of the Failure Detection settings panel.
  8678. const { data: obicoPrinterStatus } = useQuery({
  8679. queryKey: ['obico-printer-status'],
  8680. queryFn: api.getObicoPrinterStatus,
  8681. refetchInterval: 10000,
  8682. });
  8683. // Badge visibility: detection enabled AND this printer in the monitored set
  8684. // (monitored_printers null = all). Live per-print state is passed separately.
  8685. const isAiMonitored = useCallback(
  8686. (printerId: number) =>
  8687. obicoPrinterStatus?.enabled === true &&
  8688. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8689. [obicoPrinterStatus],
  8690. );
  8691. // Fetch Spoolman status to enable link spool feature
  8692. const { data: spoolmanStatus } = useQuery({
  8693. queryKey: ['spoolman-status'],
  8694. queryFn: api.getSpoolmanStatus,
  8695. staleTime: 60 * 1000, // 1 minute
  8696. });
  8697. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8698. // Fetch Spoolman settings to get sync mode
  8699. const { data: spoolmanSettings } = useQuery({
  8700. queryKey: ['spoolman-settings'],
  8701. queryFn: api.getSpoolmanSettings,
  8702. enabled: !!spoolmanEnabled,
  8703. staleTime: 60 * 1000, // 1 minute
  8704. });
  8705. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8706. // Fetch unlinked spools to know if link button should be enabled
  8707. const { data: unlinkedSpools } = useQuery({
  8708. queryKey: ['unlinked-spools'],
  8709. queryFn: api.getUnlinkedSpools,
  8710. enabled: !!spoolmanEnabled,
  8711. staleTime: 30 * 1000, // 30 seconds
  8712. });
  8713. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8714. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8715. const { data: linkedSpoolsData } = useQuery({
  8716. queryKey: ['linked-spools'],
  8717. queryFn: api.getLinkedSpools,
  8718. enabled: !!spoolmanEnabled,
  8719. staleTime: 30 * 1000, // 30 seconds
  8720. });
  8721. const linkedSpools = linkedSpoolsData?.linked;
  8722. // Fetch spool assignments for inventory feature
  8723. const { data: spoolAssignments } = useQuery({
  8724. queryKey: ['spool-assignments'],
  8725. queryFn: () => api.getAssignments(),
  8726. enabled: hasPermission('inventory:view_assignments'),
  8727. staleTime: 30 * 1000,
  8728. });
  8729. const unassignMutation = useMutation({
  8730. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8731. api.unassignSpool(printerId, amsId, trayId),
  8732. onSuccess: () => {
  8733. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8734. },
  8735. });
  8736. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8737. queryKey: ['spoolman-inventory-spools'],
  8738. queryFn: () => api.getSpoolmanInventorySpools(false),
  8739. enabled: !!spoolmanEnabled,
  8740. staleTime: 30 * 1000,
  8741. });
  8742. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8743. queryKey: ['spoolman-slot-assignments'],
  8744. queryFn: () => api.getSpoolmanSlotAssignments(),
  8745. enabled: !!spoolmanEnabled,
  8746. staleTime: 30 * 1000,
  8747. });
  8748. const unassignSpoolmanMutation = useMutation({
  8749. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8750. onSuccess: () => {
  8751. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8752. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8753. },
  8754. });
  8755. // Helper to find assignment for a specific slot
  8756. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8757. return spoolAssignments?.find(
  8758. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8759. );
  8760. };
  8761. // Create a map of printer_id -> maintenance info for quick lookup
  8762. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8763. (acc, overview) => {
  8764. acc[overview.printer_id] = {
  8765. due_count: overview.due_count,
  8766. warning_count: overview.warning_count,
  8767. total_print_hours: overview.total_print_hours,
  8768. };
  8769. return acc;
  8770. },
  8771. {} as Record<number, PrinterMaintenanceInfo>
  8772. ) || {};
  8773. // Create a map of printer_id -> smart plug
  8774. const smartPlugByPrinter = smartPlugs?.reduce(
  8775. (acc, plug) => {
  8776. if (plug.printer_id) {
  8777. acc[plug.printer_id] = plug;
  8778. }
  8779. return acc;
  8780. },
  8781. {} as Record<number, typeof smartPlugs[0]>
  8782. ) || {};
  8783. const addMutation = useMutation({
  8784. mutationFn: api.createPrinter,
  8785. onSuccess: () => {
  8786. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8787. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8788. setShowAddModal(false);
  8789. },
  8790. onError: (error: Error) => {
  8791. // Localized message when the backend returns a stable error code;
  8792. // the raw message is an English fallback for non-UI clients.
  8793. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8794. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8795. return;
  8796. }
  8797. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8798. },
  8799. });
  8800. const powerOnMutation = useMutation({
  8801. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8802. onSuccess: () => {
  8803. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8804. setPoweringOn(null);
  8805. },
  8806. onError: () => {
  8807. setPoweringOn(null);
  8808. },
  8809. });
  8810. // Bulk selection state
  8811. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8812. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8813. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8814. const [bulkActionPending, setBulkActionPending] = useState(false);
  8815. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8816. const toggleSelect = useCallback((id: number) => {
  8817. setSelectedPrinterIds(prev => {
  8818. const next = new Set(prev);
  8819. if (next.has(id)) next.delete(id);
  8820. else next.add(id);
  8821. return next;
  8822. });
  8823. }, []);
  8824. const clearSelection = useCallback(() => {
  8825. setSelectedPrinterIds(new Set());
  8826. setIsSelectionMode(false);
  8827. }, []);
  8828. // Escape key exits selection mode
  8829. useEffect(() => {
  8830. const handleKeyDown = (e: KeyboardEvent) => {
  8831. if (e.key === 'Escape' && selectionMode) {
  8832. clearSelection();
  8833. }
  8834. };
  8835. window.addEventListener('keydown', handleKeyDown);
  8836. return () => window.removeEventListener('keydown', handleKeyDown);
  8837. }, [selectionMode, clearSelection]);
  8838. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8839. setBulkActionPending(true);
  8840. const ids = Array.from(selectedPrinterIds);
  8841. // Filter to only applicable printers based on cached state
  8842. const applicableIds = ids.filter(id => {
  8843. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8844. // clearPlate is checked before the connection filter: it only releases a
  8845. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8846. // down — every other action here needs to reach the machine (#2864).
  8847. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8848. if (!status?.connected) return false;
  8849. switch (action) {
  8850. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8851. case 'pause': return status.state === 'RUNNING';
  8852. case 'resume': return status.state === 'PAUSE';
  8853. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8854. default: return false;
  8855. }
  8856. });
  8857. if (applicableIds.length === 0) {
  8858. showToast(t('printers.bulk.noneApplicable'), 'error');
  8859. setBulkActionPending(false);
  8860. setBulkConfirmAction(null);
  8861. return;
  8862. }
  8863. const apiCall = {
  8864. stop: api.stopPrint,
  8865. pause: api.pausePrint,
  8866. resume: api.resumePrint,
  8867. clearPlate: api.clearPlate,
  8868. clearHMS: api.clearHMSErrors,
  8869. }[action];
  8870. const results = await Promise.allSettled(
  8871. applicableIds.map(id => apiCall(id))
  8872. );
  8873. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8874. const failed = results.filter(r => r.status === 'rejected').length;
  8875. if (failed === 0) {
  8876. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8877. } else {
  8878. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8879. }
  8880. // Invalidate status queries for affected printers
  8881. applicableIds.forEach(id => {
  8882. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8883. });
  8884. setBulkActionPending(false);
  8885. setBulkConfirmAction(null);
  8886. }, [selectedPrinterIds, queryClient, showToast, t]);
  8887. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8888. // Actions that need confirmation
  8889. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8890. setBulkConfirmAction(action);
  8891. } else {
  8892. executeBulkAction(action);
  8893. }
  8894. }, [executeBulkAction]);
  8895. const toggleHideDisconnected = () => {
  8896. const newValue = !hideDisconnected;
  8897. setHideDisconnected(newValue);
  8898. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8899. };
  8900. const handleSortChange = (newSort: SortOption) => {
  8901. setSortBy(newSort);
  8902. localStorage.setItem('printerSortBy', newSort);
  8903. };
  8904. const handleStatusFilterChange = (value: string) => {
  8905. setStatusFilter(value);
  8906. localStorage.setItem('printerStatusFilter', value);
  8907. };
  8908. const handleLocationFilterChange = (value: string) => {
  8909. setLocationFilter(value);
  8910. localStorage.setItem('printerLocationFilter', value);
  8911. };
  8912. const toggleSortDirection = () => {
  8913. const newAsc = !sortAsc;
  8914. setSortAsc(newAsc);
  8915. localStorage.setItem('printerSortAsc', String(newAsc));
  8916. };
  8917. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8918. const getGridClasses = () => {
  8919. switch (cardSize) {
  8920. 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
  8921. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8922. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8923. case 4: return 'grid-cols-1'; // XL: single column, full width
  8924. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8925. }
  8926. };
  8927. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8928. // Increment version counter whenever a printer status cache entry is updated so
  8929. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8930. useEffect(() => {
  8931. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8932. if (
  8933. event.type === 'updated' &&
  8934. Array.isArray(event.query.queryKey) &&
  8935. event.query.queryKey[0] === 'printerStatus'
  8936. ) {
  8937. setStatusCacheVersion(v => v + 1);
  8938. }
  8939. });
  8940. return unsubscribe;
  8941. }, [queryClient]);
  8942. // Filter printers by search term, status, and location
  8943. const filteredPrinters = useMemo(() => {
  8944. if (!printers) return [];
  8945. let result = printers;
  8946. // Text search
  8947. if (search.trim()) {
  8948. const q = search.trim().toLowerCase();
  8949. result = result.filter(p =>
  8950. p.name.toLowerCase().includes(q) ||
  8951. (p.model || '').toLowerCase().includes(q) ||
  8952. (p.location || '').toLowerCase().includes(q) ||
  8953. (p.serial_number || '').toLowerCase().includes(q)
  8954. );
  8955. }
  8956. // Location filter
  8957. if (locationFilter !== 'all') {
  8958. result = result.filter(p => (p.location || '') === locationFilter);
  8959. }
  8960. // Status filter
  8961. if (statusFilter !== 'all') {
  8962. result = result.filter(p => {
  8963. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8964. if (!status?.connected) return statusFilter === 'offline';
  8965. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8966. switch (statusFilter) {
  8967. case 'printing': return status.state === 'RUNNING';
  8968. case 'paused': return status.state === 'PAUSE';
  8969. case 'finished': return status.state === 'FINISH';
  8970. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8971. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8972. case 'offline': return false; // Connected printers are never offline
  8973. default: return true;
  8974. }
  8975. });
  8976. }
  8977. return result;
  8978. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8979. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8980. // Derive unique locations for the location filter dropdown
  8981. const availableLocations = useMemo(() => {
  8982. if (!printers) return [];
  8983. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8984. }, [printers]);
  8985. // A saved location can outlive what it matched -- renamed, cleared, or the
  8986. // only printer that had it deleted. The dropdown is rendered only while some
  8987. // printer has a location, so a stale one would hide every printer *and* the
  8988. // control to undo it, leaving an empty page and no way back (#2833).
  8989. // Deliberately waits for `printers`: it is undefined while the query is in
  8990. // flight, and acting on the empty list that produces would throw the saved
  8991. // filter away every time the page loads.
  8992. useEffect(() => {
  8993. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8994. setLocationFilter('all');
  8995. localStorage.setItem('printerLocationFilter', 'all');
  8996. }, [printers, availableLocations, locationFilter]);
  8997. // Sort printers based on selected option
  8998. const sortedPrinters = useMemo(() => {
  8999. const sorted = [...filteredPrinters];
  9000. switch (sortBy) {
  9001. case 'name':
  9002. sorted.sort((a, b) => a.name.localeCompare(b.name));
  9003. break;
  9004. case 'model':
  9005. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  9006. break;
  9007. case 'location':
  9008. // Sort by location, with ungrouped printers last
  9009. sorted.sort((a, b) => {
  9010. const locA = a.location || '';
  9011. const locB = b.location || '';
  9012. if (!locA && locB) return 1;
  9013. if (locA && !locB) return -1;
  9014. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  9015. });
  9016. break;
  9017. case 'status':
  9018. // Sort by status: HMS errors > printing > idle > offline
  9019. sorted.sort((a, b) => {
  9020. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  9021. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  9022. const getPriority = (s: typeof statusA) => {
  9023. if (!s?.connected) return 3; // offline
  9024. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  9025. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  9026. if (s.state === 'RUNNING') return 1; // printing
  9027. return 2; // idle
  9028. };
  9029. return getPriority(statusA) - getPriority(statusB);
  9030. });
  9031. break;
  9032. case 'eta':
  9033. sorted.sort((a, b) => {
  9034. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  9035. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  9036. const tier = (s: typeof statusA) => {
  9037. if (!s?.connected) return 3; // offline last
  9038. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  9039. if (s.state === 'RUNNING') return 1; // printing without ETA
  9040. return 2; // idle
  9041. };
  9042. const ta = tier(statusA);
  9043. const tb = tier(statusB);
  9044. if (ta !== tb) return ta - tb;
  9045. if (ta === 0) {
  9046. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  9047. if (diff !== 0) return diff;
  9048. }
  9049. return a.name.localeCompare(b.name);
  9050. });
  9051. break;
  9052. }
  9053. // Apply ascending/descending
  9054. if (!sortAsc) {
  9055. sorted.reverse();
  9056. }
  9057. return sorted;
  9058. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  9059. const selectAll = useCallback(() => {
  9060. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  9061. setIsSelectionMode(true);
  9062. }, [sortedPrinters]);
  9063. const selectByState = useCallback((state: PrinterState) => {
  9064. setSelectedPrinterIds(prev => {
  9065. const next = new Set(prev);
  9066. sortedPrinters.forEach(p => {
  9067. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  9068. if (classifyPrinterStatus(status) === state) next.add(p.id);
  9069. });
  9070. return next;
  9071. });
  9072. setIsSelectionMode(true);
  9073. }, [sortedPrinters, queryClient]);
  9074. const selectByLocation = useCallback((location: string) => {
  9075. setSelectedPrinterIds(prev => {
  9076. const next = new Set(prev);
  9077. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9078. return next;
  9079. });
  9080. setIsSelectionMode(true);
  9081. }, [sortedPrinters]);
  9082. const selectByModel = useCallback((model: string) => {
  9083. setSelectedPrinterIds(prev => {
  9084. const next = new Set(prev);
  9085. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9086. return next;
  9087. });
  9088. setIsSelectionMode(true);
  9089. }, [sortedPrinters]);
  9090. const toggleSectionCollapse = useCallback((key: string) => {
  9091. setCollapsedSections(prev => {
  9092. const next = { ...prev, [key]: !prev[key] };
  9093. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9094. return next;
  9095. });
  9096. }, []);
  9097. // Group printers when sorted by location, status, or model
  9098. const groupedPrinters = useMemo(() => {
  9099. if (sortBy === 'name' || sortBy === 'eta') return null;
  9100. const groups: Record<string, typeof sortedPrinters> = {};
  9101. if (sortBy === 'location') {
  9102. sortedPrinters.forEach(printer => {
  9103. const location = printer.location || 'Ungrouped';
  9104. if (!groups[location]) groups[location] = [];
  9105. groups[location].push(printer);
  9106. });
  9107. } else if (sortBy === 'model') {
  9108. sortedPrinters.forEach(printer => {
  9109. const model = printer.model || 'Unknown';
  9110. if (!groups[model]) groups[model] = [];
  9111. groups[model].push(printer);
  9112. });
  9113. } else if (sortBy === 'status') {
  9114. sortedPrinters.forEach(printer => {
  9115. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9116. const group = classifyPrinterStatus(status);
  9117. if (!groups[group]) groups[group] = [];
  9118. groups[group].push(printer);
  9119. });
  9120. }
  9121. return groups;
  9122. // 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
  9123. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9124. const toolbarRef = useRef<HTMLDivElement>(null);
  9125. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9126. const expandedToolbarWidthRef = useRef(0);
  9127. const [compactToolbar, setCompactToolbar] = useState(false);
  9128. const measureToolbar = useCallback(() => {
  9129. const toolbar = toolbarRef.current;
  9130. if (!toolbar) return;
  9131. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9132. if (measuredControlsWidth) {
  9133. expandedToolbarWidthRef.current = measuredControlsWidth;
  9134. }
  9135. const searchMinimumWidth = 220;
  9136. const gapWidth = 8;
  9137. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9138. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9139. }, []);
  9140. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9141. useLayoutEffect(() => {
  9142. measureToolbar();
  9143. const toolbar = toolbarRef.current;
  9144. if (!toolbar) return;
  9145. if (typeof ResizeObserver === 'undefined') {
  9146. window.addEventListener('resize', measureToolbar);
  9147. return () => window.removeEventListener('resize', measureToolbar);
  9148. }
  9149. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9150. resizeObserver.observe(toolbar);
  9151. window.addEventListener('resize', measureToolbar);
  9152. return () => {
  9153. resizeObserver.disconnect();
  9154. window.removeEventListener('resize', measureToolbar);
  9155. };
  9156. }, [
  9157. measureToolbar,
  9158. printers?.length,
  9159. availableLocations.length,
  9160. hideDisconnected,
  9161. smartPlugCount,
  9162. ]);
  9163. const renderFilterControls = (inMenu = false) => (
  9164. <>
  9165. {/* Status filter */}
  9166. {printers && printers.length > 0 && (
  9167. <ToolbarDropdown
  9168. value={statusFilter}
  9169. onChange={handleStatusFilterChange}
  9170. fullWidth={inMenu}
  9171. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9172. />
  9173. )}
  9174. {/* Location filter — only shown when at least one printer has a location */}
  9175. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9176. <ToolbarDropdown
  9177. value={locationFilter}
  9178. onChange={handleLocationFilterChange}
  9179. fullWidth={inMenu}
  9180. options={[
  9181. { value: 'all', label: t('printers.filter.allLocations') },
  9182. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9183. ]}
  9184. />
  9185. )}
  9186. <button
  9187. type="button"
  9188. onClick={toggleHideDisconnected}
  9189. aria-pressed={hideDisconnected}
  9190. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9191. hideDisconnected
  9192. ? 'bg-bambu-green border-bambu-green text-white'
  9193. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9194. }`}
  9195. >
  9196. {t('printers.hideOffline')}
  9197. </button>
  9198. </>
  9199. );
  9200. const renderViewControls = (inMenu = false) => (
  9201. <>
  9202. {/* Sort dropdown */}
  9203. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9204. <ToolbarDropdown<SortOption>
  9205. value={sortBy}
  9206. onChange={handleSortChange}
  9207. fullWidth={inMenu}
  9208. options={[
  9209. { value: 'name', label: t('printers.sort.name') },
  9210. { value: 'status', label: t('printers.sort.status') },
  9211. { value: 'model', label: t('printers.sort.model') },
  9212. { value: 'location', label: t('printers.sort.location') },
  9213. { value: 'eta', label: t('printers.sort.eta') },
  9214. ]}
  9215. />
  9216. <button
  9217. onClick={toggleSortDirection}
  9218. 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"
  9219. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9220. >
  9221. {sortAsc ? (
  9222. <ArrowUp className="w-4 h-4 text-white" />
  9223. ) : (
  9224. <ArrowDown className="w-4 h-4 text-white" />
  9225. )}
  9226. </button>
  9227. <RouterLink
  9228. to="/printer-locations"
  9229. 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"
  9230. title={t('printers.locations.title')}
  9231. aria-label={t('printers.locations.title')}
  9232. >
  9233. <Box className="w-4 h-4 text-bambu-green" />
  9234. </RouterLink>
  9235. </div>
  9236. {/* Page view toggle: Cards / Cam Wall */}
  9237. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9238. <button
  9239. type="button"
  9240. onClick={() => {
  9241. setPageView('cards');
  9242. localStorage.setItem('printerPageView', 'cards');
  9243. }}
  9244. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9245. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9246. }`}
  9247. title={t('printers.pageView.cards')}
  9248. aria-pressed={pageView === 'cards'}
  9249. >
  9250. <LayoutGrid className="w-3.5 h-3.5" />
  9251. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9252. </button>
  9253. <button
  9254. type="button"
  9255. onClick={() => {
  9256. setPageView('camwall');
  9257. localStorage.setItem('printerPageView', 'camwall');
  9258. }}
  9259. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9260. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9261. }`}
  9262. title={t('printers.pageView.camWall')}
  9263. aria-pressed={pageView === 'camwall'}
  9264. disabled={!hasPermission('camera:view')}
  9265. >
  9266. <MonitorPlay className="w-3.5 h-3.5" />
  9267. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9268. </button>
  9269. </div>
  9270. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9271. view, and the page a kiosk token points at. Only offered once the wall
  9272. is the active view, so it doesn't compete with the toggle above. */}
  9273. {pageView === 'camwall' && hasPermission('camera:view') && (
  9274. <RouterLink
  9275. to="/camwall"
  9276. className={`flex h-8 items-center gap-1 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 ${inMenu ? 'w-full justify-center' : ''}`}
  9277. title={t('printers.pageView.openCamWallPage')}
  9278. >
  9279. <ExternalLink className="w-3.5 h-3.5" />
  9280. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9281. </RouterLink>
  9282. )}
  9283. {/* Card size selector */}
  9284. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9285. {cardSizeLabels.map((label, index) => {
  9286. const size = index + 1;
  9287. const isSelected = (pageView === 'camwall' ? camWallTileSize : cardSize) === size;
  9288. return (
  9289. <button
  9290. key={label}
  9291. onClick={() => {
  9292. if (pageView === 'camwall') {
  9293. setCamWallTileSize(size);
  9294. localStorage.setItem('camWallTileSize', String(size));
  9295. return;
  9296. }
  9297. setCompactDrilldownPrinterId(null);
  9298. setCardSize(size);
  9299. localStorage.setItem('printerCardSize', String(size));
  9300. }}
  9301. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9302. index === 0 ? 'rounded-l-lg' : ''
  9303. } ${
  9304. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9305. } ${
  9306. isSelected
  9307. ? 'bg-bambu-green text-white'
  9308. : 'text-white hover:bg-bambu-dark-tertiary'
  9309. }`}
  9310. title={t(`printers.${pageView === 'camwall' ? 'camWall.tileSize' : 'cardSize'}.${['small', 'medium', 'large', 'extraLarge'][index]}`)}
  9311. >
  9312. {label}
  9313. </button>
  9314. );
  9315. })}
  9316. </div>
  9317. </>
  9318. );
  9319. const renderActionControls = (inMenu = false) => (
  9320. <>
  9321. {/* Bulk select toggle */}
  9322. <button
  9323. onClick={() => {
  9324. if (selectionMode) clearSelection();
  9325. else setIsSelectionMode(true);
  9326. }}
  9327. 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' : ''} ${
  9328. selectionMode
  9329. ? 'bg-bambu-green border-bambu-green text-white'
  9330. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9331. }`}
  9332. title={t('printers.bulk.select')}
  9333. disabled={!hasPermission('printers:control')}
  9334. >
  9335. <CheckSquare className="w-4 h-4" />
  9336. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9337. </button>
  9338. {/* Power dropdown for offline printers with smart plugs */}
  9339. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9340. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9341. <button
  9342. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9343. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9344. inMenu
  9345. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9346. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9347. }`}
  9348. >
  9349. <span className="flex items-center gap-1.5">
  9350. <Power className="w-4 h-4" />
  9351. {t('printers.powerOn')}
  9352. </span>
  9353. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9354. </button>
  9355. {showPowerDropdown && (
  9356. <>
  9357. {/* Backdrop to close dropdown */}
  9358. <div
  9359. className="fixed inset-0 z-10"
  9360. onClick={() => setShowPowerDropdown(false)}
  9361. />
  9362. <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">
  9363. <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">
  9364. {t('printers.offlinePrintersWithPlugs')}
  9365. </div>
  9366. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9367. <PowerDropdownItem
  9368. key={printer.id}
  9369. printer={printer}
  9370. plug={smartPlugByPrinter[printer.id]}
  9371. onPowerOn={(plugId) => {
  9372. setPoweringOn(plugId);
  9373. powerOnMutation.mutate(plugId);
  9374. }}
  9375. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9376. />
  9377. ))}
  9378. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9379. <div className="px-3 py-2 text-sm text-bambu-gray">
  9380. No printers with smart plugs
  9381. </div>
  9382. )}
  9383. </div>
  9384. </>
  9385. )}
  9386. </div>
  9387. )}
  9388. <Button
  9389. onClick={() => setShowAddModal(true)}
  9390. disabled={!hasPermission('printers:create')}
  9391. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9392. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9393. >
  9394. <Plus className="w-4 h-4" />
  9395. {t('printers.addPrinter')}
  9396. </Button>
  9397. </>
  9398. );
  9399. return (
  9400. <div className="p-4 md:p-8">
  9401. <div className="space-y-3 mb-6">
  9402. <div>
  9403. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9404. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9405. {t('printers.title')}
  9406. </h1>
  9407. <StatusSummaryBar printers={printers} />
  9408. </div>
  9409. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9410. {/* Only show search bar when printers exist */}
  9411. {printers && printers.length > 0 && (
  9412. <div className="relative min-w-0 flex-1">
  9413. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9414. <input
  9415. type="search"
  9416. name="printer-search"
  9417. autoComplete="off"
  9418. data-1p-ignore
  9419. data-lpignore="true"
  9420. value={search}
  9421. onChange={(e) => setSearch(e.target.value)}
  9422. placeholder={t('printers.search')}
  9423. aria-label={t('printers.search')}
  9424. 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"
  9425. />
  9426. {search && (
  9427. <button
  9428. type="button"
  9429. aria-label={t('common.clear')}
  9430. onClick={() => setSearch('')}
  9431. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9432. >
  9433. <X className="w-4 h-4" />
  9434. </button>
  9435. )}
  9436. </div>
  9437. )}
  9438. <div
  9439. ref={expandedToolbarControlsRef}
  9440. aria-hidden={compactToolbar}
  9441. inert={compactToolbar}
  9442. 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`}
  9443. >
  9444. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9445. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9446. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9447. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9448. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9449. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9450. </div>
  9451. {compactToolbar && (
  9452. <div className="ml-auto flex items-center justify-end gap-1">
  9453. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9454. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9455. </ToolbarMenu>
  9456. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9457. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9458. </ToolbarMenu>
  9459. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9460. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9461. </ToolbarMenu>
  9462. </div>
  9463. )}
  9464. </div>
  9465. </div>
  9466. {isLoading ? (
  9467. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9468. ) : printers?.length === 0 ? (
  9469. <Card>
  9470. <CardContent className="text-center py-12">
  9471. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9472. <Button
  9473. onClick={() => setShowAddModal(true)}
  9474. disabled={!hasPermission('printers:create')}
  9475. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9476. >
  9477. <Plus className="w-4 h-4" />
  9478. {t('printers.addPrinter')}
  9479. </Button>
  9480. </CardContent>
  9481. </Card>
  9482. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9483. <Card>
  9484. <CardContent className="text-center py-12">
  9485. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9486. </CardContent>
  9487. </Card>
  9488. ) : pageView === 'camwall' ? (
  9489. <CameraWall
  9490. printers={sortedPrinters}
  9491. maxLive={camWallMaxLive}
  9492. snapshotIntervalSec={camWallSnapshotSec}
  9493. tileSize={camWallTileSize}
  9494. onTileClick={(id, name) => {
  9495. // A wall tile has no room for a split button, so it follows the
  9496. // mode the card buttons last chose.
  9497. if (cameraViewMode === 'embedded') {
  9498. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9499. } else {
  9500. openCameraWindow(id);
  9501. }
  9502. }}
  9503. statusMode={camWallStatusMode}
  9504. onChangeMaxLive={(next) => {
  9505. setCamWallMaxLive(next);
  9506. localStorage.setItem('camWallMaxLive', String(next));
  9507. }}
  9508. onChangeSnapshotIntervalSec={(next) => {
  9509. setCamWallSnapshotSec(next);
  9510. localStorage.setItem('camWallSnapshotSec', String(next));
  9511. }}
  9512. onChangeStatusMode={(next) => {
  9513. setCamWallStatusMode(next);
  9514. localStorage.setItem('camWallStatusMode', next);
  9515. }}
  9516. />
  9517. ) : groupedPrinters ? (
  9518. /* Grouped view (location, status, or model) */
  9519. <div className="space-y-6">
  9520. {(() => {
  9521. const keys = sortBy === 'status'
  9522. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9523. : Object.keys(groupedPrinters);
  9524. // For status grouping, asc/desc flips the fixed priority order
  9525. // (asc = error→offline, desc = offline→error). This matches the
  9526. // sort-toggle behaviour for other groupings.
  9527. return (sortAsc ? keys : [...keys].reverse());
  9528. })().map((groupKey) => {
  9529. const groupPrinters = groupedPrinters[groupKey];
  9530. const collapseKey = `${sortBy}:${groupKey}`;
  9531. const isOpen = !collapsedSections[collapseKey];
  9532. const dot = sortBy === 'status'
  9533. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9534. : 'bg-bambu-green';
  9535. const label = sortBy === 'status'
  9536. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9537. : groupKey;
  9538. return (
  9539. <Collapsible
  9540. key={groupKey}
  9541. open={isOpen}
  9542. onToggle={() => toggleSectionCollapse(collapseKey)}
  9543. summaryClassName="py-1"
  9544. summary={
  9545. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9546. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9547. {label}
  9548. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9549. {selectionMode && (
  9550. <button
  9551. onClick={(e) => {
  9552. e.stopPropagation();
  9553. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9554. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9555. else if (sortBy === 'model') selectByModel(groupKey);
  9556. }}
  9557. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9558. >
  9559. {t('printers.bulk.selectAll')}
  9560. </button>
  9561. )}
  9562. </h2>
  9563. }
  9564. >
  9565. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9566. {groupPrinters.map((printer) => (
  9567. <PrinterCard
  9568. key={printer.id}
  9569. printer={printer}
  9570. hideIfDisconnected={hideDisconnected}
  9571. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9572. viewMode={viewMode}
  9573. cardSize={cardSize}
  9574. amsThresholds={settings ? {
  9575. humidityGood: Number(settings.ams_humidity_good) || 40,
  9576. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9577. tempGood: Number(settings.ams_temp_good) || 28,
  9578. tempFair: Number(settings.ams_temp_fair) || 35,
  9579. } : undefined}
  9580. spoolmanEnabled={spoolmanEnabled}
  9581. hasUnlinkedSpools={hasUnlinkedSpools}
  9582. linkedSpools={linkedSpools}
  9583. spoolmanUrl={spoolmanStatus?.url}
  9584. spoolmanSyncMode={spoolmanSyncMode}
  9585. onGetAssignment={getAssignment}
  9586. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9587. spoolmanSpools={spoolmanSpools}
  9588. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9589. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9590. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9591. timeFormat={settings?.time_format || 'system'}
  9592. cameraViewMode={cameraViewMode}
  9593. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9594. onSelectCameraViewMode={selectCameraViewMode}
  9595. checkPrinterFirmware={firmwareChecksOn}
  9596. dryingPresets={effectiveDryingPresets}
  9597. nozzleTempPresets={effectiveNozzleTempPresets}
  9598. bedTempPresets={effectiveBedTempPresets}
  9599. chamberTempPresets={effectiveChamberTempPresets}
  9600. fanSpeedPresets={effectiveFanSpeedPresets}
  9601. requirePlateClear={settings?.require_plate_clear === true}
  9602. selectionMode={selectionMode}
  9603. isSelected={selectedPrinterIds.has(printer.id)}
  9604. onToggleSelect={toggleSelect}
  9605. onOpenCompactCard={openCompactCard}
  9606. aiDetectionEnabled={isAiMonitored(printer.id)}
  9607. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9608. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9609. />
  9610. ))}
  9611. </div>
  9612. </Collapsible>
  9613. );
  9614. })}
  9615. </div>
  9616. ) : (
  9617. /* Regular grid view */
  9618. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9619. {sortedPrinters.map((printer) => (
  9620. <PrinterCard
  9621. key={printer.id}
  9622. printer={printer}
  9623. hideIfDisconnected={hideDisconnected}
  9624. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9625. viewMode={viewMode}
  9626. cardSize={cardSize}
  9627. spoolmanEnabled={spoolmanEnabled}
  9628. hasUnlinkedSpools={hasUnlinkedSpools}
  9629. linkedSpools={linkedSpools}
  9630. spoolmanUrl={spoolmanStatus?.url}
  9631. spoolmanSyncMode={spoolmanSyncMode}
  9632. onGetAssignment={getAssignment}
  9633. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9634. spoolmanSpools={spoolmanSpools}
  9635. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9636. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9637. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9638. amsThresholds={settings ? {
  9639. humidityGood: Number(settings.ams_humidity_good) || 40,
  9640. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9641. tempGood: Number(settings.ams_temp_good) || 28,
  9642. tempFair: Number(settings.ams_temp_fair) || 35,
  9643. } : undefined}
  9644. timeFormat={settings?.time_format || 'system'}
  9645. cameraViewMode={cameraViewMode}
  9646. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9647. onSelectCameraViewMode={selectCameraViewMode}
  9648. checkPrinterFirmware={firmwareChecksOn}
  9649. dryingPresets={effectiveDryingPresets}
  9650. nozzleTempPresets={effectiveNozzleTempPresets}
  9651. bedTempPresets={effectiveBedTempPresets}
  9652. chamberTempPresets={effectiveChamberTempPresets}
  9653. fanSpeedPresets={effectiveFanSpeedPresets}
  9654. requirePlateClear={settings?.require_plate_clear === true}
  9655. selectionMode={selectionMode}
  9656. isSelected={selectedPrinterIds.has(printer.id)}
  9657. onToggleSelect={toggleSelect}
  9658. onOpenCompactCard={openCompactCard}
  9659. aiDetectionEnabled={isAiMonitored(printer.id)}
  9660. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9661. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9662. />
  9663. ))}
  9664. </div>
  9665. )}
  9666. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9667. <button
  9668. type="button"
  9669. onClick={returnToCompactCards}
  9670. 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}`}
  9671. title={t('common.back', 'Back')}
  9672. >
  9673. <ArrowLeft className="w-4 h-4" />
  9674. {t('common.back', 'Back')}
  9675. </button>
  9676. )}
  9677. {showAddModal && (
  9678. <AddPrinterModal
  9679. onClose={() => setShowAddModal(false)}
  9680. onAdd={(data) => addMutation.mutate(data)}
  9681. existingSerials={printers?.map(p => p.serial_number) || []}
  9682. />
  9683. )}
  9684. {/* Bulk selection toolbar */}
  9685. {selectionMode && printers && (
  9686. <BulkPrinterToolbar
  9687. selectedIds={selectedPrinterIds}
  9688. printers={printers}
  9689. onClose={clearSelection}
  9690. onSelectAll={selectAll}
  9691. onSelectByLocation={selectByLocation}
  9692. onSelectByState={selectByState}
  9693. onAction={handleBulkAction}
  9694. actionPending={bulkActionPending}
  9695. />
  9696. )}
  9697. {/* Bulk action confirmation modals */}
  9698. {bulkConfirmAction === 'stop' && (
  9699. <ConfirmModal
  9700. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9701. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9702. confirmText={t('printers.bulk.confirm.stopButton')}
  9703. variant="danger"
  9704. isLoading={bulkActionPending}
  9705. onConfirm={() => executeBulkAction('stop')}
  9706. onCancel={() => setBulkConfirmAction(null)}
  9707. />
  9708. )}
  9709. {bulkConfirmAction === 'pause' && (
  9710. <ConfirmModal
  9711. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9712. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9713. confirmText={t('printers.bulk.confirm.pauseButton')}
  9714. isLoading={bulkActionPending}
  9715. onConfirm={() => executeBulkAction('pause')}
  9716. onCancel={() => setBulkConfirmAction(null)}
  9717. />
  9718. )}
  9719. {bulkConfirmAction === 'clearPlate' && (
  9720. <ConfirmModal
  9721. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9722. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9723. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9724. isLoading={bulkActionPending}
  9725. onConfirm={() => executeBulkAction('clearPlate')}
  9726. onCancel={() => setBulkConfirmAction(null)}
  9727. />
  9728. )}
  9729. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9730. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9731. <EmbeddedCameraViewer
  9732. key={camera.id}
  9733. printerId={camera.id}
  9734. printerName={camera.name}
  9735. viewerIndex={index}
  9736. onClose={() => setEmbeddedCameraPrinters(prev => {
  9737. const next = new Map(prev);
  9738. next.delete(camera.id);
  9739. return next;
  9740. })}
  9741. />
  9742. ))}
  9743. </div>
  9744. );
  9745. }