PrintersPage.tsx 497 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { formatPrintName } from '../utils/printName';
  5. import { isBedSlinger } from '../utils/bedSlinger';
  6. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  7. import {
  8. openCameraWindow,
  9. readStoredCameraViewMode,
  10. storeCameraViewMode,
  11. type CameraViewMode,
  12. } from '../utils/camera';
  13. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  14. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  15. import {
  16. isExternalSpoolHidden,
  17. setExternalSpoolHidden as persistExternalSpoolHidden,
  18. } from '../utils/printerCardPrefs';
  19. import {
  20. BED_TEMP_DEFAULTS,
  21. CHAMBER_TEMP_DEFAULTS,
  22. FAN_SPEED_DEFAULTS,
  23. NOZZLE_TEMP_DEFAULTS,
  24. buildPresetOptions,
  25. parsePresetTriple,
  26. } from '../utils/temperatureFanPresets';
  27. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  28. // covers header + filament select + temp slider + duration + rotate-tray
  29. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  30. // earlier); under-estimating leaves the popover clipped off the bottom (the
  31. // original bug at #1447).
  32. const DRYING_POPOVER_WIDTH = 240;
  33. // Height in "now" mode plus the tallest start-mode control; a conservative
  34. // over-estimate just flips the popover above the trigger sooner.
  35. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  36. // Delay presets for the "After delay" drying start mode, in minutes.
  37. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  38. // Every printer card reads the same fleet-wide scheduled-drying list.
  39. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  40. // Why a due run has not started yet: every waiting_reason the scheduler can
  41. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  42. // for ..." with no hint why nothing is happening.
  43. const WAITING_REASON_KEYS: Record<string, string> = {
  44. ams_power_required: 'printers.drying.powerRequired',
  45. ams_retract_filament: 'printers.drying.retractFilament',
  46. ams_blocked: 'printers.drying.cannotDryNow',
  47. ams_not_found: 'printers.drying.waitingAmsNotFound',
  48. printer_offline: 'printers.drying.waitingOffline',
  49. printer_busy: 'printers.drying.waitingPrinterBusy',
  50. already_drying: 'printers.drying.waitingAlreadyDrying',
  51. interrupted: 'printers.drying.waitingInterrupted',
  52. };
  53. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  54. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  55. }
  56. // Why a scheduled drying failed, by the code the scheduler stores. A row with
  57. // no code (failed before codes existed) or an unknown one shows the backend's
  58. // English error_message instead.
  59. const FAILED_REASON_KEYS: Record<string, string> = {
  60. screen_only: 'printers.drying.screenOnly',
  61. unsupported: 'printers.drying.notSupported',
  62. did_not_start: 'printers.drying.scheduleFailedDidNotStart',
  63. };
  64. function failedReasonKey(code: string | null | undefined): string | undefined {
  65. return code ? FAILED_REASON_KEYS[code] : undefined;
  66. }
  67. // Which cannot-dry code to name when the firmware reports several at once.
  68. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  69. // button's tooltip and a scheduled row's waiting reason describe one blocked
  70. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  71. // left at the outlet, and both need the user to go and do something. The rest
  72. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  73. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  74. const codes = (reasons ?? []).map(r => Number(r));
  75. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  76. if (codes.includes(3)) return 'printers.drying.retractFilament';
  77. return 'printers.drying.cannotDryNow';
  78. }
  79. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  80. import { useTranslation } from 'react-i18next';
  81. import { useTheme } from '../contexts/ThemeContext';
  82. import { useAuth } from '../contexts/AuthContext';
  83. import {
  84. Plus,
  85. Link,
  86. Unlink,
  87. Signal,
  88. Clock,
  89. MoreVertical,
  90. Trash2,
  91. RefreshCw,
  92. RotateCw,
  93. Box,
  94. HardDrive,
  95. AlertTriangle,
  96. AlertCircle,
  97. Terminal,
  98. Power,
  99. Zap,
  100. Wrench,
  101. ChevronDown,
  102. Eye,
  103. EyeOff,
  104. Filter,
  105. Pencil,
  106. ArrowLeft,
  107. ArrowRight,
  108. ArrowUp,
  109. ArrowDown,
  110. Layers,
  111. Video,
  112. Search,
  113. Loader2,
  114. Square,
  115. Pause,
  116. Play,
  117. X,
  118. Fan,
  119. Wind,
  120. AirVent,
  121. Download,
  122. ScanSearch,
  123. CheckCircle,
  124. CheckSquare,
  125. XCircle,
  126. User,
  127. Home,
  128. Printer as PrinterIcon,
  129. Info,
  130. Cable,
  131. Flame,
  132. Hourglass,
  133. Repeat,
  134. Snowflake,
  135. Gauge,
  136. DoorOpen,
  137. DoorClosed,
  138. Move,
  139. LogIn,
  140. LogOut,
  141. MoreHorizontal,
  142. SlidersHorizontal,
  143. Stethoscope,
  144. ScanEye,
  145. LineChart as LineChartIcon,
  146. LayoutGrid,
  147. MonitorPlay,
  148. ExternalLink,
  149. PictureInPicture2,
  150. ThumbsUp,
  151. ThumbsDown,
  152. } from 'lucide-react';
  153. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  154. // Aliased: lucide-react already exports a `Link` icon into this module.
  155. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  156. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  157. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  158. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  159. import { Card, CardContent } from '../components/Card';
  160. import { Button } from '../components/Button';
  161. import { ConfirmModal } from '../components/ConfirmModal';
  162. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  163. import { FileManagerModal } from '../components/FileManagerModal';
  164. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  165. import { CameraWall } from '../components/CameraWall';
  166. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  167. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  168. import { HMSErrorModal, filterKnownHMSErrors, isSevereHMSError } from '../components/HMSErrorModal';
  169. import { AiDetectionModal } from '../components/AiDetectionModal';
  170. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  171. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  172. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  173. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  174. import { AmsBackupModal } from '../components/AmsBackupModal';
  175. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  176. import type { HeaterSensorKind } from '../api/client';
  177. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  178. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  179. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  180. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  181. import { useToast } from '../contexts/ToastContext';
  182. import { ChamberLight } from '../components/icons/ChamberLight';
  183. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  184. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  185. import { FileUploadModal } from '../components/FileUploadModal';
  186. import { PrintModal } from '../components/PrintModal';
  187. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  188. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  189. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  190. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  191. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  192. import { Collapsible } from '../components/Collapsible';
  193. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  194. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  195. import { NumberInput } from '../components/NumberInput';
  196. // The status filter's options, and the only values it may hold. One list so a
  197. // saved filter cannot be validated against a set the dropdown has since moved
  198. // on from (#2833). Labels stay literal so they remain greppable.
  199. const STATUS_FILTER_OPTIONS = [
  200. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  201. { value: 'printing', labelKey: 'printers.status.printing' },
  202. { value: 'paused', labelKey: 'printers.status.paused' },
  203. { value: 'idle', labelKey: 'printers.status.idle' },
  204. { value: 'finished', labelKey: 'printers.status.finished' },
  205. { value: 'error', labelKey: 'printers.status.error' },
  206. { value: 'offline', labelKey: 'printers.status.offline' },
  207. ] as const;
  208. function isKnownStatusFilter(value: string | null): boolean {
  209. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  210. }
  211. export interface SpoolmanSlotAssignmentRow {
  212. printer_id: number;
  213. ams_id: number;
  214. tray_id: number;
  215. spoolman_spool_id: number;
  216. }
  217. // Color names resolve via getColorName() which reads the backend color_catalog
  218. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  219. // Format K value with 3 decimal places, default to 0.020 if null
  220. function formatKValue(k: number | null | undefined): string {
  221. const value = k ?? 0.020;
  222. return value.toFixed(3);
  223. }
  224. // K-profile value shown on the slot card itself (#2532) rather than only inside
  225. // the hover popup, the way BambuStudio shows it per slot.
  226. //
  227. // `k` arrives already gated on the slot being loaded; falsy means the printer
  228. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  229. // missing value, which is captioned inside the hover card but would read as a
  230. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  231. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  232. // reported 0 makes that expression evaluate to the number 0, and React renders
  233. // numbers, putting a bare "0" under the material name.
  234. //
  235. // `reserve` holds the row's height open on the slots without a value whenever
  236. // some other slot on the same card has one, so every fill bar stays on one line.
  237. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  238. const { t } = useTranslation();
  239. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  240. if (!k) {
  241. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  242. }
  243. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  244. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  245. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  246. // family per browser and so measured differently in Safari.
  247. return (
  248. <div className={className} title={t('ams.kFactor')}>
  249. {t('ams.kFactorShort')} {formatKValue(k)}
  250. </div>
  251. );
  252. }
  253. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  254. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  255. const { mode } = useTheme();
  256. const { t } = useTranslation();
  257. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  258. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  259. return (
  260. <span
  261. 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"
  262. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  263. title={side === 'L' ? t('common.left') : t('common.right')}
  264. >
  265. {side}
  266. </span>
  267. );
  268. }
  269. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  270. // deliberately a different colour, because it means something different: this
  271. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  272. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  273. const { mode } = useTheme();
  274. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  275. return (
  276. <span
  277. 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"
  278. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  279. title={title}
  280. >
  281. {FTS_INLET_SIDE[inlet]}
  282. </span>
  283. );
  284. }
  285. /**
  286. * Which side indicator, if any, belongs on an AMS card header.
  287. *
  288. * Three sources, in descending authority:
  289. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  290. * through the switch, so the inlet is the only meaningful label.
  291. * 2. A real extruder id from ams_extruder_map.
  292. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  293. * never reported a map. This one is only a guess, and it is suppressed
  294. * when a switch is installed: with an FTS every unit reports extruder
  295. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  296. * nothing but their unit numbers.
  297. */
  298. function amsSideBadge(
  299. amsId: number,
  300. amsExtruderMap: Record<string, number>,
  301. amsSwitchInlet: Record<string, 'A' | 'B'>,
  302. ftsInstalled: boolean
  303. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  304. const inlet = amsSwitchInlet[String(amsId)];
  305. if (inlet) return { kind: 'inlet', inlet };
  306. const mapped = amsExtruderMap[String(amsId)];
  307. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  308. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  309. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  310. return null;
  311. }
  312. // Expand nozzle type codes to material names
  313. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  314. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  315. function nozzleTypeName(type: string, t: (key: string) => string): string {
  316. if (!type) return '';
  317. // Full text names (from main nozzle info)
  318. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  319. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  320. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  321. // 4-char codes (e.g. "HS01"): last 2 digits = material
  322. if (type.length >= 4) {
  323. const material = type.slice(2, 4);
  324. if (material === '00') return t('printers.nozzleStainlessSteel');
  325. if (material === '01') return t('printers.nozzleHardenedSteel');
  326. if (material === '05') return t('printers.nozzleTungstenCarbide');
  327. }
  328. // 2-digit numeric codes
  329. if (type === '00') return t('printers.nozzleStainlessSteel');
  330. if (type === '01') return t('printers.nozzleHardenedSteel');
  331. if (type === '05') return t('printers.nozzleTungstenCarbide');
  332. // 2-char alpha codes: H prefix = hardened steel
  333. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  334. return type;
  335. }
  336. // Parse flow type from nozzle type code
  337. // HH = high flow, HS = standard/normal
  338. function nozzleFlowName(type: string, t: (key: string) => string): string {
  339. if (!type) return '';
  340. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  341. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  342. return '';
  343. }
  344. // Per-slot hover card for nozzle rack
  345. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  346. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  347. slot: import('../api/client').NozzleRackSlot;
  348. index: number;
  349. activeStatus?: boolean;
  350. filamentName?: string;
  351. children: React.ReactNode;
  352. }) {
  353. const { t } = useTranslation();
  354. const [isVisible, setIsVisible] = useState(false);
  355. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  356. const triggerRef = useRef<HTMLDivElement>(null);
  357. const cardRef = useRef<HTMLDivElement>(null);
  358. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  359. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  360. const isMounted = slot.stat === 1;
  361. useEffect(() => {
  362. if (isVisible && triggerRef.current && cardRef.current) {
  363. const triggerRect = triggerRef.current.getBoundingClientRect();
  364. const cardHeight = cardRef.current.offsetHeight;
  365. const headerHeight = 56;
  366. const spaceAbove = triggerRect.top - headerHeight;
  367. const spaceBelow = window.innerHeight - triggerRect.bottom;
  368. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  369. setPosition('bottom');
  370. } else {
  371. setPosition('top');
  372. }
  373. }
  374. }, [isVisible]);
  375. const handleMouseEnter = () => {
  376. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  377. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  378. };
  379. const handleMouseLeave = () => {
  380. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  381. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  382. };
  383. useEffect(() => {
  384. return () => {
  385. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  386. };
  387. }, []);
  388. const filamentCss = parseFilamentColor(slot.filament_color);
  389. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  390. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  391. return (
  392. <div
  393. ref={triggerRef}
  394. className="relative"
  395. onMouseEnter={handleMouseEnter}
  396. onMouseLeave={handleMouseLeave}
  397. >
  398. {children}
  399. {isVisible && (
  400. <div
  401. ref={cardRef}
  402. className={`
  403. absolute left-1/2 -translate-x-1/2 z-50
  404. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  405. animate-in fade-in-0 zoom-in-95 duration-150
  406. `}
  407. style={{ maxWidth: 'calc(100vw - 24px)' }}
  408. >
  409. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  410. {isEmpty ? (
  411. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  412. Slot {index + 1} — Empty
  413. </div>
  414. ) : (
  415. <div className="p-2.5 space-y-1.5">
  416. {/* Diameter */}
  417. <div className="flex items-center justify-between">
  418. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  419. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  420. </div>
  421. {/* Type */}
  422. {typeFull && (
  423. <div className="flex items-center justify-between">
  424. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  425. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  426. </div>
  427. )}
  428. {/* Flow (hide if empty) */}
  429. {flowFull && (
  430. <div className="flex items-center justify-between">
  431. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  432. <span className="text-xs text-white font-semibold">{flowFull}</span>
  433. </div>
  434. )}
  435. {/* Status badge */}
  436. <div className="flex items-center justify-between">
  437. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  438. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  439. activeStatus || isMounted
  440. ? 'bg-green-900/50 text-green-400'
  441. : 'bg-bambu-dark-tertiary text-bambu-gray'
  442. }`}>
  443. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  444. </span>
  445. </div>
  446. {/* Wear (hide if null) */}
  447. {slot.wear != null && (
  448. <div className="flex items-center justify-between">
  449. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  450. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  451. </div>
  452. )}
  453. {/* Max Temp (hide if 0) */}
  454. {slot.max_temp > 0 && (
  455. <div className="flex items-center justify-between">
  456. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  457. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  458. </div>
  459. )}
  460. {/* Serial (hide if empty) */}
  461. {slot.serial_number && (
  462. <div className="flex items-center justify-between">
  463. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  464. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  465. </div>
  466. )}
  467. {/* Filament: material type + color swatch (hide if no color) */}
  468. {(filamentCss || slot.filament_type) && (
  469. <div className="flex items-center justify-between">
  470. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  471. <div className="flex items-center gap-1">
  472. {filamentCss && (
  473. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  474. )}
  475. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  476. </div>
  477. </div>
  478. )}
  479. </div>
  480. )}
  481. </div>
  482. {/* Arrow pointer */}
  483. <div
  484. className={`
  485. absolute left-1/2 -translate-x-1/2 w-0 h-0
  486. border-l-[6px] border-l-transparent
  487. border-r-[6px] border-r-transparent
  488. ${position === 'top'
  489. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  490. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  491. `}
  492. />
  493. </div>
  494. )}
  495. </div>
  496. );
  497. }
  498. // Dual-nozzle hover card showing L and R nozzle details side by side
  499. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  500. leftSlot?: import('../api/client').NozzleRackSlot;
  501. rightSlot?: import('../api/client').NozzleRackSlot;
  502. activeNozzle: 'L' | 'R';
  503. filamentInfo?: Record<string, { name: string; k: number | null }>;
  504. children: React.ReactNode;
  505. }) {
  506. const { t } = useTranslation();
  507. const [isVisible, setIsVisible] = useState(false);
  508. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  509. const triggerRef = useRef<HTMLDivElement>(null);
  510. const cardRef = useRef<HTMLDivElement>(null);
  511. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  512. useEffect(() => {
  513. if (isVisible && triggerRef.current && cardRef.current) {
  514. const triggerRect = triggerRef.current.getBoundingClientRect();
  515. const cardHeight = cardRef.current.offsetHeight;
  516. const headerHeight = 56;
  517. const spaceAbove = triggerRect.top - headerHeight;
  518. const spaceBelow = window.innerHeight - triggerRect.bottom;
  519. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  520. setPosition('bottom');
  521. } else {
  522. setPosition('top');
  523. }
  524. }
  525. }, [isVisible]);
  526. const handleMouseEnter = () => {
  527. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  528. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  529. };
  530. const handleMouseLeave = () => {
  531. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  532. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  533. };
  534. useEffect(() => {
  535. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  536. }, []);
  537. if (!leftSlot && !rightSlot) return <>{children}</>;
  538. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  539. const isActive = activeNozzle === side;
  540. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  541. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  542. const filamentCss = parseFilamentColor(slot.filament_color);
  543. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  544. return (
  545. <div className="flex-1 space-y-1.5">
  546. <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'}`}>
  547. {side === 'L' ? t('common.left') : t('common.right')}
  548. </div>
  549. {slot.nozzle_diameter && (
  550. <div className="flex items-center justify-between">
  551. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  552. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  553. </div>
  554. )}
  555. {typeFull && (
  556. <div className="flex items-center justify-between">
  557. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  558. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  559. </div>
  560. )}
  561. {flowFull && (
  562. <div className="flex items-center justify-between">
  563. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  564. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  565. </div>
  566. )}
  567. <div className="flex items-center justify-between">
  568. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  569. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  570. isActive
  571. ? 'bg-green-900/50 text-green-400'
  572. : 'bg-bambu-dark-tertiary text-bambu-gray'
  573. }`}>
  574. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  575. </span>
  576. </div>
  577. {slot.wear != null && (
  578. <div className="flex items-center justify-between">
  579. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  580. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  581. </div>
  582. )}
  583. {/* Serial and max temp only available on the right (removable) nozzle */}
  584. {side === 'R' && slot.max_temp > 0 && (
  585. <div className="flex items-center justify-between">
  586. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  587. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  588. </div>
  589. )}
  590. {side === 'R' && slot.serial_number && (
  591. <div className="flex items-center justify-between">
  592. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  593. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  594. </div>
  595. )}
  596. {(filamentCss || slot.filament_type || slot.filament_id) && (
  597. <div className="flex items-center justify-between">
  598. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  599. <div className="flex items-center gap-1">
  600. {filamentCss && (
  601. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  602. )}
  603. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  604. {filamentName || slot.filament_type || slot.filament_id || ''}
  605. </span>
  606. </div>
  607. </div>
  608. )}
  609. </div>
  610. );
  611. };
  612. return (
  613. <div
  614. ref={triggerRef}
  615. className="relative flex-1"
  616. onMouseEnter={handleMouseEnter}
  617. onMouseLeave={handleMouseLeave}
  618. >
  619. {children}
  620. {isVisible && (
  621. <div
  622. ref={cardRef}
  623. className={`
  624. absolute left-1/2 -translate-x-1/2 z-50
  625. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  626. animate-in fade-in-0 zoom-in-95 duration-150
  627. `}
  628. style={{ maxWidth: 'calc(100vw - 24px)' }}
  629. >
  630. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  631. <div className="p-2.5 flex gap-3">
  632. {leftSlot && renderColumn(leftSlot, 'L')}
  633. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  634. {rightSlot && renderColumn(rightSlot, 'R')}
  635. </div>
  636. </div>
  637. {/* Arrow pointer */}
  638. <div
  639. className={`
  640. absolute left-1/2 -translate-x-1/2 w-0 h-0
  641. border-l-[6px] border-l-transparent
  642. border-r-[6px] border-r-transparent
  643. ${position === 'top'
  644. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  645. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  646. `}
  647. />
  648. </div>
  649. )}
  650. </div>
  651. );
  652. }
  653. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  654. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  655. const { t } = useTranslation();
  656. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  657. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  658. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  659. // base — computing it from min(present IDs) shifts everything left when slot 16
  660. // is the one currently mounted (#943).
  661. const rackNozzles = slots.filter(s => s.id >= 2);
  662. const RACK_SIZE = 6;
  663. const RACK_BASE_ID = 16;
  664. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  665. { length: RACK_SIZE },
  666. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  667. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  668. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  669. },
  670. );
  671. return (
  672. // Sized to its contents rather than growing: the six chips are a fixed
  673. // width at any one card size, so extra width would be dead space taken
  674. // from the temperature cards beside it — which are flex-1 with a 0 basis
  675. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  676. // stays enabled so the card still gives way on a narrow printer card
  677. // instead of overflowing.
  678. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  679. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  680. <div className="flex gap-[3px] justify-center">
  681. {rackSlots.map((slot, i) => {
  682. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  683. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  684. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  685. return (
  686. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  687. <div className="flex flex-col items-center gap-0.5">
  688. <div
  689. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  690. isEmpty
  691. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  692. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  693. }`}
  694. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  695. >
  696. <span
  697. data-rack-diameter
  698. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  699. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  700. >
  701. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  702. </span>
  703. </div>
  704. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  705. acted on without counting chips. Sits below the chip rather
  706. than inside it: the chip is barely wider than its own
  707. diameter text and already carries that over a
  708. filament-coloured background. */}
  709. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  710. {i + 1}
  711. </span>
  712. </div>
  713. </NozzleSlotHoverCard>
  714. );
  715. })}
  716. </div>
  717. </div>
  718. );
  719. }
  720. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  721. function WaterDropEmpty({ className }: { className?: string }) {
  722. return (
  723. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  724. <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"/>
  725. </svg>
  726. );
  727. }
  728. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  729. function WaterDropHalf({ className }: { className?: string }) {
  730. return (
  731. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  732. <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"/>
  733. <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"/>
  734. </svg>
  735. );
  736. }
  737. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  738. function WaterDropFull({ className }: { className?: string }) {
  739. return (
  740. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  741. <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"/>
  742. <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"/>
  743. </svg>
  744. );
  745. }
  746. // Thermometer SVG - empty outline
  747. function ThermometerEmpty({ className }: { className?: string }) {
  748. return (
  749. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  750. <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"/>
  751. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  752. </svg>
  753. );
  754. }
  755. // Thermometer SVG - half filled (gold - same as humidity fair)
  756. function ThermometerHalf({ className }: { className?: string }) {
  757. return (
  758. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  759. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  760. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  761. <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"/>
  762. </svg>
  763. );
  764. }
  765. // Thermometer SVG - fully filled (red - same as humidity bad)
  766. function ThermometerFull({ className }: { className?: string }) {
  767. return (
  768. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  769. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  770. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  771. <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"/>
  772. </svg>
  773. );
  774. }
  775. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  776. // Added for visual parity with the thermometer icons on the dual-nozzle card
  777. // that previously had no icon at all (#1115, design by @m4rtini2).
  778. function NozzleIcon({ className }: { className?: string }) {
  779. return (
  780. <svg
  781. className={className}
  782. viewBox="0 0 24 24"
  783. fill="none"
  784. xmlns="http://www.w3.org/2000/svg"
  785. stroke="currentColor"
  786. strokeWidth="1.5"
  787. strokeLinecap="round"
  788. strokeLinejoin="round"
  789. >
  790. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  791. <rect x="6" y="11.5" width="12.1" height="3.7" />
  792. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  793. </svg>
  794. );
  795. }
  796. // Heater thermometer icon - filled when heating, outline when off
  797. interface HeaterThermometerProps {
  798. className?: string;
  799. color: string; // The color class (e.g., "text-orange-400")
  800. isHeating: boolean;
  801. }
  802. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  803. // Extract the actual color from Tailwind class for SVG fill
  804. const colorMap: Record<string, string> = {
  805. 'text-orange-400': '#fb923c',
  806. 'text-blue-400': '#60a5fa',
  807. 'text-green-400': '#4ade80',
  808. };
  809. const fillColor = colorMap[color] || '#888';
  810. // Glow style when heating
  811. const glowStyle = isHeating ? {
  812. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  813. } : {};
  814. if (isHeating) {
  815. // Filled thermometer with glow - heater is ON
  816. return (
  817. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  818. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  819. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  820. <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"/>
  821. </svg>
  822. );
  823. }
  824. // Empty thermometer - heater is OFF
  825. return (
  826. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  827. <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"/>
  828. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  829. </svg>
  830. );
  831. }
  832. // AMS Filament Backup tri-state indicator + toggle.
  833. // state=true → ON, click to disable
  834. // state=false → OFF, click opens modal
  835. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  836. interface AmsBackupBadgeProps {
  837. state: boolean | null;
  838. onClick: () => void;
  839. }
  840. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  841. const { t } = useTranslation();
  842. const known = state !== null;
  843. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  844. let title: string;
  845. if (state === true) {
  846. className += known
  847. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  848. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  849. title = t('printers.amsBackup.titleOn');
  850. } else if (state === false) {
  851. className += known
  852. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  853. : 'bg-bambu-dark text-bambu-gray cursor-default';
  854. title = t('printers.amsBackup.titleOff');
  855. } else {
  856. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  857. title = t('printers.amsBackup.titleUnknown');
  858. }
  859. return (
  860. <button
  861. type="button"
  862. disabled={!known}
  863. onClick={() => known && onClick()}
  864. className={className}
  865. title={title}
  866. aria-label={title}
  867. >
  868. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  869. </button>
  870. );
  871. }
  872. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  873. // like AmsBackupBadge so the two sit together in the section header, but
  874. // pinned to the right-hand end of the rule: this is a view preference for the
  875. // row, not a property of the printer.
  876. interface ExternalSpoolToggleProps {
  877. hidden: boolean;
  878. onClick: () => void;
  879. }
  880. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  881. const { t } = useTranslation();
  882. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  883. return (
  884. <button
  885. type="button"
  886. onClick={onClick}
  887. aria-pressed={hidden}
  888. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  889. hidden
  890. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  891. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  892. }`}
  893. title={title}
  894. aria-label={title}
  895. >
  896. {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)]" />}
  897. </button>
  898. );
  899. }
  900. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  901. // Reference: https://github.com/theicedmango/bambu-humidity
  902. interface HumidityIndicatorProps {
  903. humidity: number | string;
  904. goodThreshold?: number; // <= this is green
  905. fairThreshold?: number; // <= this is orange, > is red
  906. onClick?: () => void;
  907. compact?: boolean; // Smaller version for grid layout
  908. }
  909. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  910. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  911. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  912. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  913. // Status thresholds (configurable via settings)
  914. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  915. let textColor: string;
  916. let statusText: string;
  917. if (isNaN(humidityValue)) {
  918. textColor = '#C3C2C1';
  919. statusText = 'Unknown';
  920. } else if (humidityValue <= good) {
  921. textColor = '#22a352'; // Green - Good
  922. statusText = 'Good';
  923. } else if (humidityValue <= fair) {
  924. textColor = '#d4a017'; // Gold - Fair
  925. statusText = 'Fair';
  926. } else {
  927. textColor = '#c62828'; // Red - Bad
  928. statusText = 'Bad';
  929. }
  930. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  931. let DropComponent: React.FC<{ className?: string }>;
  932. if (isNaN(humidityValue)) {
  933. DropComponent = WaterDropEmpty;
  934. } else if (humidityValue <= good) {
  935. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  936. } else if (humidityValue <= fair) {
  937. DropComponent = WaterDropHalf; // Fair - half filled
  938. } else {
  939. DropComponent = WaterDropFull; // Bad - full (too humid)
  940. }
  941. return (
  942. <button
  943. type="button"
  944. onClick={onClick}
  945. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  946. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  947. >
  948. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  949. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  950. </button>
  951. );
  952. }
  953. // Temperature indicator with dynamic icon and coloring
  954. interface TemperatureIndicatorProps {
  955. temp: number;
  956. goodThreshold?: number; // <= this is blue
  957. fairThreshold?: number; // <= this is orange, > is red
  958. onClick?: () => void;
  959. compact?: boolean; // Smaller version for grid layout
  960. }
  961. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  962. // Ensure thresholds are numbers
  963. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  964. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  965. let textColor: string;
  966. let statusText: string;
  967. let ThermoComponent: React.FC<{ className?: string }>;
  968. if (temp <= good) {
  969. textColor = '#22a352'; // Green - good (same as humidity)
  970. statusText = 'Good';
  971. ThermoComponent = ThermometerEmpty;
  972. } else if (temp <= fair) {
  973. textColor = '#d4a017'; // Gold - fair (same as humidity)
  974. statusText = 'Fair';
  975. ThermoComponent = ThermometerHalf;
  976. } else {
  977. textColor = '#c62828'; // Red - bad (same as humidity)
  978. statusText = 'Bad';
  979. ThermoComponent = ThermometerFull;
  980. }
  981. return (
  982. <button
  983. type="button"
  984. onClick={onClick}
  985. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  986. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  987. >
  988. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  989. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  990. </button>
  991. );
  992. }
  993. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  994. *
  995. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  996. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  997. * every empty-by-bitmask slot lands here regardless of firmware payload
  998. * shape.
  999. *
  1000. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  1001. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  1002. * the user cleared with "Reset Slot" where a physical spool may still be
  1003. * loaded but unassigned.
  1004. *
  1005. * Returns null when the slot is loaded (tray_type is present).
  1006. */
  1007. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  1008. if (tray?.tray_type) return null;
  1009. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  1010. // spool the firmware can't identify is physically present (exists === true)
  1011. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  1012. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  1013. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  1014. if (tray?.exists === true) return 'reset';
  1015. if (tray?.exists === false) return 'physical';
  1016. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  1017. }
  1018. // How long to wait for an AMS to report a live drying cycle after the printer
  1019. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  1020. // within a couple of seconds; 30s covers the slowest observed push cadence
  1021. // without leaving the user waiting on a verdict.
  1022. const DRY_START_CONFIRM_MS = 30_000;
  1023. export function CoverImage({
  1024. url,
  1025. printName,
  1026. className = 'w-20 h-20',
  1027. radiusClass = 'rounded-lg',
  1028. }: {
  1029. url: string | null;
  1030. printName?: string;
  1031. className?: string;
  1032. radiusClass?: string;
  1033. }) {
  1034. const { t } = useTranslation();
  1035. const [loaded, setLoaded] = useState(false);
  1036. const [error, setError] = useState(false);
  1037. const [showOverlay, setShowOverlay] = useState(false);
  1038. const imgRef = useRef<HTMLImageElement>(null);
  1039. // Cache-bust the image URL when the print name changes so the browser
  1040. // fetches the new cover instead of serving the stale cached image.
  1041. const cacheBustedUrl = useMemo(() => {
  1042. if (!url) return null;
  1043. const sep = url.includes('?') ? '&' : '?';
  1044. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1045. }, [url, printName]);
  1046. // Re-evaluate load state when the image URL changes, and ask the element
  1047. // whether it is already showing something rather than assuming it is not.
  1048. //
  1049. // `onLoad` used to be the only thing that could set `loaded`, and this
  1050. // effect reset it to false unconditionally. That is right when the URL
  1051. // really changes, but it also runs on mount — and the two are not the same
  1052. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1053. // constant for the duration of a print, so navigating away from the
  1054. // printers page and back re-mounts with a byte-identical src that the
  1055. // browser serves from its in-memory cache. The `load` event for a cache hit
  1056. // and React's passive-effect flush are both plain tasks with no ordering
  1057. // between them, so when `load` won, this effect ran afterwards and undid
  1058. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1059. // sat there until a full reload. Nothing recovered it, because the URL
  1060. // never changes again during the print and so this effect never re-runs.
  1061. //
  1062. // Being a race, it reproduced every time for #2826's reporter and not at
  1063. // all here, which is also why the network panel showed no request: there
  1064. // was no request to show.
  1065. //
  1066. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1067. // which of the two ran first. It is also correct for the case the reporter
  1068. // proposed (a `load` that fires before React's handler is live), so the
  1069. // fix stands whichever mechanism is really at work.
  1070. useEffect(() => {
  1071. setError(false);
  1072. const el = imgRef.current;
  1073. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1074. }, [cacheBustedUrl]);
  1075. return (
  1076. <>
  1077. <div
  1078. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1079. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1080. >
  1081. {cacheBustedUrl && !error ? (
  1082. <>
  1083. <img
  1084. ref={imgRef}
  1085. src={cacheBustedUrl}
  1086. alt={t('printers.printPreview')}
  1087. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1088. onLoad={() => setLoaded(true)}
  1089. onError={() => setError(true)}
  1090. />
  1091. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1092. </>
  1093. ) : (
  1094. <Box className="w-8 h-8 text-bambu-gray" />
  1095. )}
  1096. </div>
  1097. {/* Cover Image Overlay */}
  1098. {showOverlay && cacheBustedUrl && (
  1099. <div
  1100. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1101. onClick={() => setShowOverlay(false)}
  1102. >
  1103. <div className="relative max-w-2xl max-h-full">
  1104. <img
  1105. src={cacheBustedUrl}
  1106. alt={t('printers.printPreview')}
  1107. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1108. />
  1109. {printName && (
  1110. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1111. )}
  1112. </div>
  1113. </div>
  1114. )}
  1115. </>
  1116. );
  1117. }
  1118. interface PrinterMaintenanceInfo {
  1119. due_count: number;
  1120. warning_count: number;
  1121. total_print_hours: number;
  1122. }
  1123. // Status summary bar component - uses queryClient to read cached statuses
  1124. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1125. const { t } = useTranslation();
  1126. const queryClient = useQueryClient();
  1127. // Subscribe to query cache changes to re-render when status updates
  1128. // Throttled to prevent rapid re-renders from causing tab crashes
  1129. const [cacheTick, setCacheTick] = useState(0);
  1130. useEffect(() => {
  1131. let pending = false;
  1132. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1133. if (!pending) {
  1134. pending = true;
  1135. requestAnimationFrame(() => {
  1136. setCacheTick(t => t + 1);
  1137. pending = false;
  1138. });
  1139. }
  1140. });
  1141. return () => unsubscribe();
  1142. }, [queryClient]);
  1143. const { counts, nextFinish } = useMemo(() => {
  1144. let printing = 0;
  1145. let paused = 0;
  1146. let finished = 0;
  1147. let idle = 0;
  1148. let offline = 0;
  1149. let loading = 0;
  1150. let error = 0;
  1151. let nextPrinterName: string | null = null;
  1152. let nextRemainingMin: number | null = null;
  1153. let nextProgress: number = 0;
  1154. printers?.forEach((printer) => {
  1155. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1156. if (status === undefined) {
  1157. // Status not yet loaded - don't count as offline yet
  1158. loading++;
  1159. } else if (!status.connected) {
  1160. offline++;
  1161. } else {
  1162. // Count printers with active HMS errors as problems
  1163. const knownHmsCount =
  1164. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1165. if (knownHmsCount > 0) {
  1166. error++;
  1167. }
  1168. switch (status.state) {
  1169. case 'RUNNING':
  1170. printing++;
  1171. if (status.remaining_time != null && status.remaining_time > 0) {
  1172. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1173. nextRemainingMin = status.remaining_time;
  1174. nextPrinterName = printer.name;
  1175. nextProgress = status.progress || 0;
  1176. }
  1177. }
  1178. break;
  1179. case 'PAUSE':
  1180. paused++;
  1181. break;
  1182. case 'FINISH':
  1183. finished++;
  1184. break;
  1185. case 'FAILED':
  1186. // FAILED is the printer's terminal gcode_state after a print stops —
  1187. // including user cancellations, where there's no actual fault. Only
  1188. // count it as a "problem" when an HMS error is also active; otherwise
  1189. // it's just a print that ended unsuccessfully and the plate needs
  1190. // clearing (same as FINISH from the operator's perspective).
  1191. if (knownHmsCount > 0) {
  1192. // Already counted above
  1193. } else {
  1194. finished++;
  1195. }
  1196. break;
  1197. default:
  1198. idle++;
  1199. break;
  1200. }
  1201. }
  1202. });
  1203. return {
  1204. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1205. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1206. };
  1207. // eslint-disable-next-line react-hooks/exhaustive-deps
  1208. }, [printers, queryClient, cacheTick]);
  1209. if (!printers?.length) return null;
  1210. const badges: { count: number; dot: string; label: string }[] = [
  1211. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1212. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1213. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1214. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1215. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1216. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1217. ];
  1218. return (
  1219. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1220. {badges.map(({ count, dot, label }) => count > 0 && (
  1221. <div key={label} className="flex items-center gap-1.5">
  1222. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1223. <span className="text-bambu-gray">
  1224. <span className="text-white font-medium">{count}</span> {label}
  1225. </span>
  1226. </div>
  1227. ))}
  1228. {nextFinish && (
  1229. <>
  1230. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1231. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1232. <div className="flex items-center gap-2">
  1233. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1234. <span className="text-white font-medium">{nextFinish.name}</span>
  1235. </div>
  1236. <div className="flex items-center gap-2 w-full sm:w-auto">
  1237. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1238. <div
  1239. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1240. style={{ width: `${nextFinish.progress}%` }}
  1241. />
  1242. </div>
  1243. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1244. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1245. </div>
  1246. </div>
  1247. </>
  1248. )}
  1249. </div>
  1250. );
  1251. }
  1252. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1253. type ViewMode = 'expanded' | 'compact';
  1254. type ToolbarDropdownOption<T extends string> = {
  1255. value: T;
  1256. label: string;
  1257. };
  1258. function ToolbarDropdown<T extends string>({
  1259. value,
  1260. options,
  1261. onChange,
  1262. fullWidth = false,
  1263. }: {
  1264. value: T;
  1265. options: ToolbarDropdownOption<T>[];
  1266. onChange: (value: T) => void;
  1267. fullWidth?: boolean;
  1268. }) {
  1269. const [isOpen, setIsOpen] = useState(false);
  1270. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1271. return (
  1272. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1273. <button
  1274. type="button"
  1275. onClick={() => setIsOpen(open => !open)}
  1276. 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'}`}
  1277. >
  1278. <span className="truncate">{selectedOption?.label}</span>
  1279. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1280. </button>
  1281. {isOpen && (
  1282. <>
  1283. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1284. <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">
  1285. {options.map(option => (
  1286. <button
  1287. key={option.value}
  1288. type="button"
  1289. onClick={() => {
  1290. onChange(option.value);
  1291. setIsOpen(false);
  1292. }}
  1293. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1294. option.value === value ? 'text-bambu-green' : 'text-white'
  1295. }`}
  1296. >
  1297. {option.label}
  1298. </button>
  1299. ))}
  1300. </div>
  1301. </>
  1302. )}
  1303. </div>
  1304. );
  1305. }
  1306. function ToolbarMenu({
  1307. label,
  1308. icon,
  1309. children,
  1310. }: {
  1311. label: string;
  1312. icon: React.ReactNode;
  1313. children: React.ReactNode;
  1314. }) {
  1315. const [isOpen, setIsOpen] = useState(false);
  1316. return (
  1317. <div className="relative">
  1318. <button
  1319. type="button"
  1320. onClick={() => setIsOpen(open => !open)}
  1321. 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"
  1322. aria-label={label}
  1323. title={label}
  1324. >
  1325. {icon}
  1326. </button>
  1327. {isOpen && (
  1328. <>
  1329. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1330. <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">
  1331. {children}
  1332. </div>
  1333. </>
  1334. )}
  1335. </div>
  1336. );
  1337. }
  1338. function IndicatorControlPopover({
  1339. title,
  1340. options = [],
  1341. unit,
  1342. customMin,
  1343. customMax,
  1344. customStep = 1,
  1345. widthClass = 'w-[240px]',
  1346. popoverWidth = 240,
  1347. popoverHeight = 280,
  1348. isPending,
  1349. onClose,
  1350. onSubmit,
  1351. children,
  1352. }: {
  1353. title: string;
  1354. options?: Array<{ label: string; value: number }>;
  1355. unit?: string;
  1356. customMin?: number;
  1357. customMax?: number;
  1358. customStep?: number;
  1359. widthClass?: string;
  1360. popoverWidth?: number;
  1361. popoverHeight?: number;
  1362. isPending?: boolean;
  1363. onClose: () => void;
  1364. onSubmit?: (value: number) => void;
  1365. children?: React.ReactNode;
  1366. }) {
  1367. const anchorRef = useRef<HTMLSpanElement>(null);
  1368. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1369. const [customValue, setCustomValue] = useState('');
  1370. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1371. // can position via fixed coords. Portaling to document.body escapes
  1372. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1373. // own contexts and would otherwise cover the popover even at z-[60].
  1374. useLayoutEffect(() => {
  1375. const trigger = anchorRef.current?.parentElement;
  1376. if (!trigger) return;
  1377. const measure = () => {
  1378. const rect = trigger.getBoundingClientRect();
  1379. setCoords(computePopoverPosition({
  1380. triggerRect: rect,
  1381. popoverWidth,
  1382. estimatedHeight: popoverHeight,
  1383. horizontalAlign: 'center',
  1384. }));
  1385. };
  1386. measure();
  1387. window.addEventListener('resize', measure);
  1388. window.addEventListener('scroll', measure, true);
  1389. return () => {
  1390. window.removeEventListener('resize', measure);
  1391. window.removeEventListener('scroll', measure, true);
  1392. };
  1393. }, [popoverWidth, popoverHeight]);
  1394. const showCustomInput = unit !== undefined;
  1395. const submitCustom = () => {
  1396. const value = Number(customValue);
  1397. if (!Number.isFinite(value)) return;
  1398. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1399. onSubmit?.(Math.round(bounded));
  1400. };
  1401. return (
  1402. <>
  1403. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1404. {createPortal(
  1405. <>
  1406. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1407. <div
  1408. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1409. style={{
  1410. top: coords?.top ?? -9999,
  1411. left: coords?.left ?? -9999,
  1412. visibility: coords ? 'visible' : 'hidden',
  1413. }}
  1414. onClick={e => e.stopPropagation()}
  1415. >
  1416. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1417. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1418. {options.length > 0 && (
  1419. <div className="px-3 py-2.5">
  1420. <div className="grid grid-cols-2 gap-1.5">
  1421. {options.map(option => (
  1422. <button
  1423. key={`${option.label}-${option.value}`}
  1424. type="button"
  1425. disabled={isPending}
  1426. onClick={() => onSubmit?.(option.value)}
  1427. 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"
  1428. >
  1429. {option.label}
  1430. </button>
  1431. ))}
  1432. </div>
  1433. </div>
  1434. )}
  1435. {children}
  1436. {showCustomInput && (
  1437. <>
  1438. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1439. <form
  1440. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1441. onSubmit={(e) => {
  1442. e.preventDefault();
  1443. submitCustom();
  1444. }}
  1445. >
  1446. <input
  1447. type="number"
  1448. min={customMin}
  1449. max={customMax}
  1450. step={customStep}
  1451. value={customValue}
  1452. onChange={e => setCustomValue(e.target.value)}
  1453. placeholder="Custom"
  1454. 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"
  1455. />
  1456. <button
  1457. type="submit"
  1458. disabled={isPending || customValue.trim() === ''}
  1459. 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"
  1460. >
  1461. Set
  1462. </button>
  1463. </form>
  1464. </>
  1465. )}
  1466. </div>
  1467. </>,
  1468. document.body
  1469. )}
  1470. </>
  1471. );
  1472. }
  1473. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1474. function NozzleTemperatureControlBox({
  1475. label,
  1476. current,
  1477. target,
  1478. isActive,
  1479. isPending,
  1480. onSubmit,
  1481. options = NOZZLE_TEMPERATURE_OPTIONS,
  1482. }: {
  1483. label: string;
  1484. current?: number;
  1485. target?: number;
  1486. isActive: boolean;
  1487. isPending?: boolean;
  1488. onSubmit: (value: number) => void;
  1489. options?: Array<{ label: string; value: number }>;
  1490. }) {
  1491. const [customValue, setCustomValue] = useState('');
  1492. const submitCustom = () => {
  1493. const value = Number(customValue);
  1494. if (!Number.isFinite(value)) return;
  1495. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1496. };
  1497. return (
  1498. <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'}`}>
  1499. <div className="mb-1.5 flex items-center justify-between gap-2">
  1500. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1501. <span className="text-[10px] text-bambu-gray">
  1502. {Math.round(current ?? 0)}°C
  1503. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1504. </span>
  1505. </div>
  1506. <div className="grid grid-cols-2 gap-1">
  1507. {options.map(option => (
  1508. <button
  1509. key={`${label}-${option.value}`}
  1510. type="button"
  1511. disabled={isPending}
  1512. onClick={() => onSubmit(option.value)}
  1513. 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"
  1514. >
  1515. {option.label}
  1516. </button>
  1517. ))}
  1518. </div>
  1519. <form
  1520. className="mt-1.5 flex gap-1"
  1521. onSubmit={(e) => {
  1522. e.preventDefault();
  1523. submitCustom();
  1524. }}
  1525. >
  1526. <input
  1527. type="number"
  1528. min={0}
  1529. max={320}
  1530. step={1}
  1531. value={customValue}
  1532. onChange={e => setCustomValue(e.target.value)}
  1533. placeholder="Custom"
  1534. 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"
  1535. />
  1536. <button
  1537. type="submit"
  1538. disabled={isPending || customValue.trim() === ''}
  1539. 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"
  1540. >
  1541. Set
  1542. </button>
  1543. </form>
  1544. </div>
  1545. );
  1546. }
  1547. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1548. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1549. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1550. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1551. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1552. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1553. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1554. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1555. };
  1556. /** Classify a printer into one of the UI status buckets. */
  1557. function classifyPrinterStatus(
  1558. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1559. ): PrinterState {
  1560. if (!status?.connected) return 'offline';
  1561. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1562. if (hmsErrors.length > 0) return 'error';
  1563. switch (status.state) {
  1564. case 'RUNNING': return 'printing';
  1565. case 'PAUSE': return 'paused';
  1566. case 'FINISH': return 'finished';
  1567. // FAILED without an active HMS error is the printer's terminal state after
  1568. // any unsuccessful end — including user-cancellations. Treat the same as
  1569. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1570. // HMS code is actually attached (handled by the early-return above).
  1571. case 'FAILED': return 'finished';
  1572. default: return 'idle';
  1573. }
  1574. }
  1575. /**
  1576. * Get human-readable status display text for a printer.
  1577. * Uses stg_cur_name for detailed calibration/preparation stages,
  1578. * otherwise formats the gcode_state nicely.
  1579. */
  1580. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1581. // If we have a specific stage name (calibration, heating, etc.), use it
  1582. if (stg_cur_name) {
  1583. return stg_cur_name;
  1584. }
  1585. // Format the gcode_state nicely
  1586. switch (state) {
  1587. case 'RUNNING':
  1588. return 'Printing';
  1589. case 'PAUSE':
  1590. return 'Paused';
  1591. case 'FINISH':
  1592. return 'Finished';
  1593. case 'FAILED':
  1594. return 'Failed';
  1595. case 'IDLE':
  1596. return 'Idle';
  1597. default:
  1598. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1599. }
  1600. }
  1601. // Bambu models that ship with an enclosure chamber fan (firmware field
  1602. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1603. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1604. // widget is hidden in fanItems instead of rendered greyed-out.
  1605. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1606. 'X1C',
  1607. 'X1',
  1608. 'X1E',
  1609. 'X2D',
  1610. 'P1S',
  1611. 'P2S',
  1612. 'H2D',
  1613. 'H2D Pro',
  1614. 'H2C',
  1615. 'H2S',
  1616. ]);
  1617. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1618. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1619. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1620. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1621. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1622. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1623. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1624. 'P2S',
  1625. 'X2D',
  1626. ]);
  1627. // Map SSDP model codes to display names
  1628. function mapModelCode(ssdpModel: string | null): string {
  1629. if (!ssdpModel) return '';
  1630. const modelMap: Record<string, string> = {
  1631. // H2 Series
  1632. 'O1D': 'H2D',
  1633. 'O1E': 'H2D Pro',
  1634. 'O2D': 'H2D Pro',
  1635. 'O1C': 'H2C',
  1636. 'O1C2': 'H2C',
  1637. 'O1S': 'H2S',
  1638. // X1 Series
  1639. 'BL-P001': 'X1C',
  1640. 'BL-P002': 'X1',
  1641. 'BL-P003': 'X1E',
  1642. // X2 Series
  1643. 'N6': 'X2D',
  1644. // A2 Series
  1645. 'N9': 'A2L',
  1646. // P Series
  1647. 'C11': 'P1S',
  1648. 'C12': 'P1P',
  1649. 'C13': 'P2S',
  1650. // A1 Series
  1651. 'N2S': 'A1',
  1652. 'N1': 'A1 Mini',
  1653. // Direct matches
  1654. 'X1C': 'X1C',
  1655. 'X1': 'X1',
  1656. 'X1E': 'X1E',
  1657. 'X2D': 'X2D',
  1658. 'P1S': 'P1S',
  1659. 'P1P': 'P1P',
  1660. 'P2S': 'P2S',
  1661. 'A1': 'A1',
  1662. 'A1 Mini': 'A1 Mini',
  1663. 'A2L': 'A2L',
  1664. 'H2D': 'H2D',
  1665. 'H2D Pro': 'H2D Pro',
  1666. 'H2C': 'H2C',
  1667. 'H2S': 'H2S',
  1668. };
  1669. return modelMap[ssdpModel] || ssdpModel;
  1670. }
  1671. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1672. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1673. // • User-defined friendly name (editable, protected by printers:update)
  1674. // • AMS serial number
  1675. // • AMS firmware version
  1676. export function AmsNameHoverCard({
  1677. ams,
  1678. printerId,
  1679. label,
  1680. amsLabels,
  1681. canEdit,
  1682. onSaved,
  1683. children,
  1684. }: {
  1685. ams: import('../api/client').AMSUnit;
  1686. printerId: number;
  1687. label: string; // auto-generated label, e.g. "AMS-A"
  1688. amsLabels?: Record<number, string>;
  1689. canEdit: boolean;
  1690. onSaved: () => void;
  1691. children: React.ReactNode;
  1692. }) {
  1693. const { t } = useTranslation();
  1694. const [isVisible, setIsVisible] = useState(false);
  1695. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1696. const [editValue, setEditValue] = useState('');
  1697. const [isSaving, setIsSaving] = useState(false);
  1698. const [saveError, setSaveError] = useState<string | null>(null);
  1699. const [isInputFocused, setIsInputFocused] = useState(false);
  1700. const triggerRef = useRef<HTMLDivElement>(null);
  1701. const cardRef = useRef<HTMLDivElement>(null);
  1702. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1703. useEffect(() => {
  1704. if (isVisible) {
  1705. setEditValue(amsLabels?.[ams.id] ?? '');
  1706. setSaveError(null);
  1707. requestAnimationFrame(() => {
  1708. if (triggerRef.current && cardRef.current) {
  1709. const rect = triggerRef.current.getBoundingClientRect();
  1710. const spaceAbove = rect.top - 56;
  1711. const spaceBelow = window.innerHeight - rect.bottom;
  1712. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1713. }
  1714. });
  1715. }
  1716. }, [isVisible, amsLabels, ams.id]);
  1717. const handleMouseEnter = () => {
  1718. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1719. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1720. };
  1721. const handleMouseLeave = () => {
  1722. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1723. if (!isInputFocused) {
  1724. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1725. }
  1726. };
  1727. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1728. const handleSave = async () => {
  1729. if (!canEdit) return;
  1730. setIsSaving(true);
  1731. setSaveError(null);
  1732. try {
  1733. const trimmed = editValue.trim();
  1734. if (trimmed) {
  1735. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1736. } else {
  1737. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1738. }
  1739. onSaved();
  1740. setIsVisible(false);
  1741. } catch (err) {
  1742. setSaveError(err instanceof Error ? err.message : String(err));
  1743. } finally {
  1744. setIsSaving(false);
  1745. }
  1746. };
  1747. const handleClear = async () => {
  1748. if (!canEdit) return;
  1749. setIsSaving(true);
  1750. setSaveError(null);
  1751. try {
  1752. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1753. onSaved();
  1754. setIsVisible(false);
  1755. } catch (err) {
  1756. setSaveError(err instanceof Error ? err.message : String(err));
  1757. } finally {
  1758. setIsSaving(false);
  1759. }
  1760. };
  1761. return (
  1762. <div
  1763. ref={triggerRef}
  1764. className="relative inline-block"
  1765. onMouseEnter={handleMouseEnter}
  1766. onMouseLeave={handleMouseLeave}
  1767. >
  1768. {children}
  1769. {isVisible && (
  1770. <div
  1771. ref={cardRef}
  1772. className={`
  1773. absolute left-0 z-50
  1774. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1775. animate-in fade-in-0 zoom-in-95 duration-150
  1776. `}
  1777. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1778. onMouseEnter={handleMouseEnter}
  1779. onMouseLeave={handleMouseLeave}
  1780. >
  1781. <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">
  1782. {/* AMS auto-label */}
  1783. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1784. {/* Serial number */}
  1785. <div className="flex items-center justify-between gap-2">
  1786. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1787. {t('printers.amsPopup.serialNumber')}
  1788. </span>
  1789. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1790. </div>
  1791. {/* Firmware version */}
  1792. <div className="flex items-center justify-between gap-2">
  1793. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1794. {t('printers.amsPopup.firmwareVersion')}
  1795. </span>
  1796. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1797. </div>
  1798. {/* Friendly name editor */}
  1799. <div className="space-y-1">
  1800. <div className="flex items-center gap-2">
  1801. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1802. {t('printers.amsPopup.friendlyName')}
  1803. </span>
  1804. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1805. </div>
  1806. <input
  1807. type="text"
  1808. value={editValue}
  1809. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1810. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1811. onFocus={() => setIsInputFocused(true)}
  1812. onBlur={() => {
  1813. setIsInputFocused(false);
  1814. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1815. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1816. }}
  1817. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1818. disabled={!canEdit}
  1819. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1820. 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"
  1821. maxLength={100}
  1822. />
  1823. {canEdit && (
  1824. <div className="space-y-1">
  1825. {saveError && (
  1826. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1827. )}
  1828. <div className="flex gap-1 justify-end">
  1829. <button
  1830. onClick={handleSave}
  1831. disabled={isSaving}
  1832. 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"
  1833. >
  1834. {t('printers.amsPopup.save')}
  1835. </button>
  1836. {amsLabels?.[ams.id] && (
  1837. <button
  1838. onClick={handleClear}
  1839. disabled={isSaving}
  1840. 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"
  1841. >
  1842. {t('printers.amsPopup.clear')}
  1843. </button>
  1844. )}
  1845. </div>
  1846. </div>
  1847. )}
  1848. </div>
  1849. </div>
  1850. </div>
  1851. )}
  1852. </div>
  1853. );
  1854. }
  1855. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1856. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1857. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1858. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1859. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1860. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1861. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1862. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1863. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1864. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1865. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1866. };
  1867. // How much the printer card's body type and icons grow at each card size
  1868. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1869. // 1.0 and an existing install looks identical until the user picks L or XL --
  1870. // the same control the request asked to have this follow.
  1871. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1872. // The scaled sizes, handed to the card subtree as custom properties. Every
  1873. // converted class names its old fixed value as the fallback, so anything that
  1874. // renders outside a card root -- the portalled temperature popover -- keeps
  1875. // exactly the size it has today.
  1876. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1877. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1878. // Rounded to a tenth so the values stay readable in devtools.
  1879. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1880. return {
  1881. '--pc-t8': px(8),
  1882. '--pc-t9': px(9),
  1883. '--pc-t10': px(10),
  1884. '--pc-t11': px(11),
  1885. '--pc-i2': px(8),
  1886. '--pc-i25': px(10),
  1887. '--pc-i3': px(12),
  1888. '--pc-i35': px(14),
  1889. '--pc-i4': px(16),
  1890. '--pc-i5': px(20),
  1891. '--pc-i7': px(28),
  1892. } as React.CSSProperties;
  1893. }
  1894. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1895. const { t } = useTranslation();
  1896. const queryClient = useQueryClient();
  1897. const { showToast } = useToast();
  1898. // One fleet-wide query shared by every card, not one per card: the list is
  1899. // nearly always empty and a 20-printer fleet would otherwise make 20
  1900. // requests every 30s. React Query dedupes on the key.
  1901. const { data: scheduled = [] } = useQuery({
  1902. queryKey: SCHEDULED_DRYINGS_KEY,
  1903. queryFn: () => api.listScheduledDryings(),
  1904. refetchInterval: 30_000,
  1905. });
  1906. // The live AMS status reports a starting cycle well before the next poll;
  1907. // refetch so a just-dispatched schedule doesn't linger as pending.
  1908. useEffect(() => {
  1909. if (dryingActive) {
  1910. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1911. }
  1912. }, [dryingActive, queryClient]);
  1913. const cancelMutation = useMutation({
  1914. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1915. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1916. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1917. });
  1918. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1919. // old firmware on a printer that was offline at schedule time), and without
  1920. // this the run just vanishes with only the backend log saying why.
  1921. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1922. if (rows.length === 0) return null;
  1923. return (
  1924. <div className="mt-2 space-y-1">
  1925. {rows.map(s => {
  1926. const failed = s.status === 'failed';
  1927. const reasonKey = waitingReasonKey(s.waiting_reason);
  1928. const failedKey = failedReasonKey(s.error_code);
  1929. return (
  1930. <div
  1931. key={s.id}
  1932. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1933. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1934. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1935. }`}
  1936. >
  1937. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1938. {failed ? (
  1939. t('printers.drying.scheduleFailedReason', {
  1940. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1941. })
  1942. ) : (
  1943. <>
  1944. {s.start_after
  1945. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1946. : t('printers.drying.scheduledAsap')}
  1947. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1948. </>
  1949. )}
  1950. </span>
  1951. <button
  1952. onClick={() => cancelMutation.mutate(s.id)}
  1953. disabled={cancelMutation.isPending}
  1954. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1955. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1956. >
  1957. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1958. </button>
  1959. </div>
  1960. );
  1961. })}
  1962. </div>
  1963. );
  1964. }
  1965. function PrinterCard({
  1966. printer,
  1967. hideIfDisconnected,
  1968. maintenanceInfo,
  1969. viewMode = 'expanded',
  1970. cardSize = 2,
  1971. amsThresholds,
  1972. spoolmanEnabled = false,
  1973. linkedSpools,
  1974. spoolmanUrl,
  1975. spoolmanSyncMode,
  1976. onGetAssignment,
  1977. onUnassignSpool,
  1978. spoolmanSpools,
  1979. spoolmanSlotAssignments,
  1980. spoolmanLoading = false,
  1981. onUnassignSpoolmanSpool,
  1982. timeFormat = 'system',
  1983. cameraViewMode = 'window',
  1984. onOpenEmbeddedCamera,
  1985. onSelectCameraViewMode,
  1986. checkPrinterFirmware = true,
  1987. dryingPresets = DRYING_PRESETS,
  1988. requirePlateClear = false,
  1989. selectionMode = false,
  1990. isSelected = false,
  1991. onToggleSelect,
  1992. onOpenCompactCard,
  1993. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1994. bedTempPresets = BED_TEMP_DEFAULTS,
  1995. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1996. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1997. aiDetectionEnabled = false,
  1998. aiDetection,
  1999. aiLastError = null,
  2000. }: {
  2001. printer: Printer;
  2002. hideIfDisconnected?: boolean;
  2003. maintenanceInfo?: PrinterMaintenanceInfo;
  2004. viewMode?: ViewMode;
  2005. cardSize?: number;
  2006. amsThresholds?: {
  2007. humidityGood: number;
  2008. humidityFair: number;
  2009. tempGood: number;
  2010. tempFair: number;
  2011. };
  2012. spoolmanEnabled?: boolean;
  2013. hasUnlinkedSpools?: boolean;
  2014. linkedSpools?: Record<string, LinkedSpoolInfo>;
  2015. spoolmanUrl?: string | null;
  2016. spoolmanSyncMode?: string | null;
  2017. spoolAssignments?: SpoolAssignment[];
  2018. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  2019. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  2020. spoolmanSpools?: InventorySpool[];
  2021. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  2022. spoolmanLoading?: boolean;
  2023. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  2024. timeFormat?: 'system' | '12h' | '24h';
  2025. cameraViewMode?: CameraViewMode;
  2026. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  2027. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  2028. checkPrinterFirmware?: boolean;
  2029. dryingPresets?: Record<string, DryingPreset>;
  2030. requirePlateClear?: boolean;
  2031. selectionMode?: boolean;
  2032. isSelected?: boolean;
  2033. onToggleSelect?: (id: number) => void;
  2034. onOpenCompactCard?: (id: number) => void;
  2035. nozzleTempPresets?: readonly [number, number, number];
  2036. bedTempPresets?: readonly [number, number, number];
  2037. chamberTempPresets?: readonly [number, number, number];
  2038. fanSpeedPresets?: readonly [number, number, number];
  2039. aiDetectionEnabled?: boolean;
  2040. aiDetection?: AiDetection;
  2041. aiLastError?: string | null;
  2042. }) {
  2043. const { t } = useTranslation();
  2044. const queryClient = useQueryClient();
  2045. const navigate = useNavigate();
  2046. const { showToast } = useToast();
  2047. const { hasPermission, canModify } = useAuth();
  2048. const [showMenu, setShowMenu] = useState(false);
  2049. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  2050. const [deleteArchives, setDeleteArchives] = useState(true);
  2051. const [showEditModal, setShowEditModal] = useState(false);
  2052. const [showFileManager, setShowFileManager] = useState(false);
  2053. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  2054. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  2055. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  2056. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  2057. const [showHMSModal, setShowHMSModal] = useState(false);
  2058. // #1546: AI failure detection modal — opens from the AI badge.
  2059. const [showAiModal, setShowAiModal] = useState(false);
  2060. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  2061. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  2062. // External spool visibility (#1782) — browser-local, per printer. Read once
  2063. // per card; the toggle that writes it is the only thing that changes it.
  2064. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2065. isExternalSpoolHidden(printer.id),
  2066. );
  2067. const toggleExternalSpool = useCallback(() => {
  2068. setExternalSpoolHidden((prev) => {
  2069. const next = !prev;
  2070. persistExternalSpoolHidden(printer.id, next);
  2071. return next;
  2072. });
  2073. }, [printer.id]);
  2074. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2075. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2076. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2077. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2078. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2079. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2080. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2081. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2082. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2083. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2084. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2085. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2086. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2087. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2088. // AMS drying popover state: which AMS unit has the popover open
  2089. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2090. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2091. const [dryingFilament, setDryingFilament] = useState('PLA');
  2092. const [dryingTemp, setDryingTemp] = useState(50);
  2093. const [dryingDuration, setDryingDuration] = useState(4);
  2094. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2095. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2096. // go through scheduleDryingMutation.
  2097. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2098. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2099. const [dryingStartAt, setDryingStartAt] = useState('');
  2100. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2101. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2102. // Reset every field the popover owns, including the start mode. Leaving the
  2103. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2104. // the next open, by then in the past, and the POST rejected it.
  2105. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2106. const firstTray = ams.tray.find(t => t.tray_type);
  2107. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2108. // Only reachable if a custom preset set dropped PLA itself.
  2109. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2110. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2111. setDryingFilament(filType);
  2112. setDryingTemp(preset[moduleType] || preset.n3f);
  2113. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2114. setDryingRotateTray(false);
  2115. setDryingStartMode('now');
  2116. setDryingDelayMinutes(120);
  2117. setDryingStartAt('');
  2118. setDryingPopoverModuleType(ams.module_type);
  2119. setDryingPopoverAmsId(ams.id);
  2120. setDryingPopoverAnchor(trigger);
  2121. }, [dryingPresets]);
  2122. // Re-measure on resize/scroll so the popover and its arrow track the
  2123. // flame button, like IndicatorControlPopover.
  2124. useLayoutEffect(() => {
  2125. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2126. const measure = () => {
  2127. setDryingPopoverPos(computePopoverPosition({
  2128. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2129. popoverWidth: DRYING_POPOVER_WIDTH,
  2130. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2131. horizontalAlign: 'center',
  2132. }));
  2133. };
  2134. measure();
  2135. window.addEventListener('resize', measure);
  2136. window.addEventListener('scroll', measure, true);
  2137. return () => {
  2138. window.removeEventListener('resize', measure);
  2139. window.removeEventListener('scroll', measure, true);
  2140. };
  2141. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2142. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2143. // Whether the click hitting the backdrop is the one that dismissed the
  2144. // native datetime picker (see the backdrop's onMouseDown).
  2145. const dryingBackdropSkipCloseRef = useRef(false);
  2146. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2147. // an object rather than a bare id so restarting drying on the SAME unit produces
  2148. // a new identity and rearms the timeout below.
  2149. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2150. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2151. const [isDropUploading, setIsDropUploading] = useState(false);
  2152. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2153. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2154. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2155. // inside the card would have to open upward into the card body; anchored to
  2156. // the viewport it escapes the card and the grid's scroll container both.
  2157. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2158. const dragCounterRef = useRef(0);
  2159. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2160. amsId: number;
  2161. amsLabel: string;
  2162. mode: 'humidity' | 'temperature';
  2163. } | null>(null);
  2164. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2165. initialKind: HeaterSensorKind;
  2166. availableKinds: HeaterSensorKind[];
  2167. } | null>(null);
  2168. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2169. tagUid: string;
  2170. trayUuid: string;
  2171. printerId: number;
  2172. amsId: number;
  2173. trayId: number;
  2174. } | null>(null);
  2175. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2176. printerId: number;
  2177. amsId: number;
  2178. trayId: number;
  2179. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2180. } | null>(null);
  2181. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2182. amsId: number;
  2183. trayId: number;
  2184. trayCount: number;
  2185. trayType?: string;
  2186. trayColor?: string;
  2187. traySubBrands?: string;
  2188. trayInfoIdx?: string;
  2189. extruderId?: number;
  2190. caliIdx?: number | null;
  2191. savedPresetId?: string;
  2192. } | null>(null);
  2193. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2194. const [plateCheckResult, setPlateCheckResult] = useState<{
  2195. is_empty: boolean;
  2196. confidence: number;
  2197. difference_percent: number;
  2198. message: string;
  2199. debug_image_url?: string;
  2200. needs_calibration: boolean;
  2201. light_warning?: boolean;
  2202. reference_count?: number;
  2203. max_references?: number;
  2204. roi?: { x: number; y: number; w: number; h: number };
  2205. } | null>(null);
  2206. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2207. const [isCalibrating, setIsCalibrating] = useState(false);
  2208. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2209. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2210. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2211. const { data: status } = useQuery({
  2212. queryKey: ['printerStatus', printer.id],
  2213. queryFn: () => api.getPrinterStatus(printer.id),
  2214. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2215. });
  2216. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2217. const { data: firmwareInfo } = useQuery({
  2218. queryKey: ['firmwareUpdate', printer.id],
  2219. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2220. staleTime: 5 * 60 * 1000,
  2221. refetchInterval: 5 * 60 * 1000,
  2222. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2223. });
  2224. // Collect unique tray_info_idx values for cloud filament info lookup
  2225. const trayInfoIds = useMemo(() => {
  2226. const ids = new Set<string>();
  2227. if (status?.ams) {
  2228. for (const ams of status.ams) {
  2229. for (const tray of ams.tray || []) {
  2230. if (tray.tray_info_idx) {
  2231. ids.add(tray.tray_info_idx);
  2232. }
  2233. }
  2234. }
  2235. }
  2236. for (const vt of status?.vt_tray ?? []) {
  2237. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2238. }
  2239. if (status?.nozzle_rack) {
  2240. for (const slot of status.nozzle_rack) {
  2241. if (slot.filament_id) {
  2242. ids.add(slot.filament_id);
  2243. }
  2244. }
  2245. }
  2246. return Array.from(ids);
  2247. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2248. // Collect loaded filament types for queue widget filtering
  2249. const loadedFilamentTypes = useMemo(() => {
  2250. const types = new Set<string>();
  2251. if (status?.ams) {
  2252. for (const ams of status.ams) {
  2253. for (const tray of ams.tray || []) {
  2254. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2255. }
  2256. }
  2257. }
  2258. for (const vt of status?.vt_tray ?? []) {
  2259. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2260. }
  2261. return types;
  2262. }, [status?.ams, status?.vt_tray]);
  2263. // Collect loaded filament type+color pairs for queue widget override matching
  2264. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2265. const loadedFilaments = useMemo(() => {
  2266. const filaments = new Set<string>();
  2267. if (status?.ams) {
  2268. for (const ams of status.ams) {
  2269. for (const tray of ams.tray || []) {
  2270. if (tray.tray_type && tray.tray_color) {
  2271. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2272. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2273. }
  2274. }
  2275. }
  2276. }
  2277. for (const vt of status?.vt_tray ?? []) {
  2278. if (vt.tray_type && vt.tray_color) {
  2279. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2280. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2281. }
  2282. }
  2283. return filaments;
  2284. }, [status?.ams, status?.vt_tray]);
  2285. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2286. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2287. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2288. const loadedVariants = useMemo(() => {
  2289. const variants = new Set<string>();
  2290. if (status?.ams) {
  2291. for (const ams of status.ams) {
  2292. for (const tray of ams.tray || []) {
  2293. if (tray.tray_type && tray.tray_color) {
  2294. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2295. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. for (const vt of status?.vt_tray ?? []) {
  2301. if (vt.tray_type && vt.tray_color) {
  2302. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2303. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2304. }
  2305. }
  2306. return variants;
  2307. }, [status?.ams, status?.vt_tray]);
  2308. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2309. const { data: filamentInfo } = useQuery({
  2310. queryKey: ['filamentInfo', trayInfoIds],
  2311. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2312. enabled: trayInfoIds.length > 0,
  2313. staleTime: 5 * 60 * 1000, // 5 minutes
  2314. });
  2315. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2316. const { data: slotPresets } = useQuery({
  2317. queryKey: ['slotPresets', printer.id],
  2318. queryFn: () => api.getSlotPresets(printer.id),
  2319. staleTime: 2 * 60 * 1000, // 2 minutes
  2320. });
  2321. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2322. // Only queried when there's a running print backed by an archive; shared
  2323. // React Query cache with the Queue / Archives pages keeps it cheap.
  2324. const activeArchiveId =
  2325. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2326. const { data: activeArchivePlates } = useQuery({
  2327. queryKey: ['archive-plates', activeArchiveId],
  2328. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2329. enabled: activeArchiveId != null,
  2330. staleTime: 5 * 60 * 1000,
  2331. });
  2332. const activePlateLabel = (() => {
  2333. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2334. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2335. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2336. })();
  2337. // Fetch user-defined AMS friendly names from the database
  2338. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2339. queryKey: ['amsLabels', printer.id],
  2340. queryFn: () => api.getAmsLabels(printer.id),
  2341. staleTime: 5 * 60 * 1000, // 5 minutes
  2342. });
  2343. // Cache WiFi signal to prevent it disappearing on updates
  2344. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2345. useEffect(() => {
  2346. if (status?.wifi_signal != null) {
  2347. setCachedWifiSignal(status.wifi_signal);
  2348. }
  2349. }, [status?.wifi_signal]);
  2350. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2351. // Cache connected state to prevent flicker when status briefly becomes undefined
  2352. const cachedConnected = useRef<boolean | undefined>(undefined);
  2353. useEffect(() => {
  2354. if (status?.connected !== undefined) {
  2355. cachedConnected.current = status.connected;
  2356. }
  2357. }, [status?.connected]);
  2358. const isConnected = status?.connected ?? cachedConnected.current;
  2359. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2360. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2361. useEffect(() => {
  2362. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2363. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2364. }
  2365. }, [status?.ams_extruder_map]);
  2366. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2367. ? status.ams_extruder_map
  2368. : cachedAmsExtruderMap.current;
  2369. // Same caching for the Filament Track Switch inlet bindings, for the same
  2370. // reason: a partial MQTT frame briefly empties the map and the badges would
  2371. // otherwise blink out.
  2372. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2373. useEffect(() => {
  2374. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2375. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2376. }
  2377. }, [status?.ams_switch_inlet]);
  2378. const ftsInstalled = status?.fila_switch?.installed === true;
  2379. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2380. ? status.ams_switch_inlet
  2381. : cachedAmsSwitchInlet.current;
  2382. // Cache AMS data to prevent it disappearing on idle/offline printers
  2383. const cachedAmsData = useRef<AMSUnit[]>([]);
  2384. useEffect(() => {
  2385. if (status?.ams && status.ams.length > 0) {
  2386. cachedAmsData.current = status.ams;
  2387. }
  2388. }, [status?.ams]);
  2389. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2390. // #2532: the K-profile line only exists on slots the printer has actually
  2391. // calibrated. The AMS units and the external-spool group are flex siblings in
  2392. // one row, so on a card that shows a value anywhere, the slots without one
  2393. // reserve the same height -- otherwise their fill bars sit a line above their
  2394. // neighbours'. A card with no calibrated slot at all is unaffected.
  2395. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2396. || (status?.vt_tray ?? []).some(tray => tray.k);
  2397. // Confirm a drying cycle actually started (#2533). Firmware answers
  2398. // ams_filament_drying with result=success even when it then silently declines,
  2399. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2400. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2401. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2402. // means the printer took the command and dropped it.
  2403. useEffect(() => {
  2404. if (!dryStartWatch) return;
  2405. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2406. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2407. }, [dryStartWatch, amsData]);
  2408. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2409. // otherwise rearm the timeout on every frame, so it would never elapse.
  2410. useEffect(() => {
  2411. if (!dryStartWatch) return;
  2412. const timer = setTimeout(() => {
  2413. setDryStartWatch(null);
  2414. showToast(t('printers.drying.toastNotStarted'), 'error');
  2415. }, DRY_START_CONFIRM_MS);
  2416. return () => clearTimeout(timer);
  2417. }, [dryStartWatch, showToast, t]);
  2418. // Cache tray_now to prevent flickering when undefined values come in
  2419. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2420. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2421. const cachedTrayNow = useRef<number | undefined>(undefined);
  2422. const currentTrayNow = status?.tray_now;
  2423. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2424. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2425. cachedTrayNow.current = currentTrayNow;
  2426. } else if (currentTrayNow === 255) {
  2427. cachedTrayNow.current = undefined;
  2428. }
  2429. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2430. ? currentTrayNow
  2431. : cachedTrayNow.current;
  2432. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2433. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2434. // expectedTray = the slot the firmware now expects filament in
  2435. // previousTray = the slot that ran out
  2436. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2437. // so these are often different — the graphic highlights the expected one.
  2438. const expectedTray = status?.expected_tray ?? null;
  2439. const previousTray = status?.previous_tray ?? null;
  2440. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2441. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2442. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2443. if (globalId === null) return null;
  2444. if (globalId === 254) return t('printers.expectedSlot.external');
  2445. if (globalId >= 128 && globalId <= 135) {
  2446. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2447. }
  2448. const amsId = Math.floor(globalId / 4);
  2449. const slot = globalId % 4;
  2450. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2451. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2452. };
  2453. const runoutGuidance = status?.state === 'PAUSE'
  2454. ? {
  2455. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2456. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2457. }
  2458. : null;
  2459. // Fetch smart plug for this printer
  2460. const { data: smartPlug } = useQuery({
  2461. queryKey: ['smartPlugByPrinter', printer.id],
  2462. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2463. });
  2464. // Fetch script plugs for this printer (for multi-device control)
  2465. const { data: scriptPlugs } = useQuery({
  2466. queryKey: ['scriptPlugsByPrinter', printer.id],
  2467. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2468. });
  2469. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2470. const { data: plugStatus } = useQuery({
  2471. queryKey: ['smartPlugStatus', smartPlug?.id],
  2472. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2473. enabled: !!smartPlug,
  2474. refetchInterval: 10000, // 10 seconds for real-time power display
  2475. });
  2476. // Fetch queue count for this printer
  2477. const { data: queueItems } = useQuery({
  2478. queryKey: ['queue', printer.id, 'pending'],
  2479. queryFn: () => api.getQueue(printer.id, 'pending'),
  2480. });
  2481. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2482. // so the badge only shows on printers that can actually run the queued jobs.
  2483. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2484. const queueCount = useMemo(() => {
  2485. if (!queueItems?.length) return 0;
  2486. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2487. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2488. // Fetch currently printing queue item to show who started it (Issue #206)
  2489. const { data: printingQueueItems } = useQuery({
  2490. queryKey: ['queue', printer.id, 'printing'],
  2491. queryFn: () => api.getQueue(printer.id, 'printing'),
  2492. enabled: status?.state === 'RUNNING',
  2493. });
  2494. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2495. const { data: reprintUser } = useQuery({
  2496. queryKey: ['currentPrintUser', printer.id],
  2497. queryFn: () => api.getCurrentPrintUser(printer.id),
  2498. enabled: status?.state === 'RUNNING',
  2499. });
  2500. // Combine both sources: queue item user takes precedence, then reprint user
  2501. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2502. // Fetch last completed print for this printer
  2503. const { data: lastPrints } = useQuery({
  2504. queryKey: ['archives', printer.id, 'last'],
  2505. queryFn: () => api.getArchives(printer.id, 1, 0),
  2506. enabled: status?.connected && status?.state !== 'RUNNING',
  2507. });
  2508. const lastPrint = lastPrints?.[0];
  2509. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2510. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2511. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2512. // gate is up and the just-finished print asked for a verdict, offer
  2513. // Good/Reject right where the operator releases the plate. Releasing the
  2514. // plate without answering stays possible — the two are orthogonal (though
  2515. // the confirm_default_good_on_plate_clear setting can couple them).
  2516. // Only offered to whoever may record it: the PATCH checks archives:update
  2517. // against the archive's owner, so for anyone else the pair could only fail.
  2518. const pendingConfirmArchive =
  2519. lastPrint &&
  2520. lastPrint.status === 'completed' &&
  2521. lastPrint.confirm_requested &&
  2522. lastPrint.user_verdict == null &&
  2523. canModify('archives', 'update', lastPrint.created_by_id)
  2524. ? lastPrint
  2525. : null;
  2526. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2527. // Auto Power Off the printer is powered down exactly when the operator clears the
  2528. // plate. Hiding the control there left no way to release the gate (#2864).
  2529. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2530. const activePrintName = status?.current_print && isPrintingOrPaused
  2531. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2532. : null;
  2533. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2534. useEffect(() => {
  2535. if (activePrintName) {
  2536. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2537. } else if (!needsPlateClear) {
  2538. setRetainedPrintJob(null);
  2539. }
  2540. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2541. const plateStatus = (() => {
  2542. // Connected-only because the pill's only render site sits inside the live-status
  2543. // panel. For a powered-down printer the plate-clear button itself carries the
  2544. // state — see the standalone slot below the status block (#2864).
  2545. if (!requirePlateClear || !status?.connected) return null;
  2546. if (isPrintingOrPaused) {
  2547. return {
  2548. label: t('printers.plateStatus.inUse'),
  2549. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2550. };
  2551. }
  2552. if (status.awaiting_plate_clear) {
  2553. return {
  2554. label: t('printers.plateStatus.notCleared'),
  2555. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2556. };
  2557. }
  2558. return {
  2559. label: t('printers.plateStatus.cleared'),
  2560. className: 'bg-status-ok/20 text-status-ok',
  2561. };
  2562. })();
  2563. const plateStatusPill = plateStatus ? (
  2564. <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}`}>
  2565. {plateStatus.label}
  2566. </span>
  2567. ) : null;
  2568. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2569. const shouldHide = hideIfDisconnected && isConnected === false;
  2570. const deleteMutation = useMutation({
  2571. mutationFn: (options: { deleteArchives: boolean }) =>
  2572. api.deletePrinter(printer.id, options.deleteArchives),
  2573. onSuccess: () => {
  2574. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2575. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2576. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2577. },
  2578. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2579. });
  2580. const connectMutation = useMutation({
  2581. mutationFn: () => api.connectPrinter(printer.id),
  2582. onSuccess: () => {
  2583. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2584. },
  2585. });
  2586. const forceRefreshMutation = useMutation({
  2587. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2588. onSuccess: () => {
  2589. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2590. showToast(t('printers.forceRefreshSuccess'), 'success');
  2591. },
  2592. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2593. });
  2594. const unlinkSpoolMutation = useMutation({
  2595. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2596. onSuccess: (result) => {
  2597. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2598. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2599. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2600. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2601. },
  2602. onError: (error: Error) => {
  2603. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2604. },
  2605. });
  2606. // AMS drying mutations
  2607. const startDryingMutation = useMutation({
  2608. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2609. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2610. onSuccess: (_data, { amsId }) => {
  2611. setDryingPopoverAmsId(null);
  2612. setDryStartWatch({ amsId });
  2613. // "Command sent", not "drying started" — at this point the printer has only
  2614. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2615. // the cycle is genuinely live; the watcher below covers the case where it
  2616. // never appears.
  2617. showToast(t('printers.drying.toastCommandSent'), 'success');
  2618. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2619. },
  2620. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2621. });
  2622. // Scheduled (delayed / at-time) drying runs (#2638)
  2623. const scheduleDryingMutation = useMutation({
  2624. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2625. api.createScheduledDrying({
  2626. printer_id: printer.id,
  2627. ams_id: params.amsId,
  2628. temp: params.temp,
  2629. duration_hours: params.duration,
  2630. filament: params.filament,
  2631. rotate_tray: params.rotateTray,
  2632. start_after: params.startAfter,
  2633. }),
  2634. onSuccess: () => {
  2635. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2636. setDryingPopoverAmsId(null);
  2637. },
  2638. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2639. });
  2640. const stopDryingMutation = useMutation({
  2641. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2642. onSuccess: () => {
  2643. setDryStartWatch(null);
  2644. showToast(t('printers.drying.toastStopped'), 'success');
  2645. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2646. },
  2647. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2648. });
  2649. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2650. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2651. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2652. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2653. // showing the old backup state until the user reopens it.
  2654. const setAmsBackupMutation = useMutation({
  2655. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2656. onSuccess: (_data, enabled) => {
  2657. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2658. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2659. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2660. },
  2661. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2662. });
  2663. // Smart plug control mutations
  2664. const powerControlMutation = useMutation({
  2665. mutationFn: (action: 'on' | 'off') =>
  2666. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2667. onSuccess: () => {
  2668. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2669. },
  2670. });
  2671. const toggleAutoOffMutation = useMutation({
  2672. mutationFn: (enabled: boolean) =>
  2673. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2674. onSuccess: () => {
  2675. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2676. // Also invalidate the smart-plugs list to keep Settings page in sync
  2677. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2678. },
  2679. });
  2680. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2681. const runScriptMutation = useMutation({
  2682. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2683. onSuccess: () => {
  2684. showToast(t('printers.toast.scriptTriggered'));
  2685. },
  2686. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2687. });
  2688. // Print control mutations
  2689. const stopPrintMutation = useMutation({
  2690. mutationFn: () => api.stopPrint(printer.id),
  2691. onSuccess: () => {
  2692. showToast(t('printers.toast.printStopped'));
  2693. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2694. },
  2695. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2696. });
  2697. const pausePrintMutation = useMutation({
  2698. mutationFn: () => api.pausePrint(printer.id),
  2699. onSuccess: () => {
  2700. showToast(t('printers.toast.printPaused'));
  2701. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2702. },
  2703. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2704. });
  2705. const resumePrintMutation = useMutation({
  2706. mutationFn: () => api.resumePrint(printer.id),
  2707. onSuccess: () => {
  2708. showToast(t('printers.toast.printResumed'));
  2709. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2710. },
  2711. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2712. });
  2713. const clearPlateMutation = useMutation({
  2714. mutationFn: () => api.clearPlate(printer.id),
  2715. onSuccess: () => {
  2716. showToast(t('queue.clearPlateSuccess'));
  2717. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2718. old ? { ...old, awaiting_plate_clear: false } : old
  2719. );
  2720. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2721. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2722. },
  2723. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2724. });
  2725. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2726. // reject goes through the dialog for the optional reason + reprint.
  2727. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2728. // Only "good" is answered on the card. A reject wants a reason and possibly
  2729. // a reprint, so that button opens the dialog instead — and the parameter
  2730. // says as much, rather than accepting a verdict this path cannot send and
  2731. // then reporting it as good.
  2732. const cardVerdictMutation = useMutation({
  2733. mutationFn: (verdict: 'good') =>
  2734. api.updateArchive(pendingConfirmArchive!.id, {
  2735. user_verdict: verdict,
  2736. user_verdict_source: 'printer_card',
  2737. }),
  2738. onSuccess: () => {
  2739. showToast(t('confirmOutcome.savedGood'), 'success');
  2740. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2741. },
  2742. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2743. });
  2744. // Rendered from two places: inside the live-status block for a connected printer,
  2745. // and standalone below it for a powered-down one, whose status block isn't rendered
  2746. // at all (#2864). Shared so the two can't drift apart.
  2747. const expandedClearPlateButton = (
  2748. <>
  2749. {pendingConfirmArchive && (
  2750. <div className="mt-2 flex items-center gap-1.5">
  2751. <span
  2752. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2753. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2754. >
  2755. {t('confirmOutcome.cardPrompt')}
  2756. </span>
  2757. <button
  2758. type="button"
  2759. onClick={() => setShowConfirmOutcome(true)}
  2760. disabled={cardVerdictMutation.isPending}
  2761. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2762. title={t('confirmOutcome.reject')}
  2763. >
  2764. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2765. </button>
  2766. <button
  2767. type="button"
  2768. onClick={() => cardVerdictMutation.mutate('good')}
  2769. disabled={cardVerdictMutation.isPending}
  2770. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2771. title={t('confirmOutcome.good')}
  2772. >
  2773. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2774. </button>
  2775. </div>
  2776. )}
  2777. <button
  2778. type="button"
  2779. onClick={() => clearPlateMutation.mutate()}
  2780. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2781. 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"
  2782. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2783. >
  2784. {clearPlateMutation.isPending ? (
  2785. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2786. ) : (
  2787. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2788. )}
  2789. {t('printers.plateStatus.markCleared')}
  2790. </button>
  2791. {showConfirmOutcome && pendingConfirmArchive && (
  2792. <ConfirmOutcomeDialog
  2793. archiveId={pendingConfirmArchive.id}
  2794. onClose={() => setShowConfirmOutcome(false)}
  2795. />
  2796. )}
  2797. </>
  2798. );
  2799. const nozzleTemperatureMutation = useMutation({
  2800. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2801. api.setNozzleTemperature(printer.id, target, nozzle),
  2802. onSuccess: (result) => {
  2803. setStatusControlMenu(null);
  2804. showToast(result.message);
  2805. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2806. },
  2807. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2808. });
  2809. const bedTemperatureMutation = useMutation({
  2810. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2811. onSuccess: (result) => {
  2812. setStatusControlMenu(null);
  2813. showToast(result.message);
  2814. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2815. },
  2816. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2817. });
  2818. const chamberTemperatureMutation = useMutation({
  2819. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2820. onSuccess: (result) => {
  2821. setStatusControlMenu(null);
  2822. showToast(result.message);
  2823. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2824. },
  2825. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2826. });
  2827. const fanSpeedMutation = useMutation({
  2828. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2829. api.setFanSpeed(printer.id, fan, speed),
  2830. onMutate: async ({ fan, speed }) => {
  2831. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2832. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2833. const fanField = {
  2834. part: 'cooling_fan_speed',
  2835. aux: 'big_fan1_speed',
  2836. aux2: 'left_aux_fan_speed',
  2837. chamber: 'big_fan2_speed',
  2838. }[fan];
  2839. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2840. old ? { ...old, [fanField]: speed } : old
  2841. );
  2842. return { previousStatus };
  2843. },
  2844. onSuccess: (result) => {
  2845. setStatusControlMenu(null);
  2846. showToast(result.message);
  2847. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2848. },
  2849. onError: (error: Error, _variables, context) => {
  2850. if (context?.previousStatus) {
  2851. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2852. }
  2853. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2854. },
  2855. });
  2856. const selectExtruderMutation = useMutation({
  2857. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2858. onMutate: async (extruder) => {
  2859. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2860. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2861. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2862. old ? { ...old, active_extruder: extruder } : old
  2863. );
  2864. return { previousStatus };
  2865. },
  2866. onSuccess: (result) => {
  2867. setStatusControlMenu(null);
  2868. showToast(result.message);
  2869. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2870. },
  2871. onError: (error: Error, _extruder, context) => {
  2872. if (context?.previousStatus) {
  2873. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2874. }
  2875. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2876. },
  2877. });
  2878. // Chamber light mutation with optimistic update
  2879. const chamberLightMutation = useMutation({
  2880. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2881. onMutate: async (on) => {
  2882. // Cancel any outgoing refetches
  2883. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2884. // Snapshot the previous value
  2885. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2886. // Optimistically update
  2887. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2888. ...old,
  2889. chamber_light: on,
  2890. }));
  2891. return { previousStatus };
  2892. },
  2893. onSuccess: (_, on) => {
  2894. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2895. },
  2896. onError: (error: Error, _, context) => {
  2897. // Rollback on error
  2898. if (context?.previousStatus) {
  2899. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2900. }
  2901. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2902. },
  2903. });
  2904. // Print speed mutation with optimistic update
  2905. const printSpeedMutation = useMutation({
  2906. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2907. onMutate: async (mode) => {
  2908. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2909. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2910. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2911. ...old,
  2912. speed_level: mode,
  2913. }));
  2914. return { previousStatus };
  2915. },
  2916. onError: (error: Error, _, context) => {
  2917. if (context?.previousStatus) {
  2918. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2919. }
  2920. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2921. },
  2922. });
  2923. const airductMutation = useMutation({
  2924. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2925. onMutate: async (mode) => {
  2926. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2927. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2928. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2929. ...old,
  2930. airduct_mode: mode === 'cooling' ? 0 : 1,
  2931. }));
  2932. return { previousStatus };
  2933. },
  2934. onError: (error: Error, _, context) => {
  2935. if (context?.previousStatus) {
  2936. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2937. }
  2938. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2939. },
  2940. });
  2941. const bedJogMutation = useMutation({
  2942. mutationFn: ({ distance }: { distance: number }) =>
  2943. api.bedJog(printer.id, distance),
  2944. onError: (error: Error) =>
  2945. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2946. });
  2947. const xyJogMutation = useMutation({
  2948. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2949. api.xyJog(printer.id, x, y),
  2950. onError: (error: Error) =>
  2951. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2952. });
  2953. const extruderJogMutation = useMutation({
  2954. mutationFn: (distance: number) =>
  2955. api.extruderJog(printer.id, distance),
  2956. onError: (error: Error) =>
  2957. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2958. });
  2959. const homeAxesMutation = useMutation({
  2960. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2961. onSuccess: () => {
  2962. showToast(t('printers.bedJog.homingStarted'));
  2963. },
  2964. onError: (error: Error) =>
  2965. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2966. });
  2967. // Plate detection setting mutation
  2968. const plateDetectionMutation = useMutation({
  2969. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2970. onSuccess: () => {
  2971. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2972. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2973. },
  2974. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2975. });
  2976. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2977. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2978. // metrics, and the print picker — so flipping this flag puts the printer
  2979. // out of service across every consumer in one place. Used from the
  2980. // overflow menu and EditPrinterModal.
  2981. const maintenanceMutation = useMutation({
  2982. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2983. onSuccess: (_data, isActive) => {
  2984. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2985. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2986. showToast(
  2987. isActive
  2988. ? t('printers.maintenance.toastExited', { name: printer.name })
  2989. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2990. 'success',
  2991. );
  2992. },
  2993. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2994. });
  2995. // Confirm before entering maintenance on a printing printer (entering mode
  2996. // disconnects MQTT, which stops progress tracking + completion notifications
  2997. // for the in-flight job).
  2998. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2999. const handleEnterMaintenance = () => {
  3000. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  3001. setConfirmMaintenanceEnter(true);
  3002. } else {
  3003. maintenanceMutation.mutate(false);
  3004. }
  3005. };
  3006. // Query for printable objects (for skip functionality)
  3007. // Fetch when printing with 2+ objects OR when modal is open
  3008. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  3009. const { data: objectsData } = useQuery({
  3010. queryKey: ['printableObjects', printer.id],
  3011. queryFn: () => api.getPrintableObjects(printer.id),
  3012. enabled: showSkipObjectsModal || isPrintingWithObjects,
  3013. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  3014. });
  3015. // State for tracking which AMS slot is being refreshed
  3016. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  3017. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  3018. const seenBusyStateRef = useRef<boolean>(false);
  3019. // Fallback timeout ref
  3020. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3021. // Minimum display time passed
  3022. const minTimePassedRef = useRef<boolean>(false);
  3023. // AMS slot refresh mutation
  3024. const refreshAmsSlotMutation = useMutation({
  3025. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  3026. api.refreshAmsSlot(printer.id, amsId, slotId),
  3027. onMutate: ({ amsId, slotId }) => {
  3028. // Clear any existing timeout
  3029. if (refreshTimeoutRef.current) {
  3030. clearTimeout(refreshTimeoutRef.current);
  3031. }
  3032. // Reset state
  3033. seenBusyStateRef.current = false;
  3034. minTimePassedRef.current = false;
  3035. setRefreshingSlot({ amsId, slotId });
  3036. // Minimum display time (2 seconds)
  3037. setTimeout(() => {
  3038. minTimePassedRef.current = true;
  3039. }, 2000);
  3040. // Fallback timeout (30 seconds max)
  3041. refreshTimeoutRef.current = setTimeout(() => {
  3042. setRefreshingSlot(null);
  3043. }, 30000);
  3044. },
  3045. onSuccess: (data) => {
  3046. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  3047. },
  3048. onError: (error: Error) => {
  3049. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  3050. if (refreshTimeoutRef.current) {
  3051. clearTimeout(refreshTimeoutRef.current);
  3052. }
  3053. setRefreshingSlot(null);
  3054. },
  3055. });
  3056. // AMS load/unload mutations (#891)
  3057. const loadAmsTrayMutation = useMutation({
  3058. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  3059. api.loadAmsTray(printer.id, trayId, extruderId),
  3060. onSuccess: (data) => {
  3061. setFeedDirectionRequest(null);
  3062. showToast(data.message || t('printers.toast.loadInitiated'));
  3063. },
  3064. onError: (error: Error) => {
  3065. setFeedDirectionRequest(null);
  3066. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3067. },
  3068. });
  3069. const unloadAmsMutation = useMutation({
  3070. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3071. onSuccess: (data) => {
  3072. showToast(data.message || t('printers.toast.unloadInitiated'));
  3073. },
  3074. onError: (error: Error) => {
  3075. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3076. },
  3077. });
  3078. // Pending "which hotend?" question, non-null only while the dialog is open.
  3079. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3080. // load command has to name one — see FeedDirectionModal.
  3081. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3082. trayId: number;
  3083. amsId: number;
  3084. slotId: number;
  3085. slotLabel: string;
  3086. } | null>(null);
  3087. // Whether a load from this printer has to ask which hotend to feed.
  3088. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3089. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3090. // The external holder needs no question: its two tray ids name the side
  3091. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3092. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3093. // external spool, because it would occupy an extruder channel permanently.
  3094. //
  3095. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3096. // carries does not address an HT unit, so the load is refused whatever the
  3097. // answer. Asking first would only put a dialog in front of the same error.
  3098. const isExternal = amsId === 255;
  3099. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3100. loadAmsTrayMutation.mutate({ trayId });
  3101. return;
  3102. }
  3103. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3104. // front rather than sending a command the firmware will drop. BambuStudio
  3105. // shows the same message and returns without publishing anything.
  3106. if (!status?.fila_switch?.ready) {
  3107. showToast(t('printers.ams.switchNotReady'), 'warning');
  3108. return;
  3109. }
  3110. setFeedDirectionRequest({
  3111. trayId,
  3112. amsId,
  3113. slotId,
  3114. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3115. });
  3116. };
  3117. // Plate references state
  3118. const [plateReferences, setPlateReferences] = useState<{
  3119. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3120. max_references: number;
  3121. } | null>(null);
  3122. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3123. // Fetch plate references
  3124. const fetchPlateReferences = async () => {
  3125. try {
  3126. const data = await api.getPlateReferences(printer.id);
  3127. setPlateReferences(data);
  3128. } catch {
  3129. // Ignore errors - references will show as empty
  3130. }
  3131. };
  3132. // Toggle plate detection enabled/disabled
  3133. const handleTogglePlateDetection = () => {
  3134. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3135. };
  3136. // Open plate detection management modal (for calibration/references)
  3137. const handleOpenPlateManagement = async () => {
  3138. setIsCheckingPlate(true);
  3139. setPlateCheckResult(null);
  3140. // Auto-turn on light if it's off
  3141. const lightWasOff = status?.chamber_light === false;
  3142. setPlateCheckLightWasOff(lightWasOff);
  3143. if (lightWasOff) {
  3144. await api.setChamberLight(printer.id, true);
  3145. // Wait for light to physically turn on and camera to adjust exposure
  3146. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3147. await new Promise(resolve => setTimeout(resolve, 2500));
  3148. }
  3149. try {
  3150. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3151. setPlateCheckResult(result);
  3152. fetchPlateReferences();
  3153. } catch (error) {
  3154. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3155. // Restore light if check failed
  3156. if (lightWasOff) {
  3157. await api.setChamberLight(printer.id, false);
  3158. setPlateCheckLightWasOff(false);
  3159. }
  3160. } finally {
  3161. setIsCheckingPlate(false);
  3162. }
  3163. };
  3164. // Close plate check modal and restore light state
  3165. const closePlateCheckModal = useCallback(async () => {
  3166. setPlateCheckResult(null);
  3167. // Restore light to original state if we turned it on
  3168. if (plateCheckLightWasOff) {
  3169. await api.setChamberLight(printer.id, false);
  3170. setPlateCheckLightWasOff(false);
  3171. }
  3172. }, [plateCheckLightWasOff, printer.id]);
  3173. // Calibrate plate detection handler
  3174. const handleCalibratePlate = async (label?: string) => {
  3175. setIsCalibrating(true);
  3176. try {
  3177. const result = await api.calibratePlateDetection(printer.id, { label });
  3178. if (result.success) {
  3179. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3180. // Refresh references and re-check
  3181. fetchPlateReferences();
  3182. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3183. setPlateCheckResult(checkResult);
  3184. } else {
  3185. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3186. }
  3187. } catch (error) {
  3188. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3189. } finally {
  3190. setIsCalibrating(false);
  3191. }
  3192. };
  3193. // Update reference label
  3194. const handleUpdateRefLabel = async (index: number, label: string) => {
  3195. try {
  3196. await api.updatePlateReferenceLabel(printer.id, index, label);
  3197. setEditingRefLabel(null);
  3198. fetchPlateReferences();
  3199. } catch (error) {
  3200. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3201. }
  3202. };
  3203. // Delete reference
  3204. const handleDeleteRef = async (index: number) => {
  3205. try {
  3206. await api.deletePlateReference(printer.id, index);
  3207. showToast(t('printers.toast.referenceDeleted'), 'success');
  3208. fetchPlateReferences();
  3209. // Re-check to update counts
  3210. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3211. setPlateCheckResult(checkResult);
  3212. } catch (error) {
  3213. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3214. }
  3215. };
  3216. // Save ROI settings
  3217. const handleSaveRoi = async () => {
  3218. if (!editingRoi) return;
  3219. setIsSavingRoi(true);
  3220. try {
  3221. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3222. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3223. setEditingRoi(null);
  3224. // Re-check to see new ROI in action
  3225. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3226. setPlateCheckResult(checkResult);
  3227. } catch (error) {
  3228. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3229. } finally {
  3230. setIsSavingRoi(false);
  3231. }
  3232. };
  3233. // Close plate check modal on Escape key
  3234. useEffect(() => {
  3235. const handleEscape = (e: KeyboardEvent) => {
  3236. if (e.key === 'Escape' && plateCheckResult) {
  3237. closePlateCheckModal();
  3238. }
  3239. };
  3240. window.addEventListener('keydown', handleEscape);
  3241. return () => window.removeEventListener('keydown', handleEscape);
  3242. }, [plateCheckResult, closePlateCheckModal]);
  3243. // Watch ams_status_main to detect when RFID read completes
  3244. // ams_status_main: 0=idle, 2=rfid_identifying
  3245. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3246. useEffect(() => {
  3247. if (!refreshingSlot) return;
  3248. const amsStatus = status?.ams_status_main ?? 0;
  3249. // Track when we see non-idle state (printer is working)
  3250. if (amsStatus !== 0) {
  3251. seenBusyStateRef.current = true;
  3252. // Cancel any deferred clear since we're back to busy
  3253. if (deferredClearRef.current) {
  3254. clearTimeout(deferredClearRef.current);
  3255. deferredClearRef.current = null;
  3256. }
  3257. }
  3258. // When we've seen busy and now idle, clear (with min time check)
  3259. if (seenBusyStateRef.current && amsStatus === 0) {
  3260. if (minTimePassedRef.current) {
  3261. // Min time passed - clear now
  3262. if (refreshTimeoutRef.current) {
  3263. clearTimeout(refreshTimeoutRef.current);
  3264. }
  3265. setRefreshingSlot(null);
  3266. } else {
  3267. // Schedule clear after min time (2 seconds from start)
  3268. if (!deferredClearRef.current) {
  3269. deferredClearRef.current = setTimeout(() => {
  3270. if (refreshTimeoutRef.current) {
  3271. clearTimeout(refreshTimeoutRef.current);
  3272. }
  3273. setRefreshingSlot(null);
  3274. }, 2000);
  3275. }
  3276. }
  3277. }
  3278. return () => {
  3279. if (deferredClearRef.current) {
  3280. clearTimeout(deferredClearRef.current);
  3281. }
  3282. };
  3283. }, [status?.ams_status_main, refreshingSlot]);
  3284. useEffect(() => {
  3285. if (!showMenu) return;
  3286. const handleClickOutside = (event: MouseEvent) => {
  3287. const target = event.target as Node;
  3288. if (!printerActionsMenuRef.current?.contains(target)) {
  3289. setShowMenu(false);
  3290. }
  3291. };
  3292. document.addEventListener('mousedown', handleClickOutside);
  3293. return () => document.removeEventListener('mousedown', handleClickOutside);
  3294. }, [showMenu]);
  3295. if (shouldHide) {
  3296. return null;
  3297. }
  3298. // Size-based styling helpers
  3299. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3300. // width, its thumbnail and the printer name, but every label inside the
  3301. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3302. // S one -- the disparity was worst exactly where someone asking for more
  3303. // room ends up. These custom properties carry the scaled sizes into the
  3304. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3305. // unless they reach for a size that is already asking for more space.
  3306. // Plain computation rather than useMemo: this sits after the card's early
  3307. // returns, where a hook would break the rules-of-hooks ordering, and
  3308. // building ten strings per render costs nothing.
  3309. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3310. const getImageSize = () => {
  3311. switch (cardSize) {
  3312. case 1: return 'w-10 h-10';
  3313. case 2: return 'w-14 h-14';
  3314. case 3: return 'w-16 h-16';
  3315. case 4: return 'w-20 h-20';
  3316. default: return 'w-14 h-14';
  3317. }
  3318. };
  3319. const getTitleSize = () => {
  3320. switch (cardSize) {
  3321. case 1: return 'text-base truncate';
  3322. case 2: return 'text-lg';
  3323. case 3: return 'text-xl';
  3324. case 4: return 'text-2xl';
  3325. default: return 'text-lg';
  3326. }
  3327. };
  3328. const getSpacing = () => {
  3329. switch (cardSize) {
  3330. case 1: return 'mb-2';
  3331. case 2: return 'mb-4';
  3332. case 3: return 'mb-5';
  3333. case 4: return 'mb-6';
  3334. default: return 'mb-4';
  3335. }
  3336. };
  3337. // A dropped file always becomes a queue item, so a printer that is busy,
  3338. // offline or mid-drying is no reason to refuse the drop — it only means the
  3339. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3340. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3341. // what this would have done for them.
  3342. //
  3343. // What remains is what the flow actually performs: upload the file, then
  3344. // create a queue item. It never touches printers:control, which is what this
  3345. // used to check — so someone holding that but neither of these had the file
  3346. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3347. // button below has always checked this pair.
  3348. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3349. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3350. // and the modal's own "will start later" toast cannot disagree.
  3351. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3352. const handleCardDragEnter = (e: React.DragEvent) => {
  3353. e.preventDefault();
  3354. dragCounterRef.current++;
  3355. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3356. };
  3357. const handleCardDragOver = (e: React.DragEvent) => {
  3358. e.preventDefault();
  3359. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3360. };
  3361. const handleCardDragLeave = (e: React.DragEvent) => {
  3362. e.preventDefault();
  3363. dragCounterRef.current--;
  3364. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3365. };
  3366. const handleCardDrop = async (e: React.DragEvent) => {
  3367. e.preventDefault();
  3368. dragCounterRef.current = 0;
  3369. setIsDraggingFile(false);
  3370. if (!canDrop) return;
  3371. const droppedFiles = Array.from(e.dataTransfer.files);
  3372. const file = droppedFiles[0];
  3373. if (!file) return;
  3374. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3375. const lower = file.name.toLowerCase();
  3376. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3377. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3378. return;
  3379. }
  3380. setIsDropUploading(true);
  3381. try {
  3382. const result = await api.uploadLibraryFile(file, null);
  3383. // Check printer compatibility if sliced_for_model is available in metadata
  3384. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3385. const printerModel = mapModelCode(printer.model);
  3386. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3387. await api.deleteLibraryFile(result.id).catch(() => {});
  3388. showToast(
  3389. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3390. 'error'
  3391. );
  3392. return;
  3393. }
  3394. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3395. } catch {
  3396. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3397. } finally {
  3398. setIsDropUploading(false);
  3399. }
  3400. };
  3401. const handleCardClick = (e: React.MouseEvent) => {
  3402. if (viewMode !== 'compact' || selectionMode) return;
  3403. const target = e.target as HTMLElement;
  3404. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3405. onOpenCompactCard?.(printer.id);
  3406. };
  3407. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3408. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3409. // Opening a camera in a given mode, without touching which mode is remembered
  3410. // -- the split button's two halves want the same action but disagree about
  3411. // whether the choice was deliberate enough to keep.
  3412. const openCameraIn = (mode: CameraViewMode) => {
  3413. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3414. onOpenEmbeddedCamera(printer.id, printer.name);
  3415. } else {
  3416. openCameraWindow(printer.id);
  3417. }
  3418. };
  3419. // Picking a mode both opens the camera that way and makes it the mode the
  3420. // plain icon uses from now on. A menu that only changed a preference would
  3421. // leave the user with a second click to do the thing they already asked for.
  3422. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3423. [
  3424. {
  3425. mode: 'window' as const,
  3426. icon: <ExternalLink className="w-4 h-4" />,
  3427. label: t('settings.newWindow'),
  3428. title: t('settings.cameraWindowDescription'),
  3429. },
  3430. {
  3431. mode: 'embedded' as const,
  3432. icon: <PictureInPicture2 className="w-4 h-4" />,
  3433. label: t('settings.embeddedOverlay'),
  3434. title: t('settings.cameraOverlayDescription'),
  3435. },
  3436. ]
  3437. ).map(({ mode, icon, label, title }) => ({
  3438. icon,
  3439. // The remembered mode is marked in the label itself: the icon slot already
  3440. // carries the mode's own icon, and a separate tick column would push both
  3441. // entries out of line with every other card menu.
  3442. label: mode === cameraViewMode ? `${label} ✓` : label,
  3443. title,
  3444. onClick: () => {
  3445. onSelectCameraViewMode?.(mode);
  3446. openCameraIn(mode);
  3447. },
  3448. }));
  3449. const renderAmsSlotActions = ({
  3450. amsId,
  3451. slotId,
  3452. loadTrayId,
  3453. isRefreshing,
  3454. includeRfid = true,
  3455. }: {
  3456. amsId: number;
  3457. slotId: number;
  3458. loadTrayId: number;
  3459. isRefreshing?: boolean;
  3460. includeRfid?: boolean;
  3461. }) => {
  3462. const printerBusy = status?.state === 'RUNNING';
  3463. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3464. // ams*4+slot, so the id this menu carries does not name it to the load and
  3465. // unload endpoints — they reject it. Sending no slot falls back to the
  3466. // printer-wide unload, which is what this menu did for every slot before
  3467. // the per-slot form existed. Load has never worked on an HT slot for the
  3468. // same addressing reason; fixing that is a separate change.
  3469. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3470. return (
  3471. <>
  3472. {includeRfid && (
  3473. <button
  3474. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3475. hasPermission('printers:ams_rfid')
  3476. ? 'text-white hover:bg-bambu-dark-tertiary'
  3477. : 'text-bambu-gray/50 cursor-not-allowed'
  3478. }`}
  3479. onClick={(e) => {
  3480. e.stopPropagation();
  3481. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3482. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3483. }}
  3484. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3485. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3486. >
  3487. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3488. {t('printers.rfid.reread')}
  3489. </button>
  3490. )}
  3491. <button
  3492. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3493. hasPermission('printers:control')
  3494. ? 'text-white hover:bg-bambu-dark-tertiary'
  3495. : 'text-bambu-gray/50 cursor-not-allowed'
  3496. }`}
  3497. onClick={(e) => {
  3498. e.stopPropagation();
  3499. if (printerBusy || !hasPermission('printers:control')) return;
  3500. startAmsLoad(amsId, slotId, loadTrayId);
  3501. }}
  3502. disabled={printerBusy || !hasPermission('printers:control')}
  3503. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3504. >
  3505. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3506. {t('printers.ams.load')}
  3507. </button>
  3508. <button
  3509. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3510. hasPermission('printers:control')
  3511. ? 'text-white hover:bg-bambu-dark-tertiary'
  3512. : 'text-bambu-gray/50 cursor-not-allowed'
  3513. }`}
  3514. onClick={(e) => {
  3515. e.stopPropagation();
  3516. if (printerBusy || !hasPermission('printers:control')) return;
  3517. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3518. }}
  3519. disabled={printerBusy || !hasPermission('printers:control')}
  3520. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3521. >
  3522. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3523. {t('printers.ams.unload')}
  3524. </button>
  3525. </>
  3526. );
  3527. };
  3528. const printerActionsMenu = (
  3529. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3530. <Button
  3531. variant="secondary"
  3532. size="sm"
  3533. onClick={() => setShowMenu(!showMenu)}
  3534. title={t('common.more', 'More')}
  3535. className={footerIconButtonClass}
  3536. >
  3537. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3538. </Button>
  3539. {showMenu && (
  3540. <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">
  3541. <button
  3542. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3543. hasPermission('printers:update')
  3544. ? 'hover:bg-bambu-dark-tertiary'
  3545. : 'opacity-50 cursor-not-allowed'
  3546. }`}
  3547. onClick={() => {
  3548. if (!hasPermission('printers:update')) return;
  3549. setShowEditModal(true);
  3550. setShowMenu(false);
  3551. }}
  3552. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3553. >
  3554. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3555. {t('common.edit')}
  3556. </button>
  3557. <button
  3558. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3559. onClick={() => {
  3560. setShowPrinterInfo(true);
  3561. setShowMenu(false);
  3562. }}
  3563. >
  3564. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3565. {t('printers.printerInformation')}
  3566. </button>
  3567. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3568. <button
  3569. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3570. hasPermission('printers:update')
  3571. ? 'hover:bg-bambu-dark-tertiary'
  3572. : 'opacity-50 cursor-not-allowed'
  3573. }`}
  3574. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3575. onClick={() => {
  3576. if (!hasPermission('printers:update')) return;
  3577. setShowMenu(false);
  3578. if (printer.is_active !== false) {
  3579. handleEnterMaintenance();
  3580. } else {
  3581. maintenanceMutation.mutate(true);
  3582. }
  3583. }}
  3584. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3585. >
  3586. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3587. {printer.is_active !== false
  3588. ? t('printers.maintenance.menuEnter')
  3589. : t('printers.maintenance.menuExit')}
  3590. </button>
  3591. <button
  3592. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3593. onClick={() => {
  3594. connectMutation.mutate();
  3595. setShowMenu(false);
  3596. }}
  3597. >
  3598. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3599. {t('printers.reconnect')}
  3600. </button>
  3601. <button
  3602. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3603. disabled={forceRefreshMutation.isPending}
  3604. onClick={() => {
  3605. forceRefreshMutation.mutate();
  3606. setShowMenu(false);
  3607. }}
  3608. >
  3609. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3610. {t('printers.forceRefresh')}
  3611. </button>
  3612. <button
  3613. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3614. onClick={() => {
  3615. setShowMQTTDebug(true);
  3616. setShowMenu(false);
  3617. }}
  3618. >
  3619. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3620. {t('printers.mqttDebug')}
  3621. </button>
  3622. <button
  3623. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3624. onClick={() => {
  3625. setShowDiagnostic(true);
  3626. setShowMenu(false);
  3627. }}
  3628. >
  3629. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3630. {t('diagnostic.runButton')}
  3631. </button>
  3632. <button
  3633. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3634. hasPermission('printers:delete')
  3635. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3636. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3637. }`}
  3638. onClick={() => {
  3639. if (!hasPermission('printers:delete')) return;
  3640. setShowDeleteConfirm(true);
  3641. setShowMenu(false);
  3642. }}
  3643. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3644. >
  3645. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3646. {t('common.delete')}
  3647. </button>
  3648. </div>
  3649. )}
  3650. </div>
  3651. );
  3652. return (
  3653. <Card
  3654. id={`printer-card-${printer.id}`}
  3655. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3656. style={cardScaleStyle}
  3657. onClick={handleCardClick}
  3658. onDragEnter={handleCardDragEnter}
  3659. onDragOver={handleCardDragOver}
  3660. onDragLeave={handleCardDragLeave}
  3661. onDrop={handleCardDrop}
  3662. >
  3663. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3664. {selectionMode && (
  3665. <div
  3666. className="absolute inset-0 z-20 flex items-start p-2"
  3667. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3668. >
  3669. {isSelected ? (
  3670. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3671. ) : (
  3672. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3673. )}
  3674. </div>
  3675. )}
  3676. {/* Drop zone overlay */}
  3677. {(isDraggingFile || isDropUploading) && (
  3678. <div
  3679. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3680. isDropUploading
  3681. ? 'bg-bambu-green/10 border-bambu-green/50'
  3682. : canDrop
  3683. ? 'bg-bambu-green/10 border-bambu-green'
  3684. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3685. }`}
  3686. >
  3687. <div className="text-center">
  3688. {isDropUploading ? (
  3689. <>
  3690. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3691. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3692. </>
  3693. ) : canDrop ? (
  3694. <>
  3695. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3696. <p className="text-sm font-medium text-bambu-green">
  3697. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3698. </p>
  3699. </>
  3700. ) : (
  3701. <>
  3702. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3703. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3704. {!hasPermission('library:upload')
  3705. ? t('fileManager.noPermissionUpload')
  3706. : t('fileManager.noPermissionAddToQueue')}
  3707. </p>
  3708. </>
  3709. )}
  3710. </div>
  3711. </div>
  3712. )}
  3713. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3714. {/* Header */}
  3715. <div className={getSpacing()}>
  3716. {/* Top row: Image, Name, Menu */}
  3717. <div className="flex items-start justify-between gap-2">
  3718. <div className="flex items-center gap-3 min-w-0 flex-1">
  3719. {/* Printer Model Image */}
  3720. <img
  3721. src={getPrinterImage(printer.model)}
  3722. alt={printer.model || t('common.printer')}
  3723. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3724. />
  3725. <div className="min-w-0 flex-1">
  3726. <div className="flex items-center justify-between gap-2">
  3727. <div className="flex min-w-0 items-center gap-2">
  3728. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3729. {/* Connection indicator dot for compact mode */}
  3730. {viewMode === 'compact' && (() => {
  3731. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3732. const hasSevere = hmsErrors.some(isSevereHMSError);
  3733. const hasWarning = hmsErrors.length > 0;
  3734. const pipColor = !status?.connected
  3735. ? 'bg-status-error'
  3736. : hasSevere
  3737. ? 'bg-status-error'
  3738. : hasWarning
  3739. ? 'bg-status-warning'
  3740. : 'bg-status-ok';
  3741. const pipTitle = !status?.connected
  3742. ? t('printers.connection.offline')
  3743. : hasWarning
  3744. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3745. : t('printers.connection.connected');
  3746. return (
  3747. <div
  3748. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3749. title={pipTitle}
  3750. />
  3751. );
  3752. })()}
  3753. </div>
  3754. {viewMode === 'compact' && showClearPlateButton && (
  3755. <button
  3756. type="button"
  3757. onClick={() => clearPlateMutation.mutate()}
  3758. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3759. aria-label={t('printers.plateStatus.markCleared')}
  3760. 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"
  3761. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3762. >
  3763. {clearPlateMutation.isPending ? (
  3764. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3765. ) : (
  3766. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3767. )}
  3768. </button>
  3769. )}
  3770. </div>
  3771. <p className="text-sm text-bambu-gray">
  3772. {printer.model || 'Unknown Model'}
  3773. {/* Nozzle Info - only in expanded. Every fitted size, not
  3774. just nozzles[0]: the array is indexed by extruder, so on a
  3775. dual-nozzle machine with two sizes fitted showing the
  3776. first entry alone named one hotend and implied it was the
  3777. whole printer. Deduplicated, so the usual matching pair
  3778. still reads as a single "0.4mm". */}
  3779. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3780. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3781. • {installedNozzleDiameters(status).join(' / ')}mm
  3782. </span>
  3783. )}
  3784. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3785. <span className="ml-2 text-bambu-gray">
  3786. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3787. {Math.round(maintenanceInfo.total_print_hours)}h
  3788. </span>
  3789. )}
  3790. </p>
  3791. </div>
  3792. </div>
  3793. </div>
  3794. {/* Badges row - only in expanded mode */}
  3795. {viewMode === 'expanded' && (
  3796. <div className="mt-2">
  3797. <div className="flex flex-wrap items-center gap-2">
  3798. {/* Connection status badge (or Maintenance pill when out of service).
  3799. Defensive: only swap when is_active is EXPLICITLY false. An
  3800. undefined / missing field defaults to "active" so the regular
  3801. pill renders — matches the backend default and prevents test
  3802. fixtures (or stale clients) from accidentally tripping the
  3803. maintenance UI. */}
  3804. {printer.is_active === false ? (
  3805. <span
  3806. 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"
  3807. title={t('printers.maintenance.subtitle')}
  3808. >
  3809. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3810. {t('printers.maintenance.pillLabel')}
  3811. </span>
  3812. ) : (
  3813. <span
  3814. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3815. status?.connected
  3816. ? 'bg-status-ok/20 text-status-ok'
  3817. : 'bg-status-error/20 text-status-error'
  3818. }`}
  3819. >
  3820. {status?.connected ? (
  3821. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3822. ) : (
  3823. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3824. )}
  3825. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3826. </span>
  3827. )}
  3828. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3829. {printer.is_active !== false && !status?.connected && (
  3830. <button
  3831. onClick={() => setShowDiagnostic(true)}
  3832. 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"
  3833. title={t('diagnostic.runButton')}
  3834. >
  3835. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3836. {t('diagnostic.runButton')}
  3837. </button>
  3838. )}
  3839. {/* Network connection indicator */}
  3840. {status?.connected && status?.wired_network && (
  3841. <span
  3842. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3843. title={t('printers.connection.ethernet', 'Ethernet')}
  3844. >
  3845. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3846. {t('printers.connection.ethernet', 'Ethernet')}
  3847. </span>
  3848. )}
  3849. {/* WiFi signal indicator */}
  3850. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3851. <span
  3852. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3853. wifiSignal >= -50
  3854. ? 'bg-status-ok/20 text-status-ok'
  3855. : wifiSignal >= -60
  3856. ? 'bg-status-ok/20 text-status-ok'
  3857. : wifiSignal >= -70
  3858. ? 'bg-status-warning/20 text-status-warning'
  3859. : wifiSignal >= -80
  3860. ? 'bg-orange-500/20 text-orange-600'
  3861. : 'bg-status-error/20 text-status-error'
  3862. }`}
  3863. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3864. >
  3865. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3866. {wifiSignal}dBm
  3867. </span>
  3868. )}
  3869. {/* HMS Status Indicator */}
  3870. {status?.connected && (() => {
  3871. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3872. return (
  3873. <button
  3874. onClick={() => setShowHMSModal(true)}
  3875. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3876. knownErrors.length > 0
  3877. ? knownErrors.some(isSevereHMSError)
  3878. ? 'bg-status-error/20 text-status-error'
  3879. : 'bg-status-warning/20 text-status-warning'
  3880. : 'bg-status-ok/20 text-status-ok'
  3881. }`}
  3882. title={t('printers.clickToViewHmsErrors')}
  3883. >
  3884. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3885. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3886. </button>
  3887. );
  3888. })()}
  3889. {/* AI failure detection badge (#1546) — always shown while detection
  3890. is enabled for this printer, like the other health badges. Gray
  3891. "Idle" outside a monitored print, class-colored during one. */}
  3892. {aiDetectionEnabled && (() => {
  3893. const cls = aiDetectionClass(aiDetection);
  3894. const colorClass =
  3895. cls === 'failure'
  3896. ? 'bg-status-error/20 text-status-error'
  3897. : cls === 'warning'
  3898. ? 'bg-status-warning/20 text-status-warning'
  3899. : cls === 'safe'
  3900. ? 'bg-status-ok/20 text-status-ok'
  3901. : cls === 'error'
  3902. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3903. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3904. // 'error' and 'unknown' have no score to quote — saying
  3905. // "Safe (0.000)" for a print nothing is looking at is the
  3906. // whole of #2952.
  3907. const title =
  3908. cls === 'error'
  3909. ? t('printers.aiDetection.tooltipError', {
  3910. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3911. })
  3912. : cls === 'unknown'
  3913. ? t('printers.aiDetection.tooltipUnknown')
  3914. : aiDetection
  3915. ? t('printers.aiDetection.tooltip', {
  3916. status: t(`printers.aiDetection.${cls}`),
  3917. score: aiDetection.score.toFixed(3),
  3918. })
  3919. : t('printers.aiDetection.tooltipIdle');
  3920. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3921. return (
  3922. <button
  3923. onClick={() => setShowAiModal(true)}
  3924. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3925. title={title}
  3926. >
  3927. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3928. {t(`printers.aiDetection.${cls}`)}
  3929. </button>
  3930. );
  3931. })()}
  3932. {/* Maintenance Status Indicator */}
  3933. {maintenanceInfo && (
  3934. <button
  3935. onClick={() => navigate('/maintenance')}
  3936. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3937. maintenanceInfo.due_count > 0
  3938. ? 'bg-status-error/20 text-status-error'
  3939. : maintenanceInfo.warning_count > 0
  3940. ? 'bg-status-warning/20 text-status-warning'
  3941. : 'bg-status-ok/20 text-status-ok'
  3942. }`}
  3943. title={
  3944. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3945. ? `${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`
  3946. : t('printers.maintenanceUpToDate')
  3947. }
  3948. >
  3949. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3950. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3951. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3952. : 'OK'}
  3953. </button>
  3954. )}
  3955. {/* Queue Count Badge */}
  3956. {queueCount > 0 && (
  3957. <button
  3958. onClick={() => navigate('/queue')}
  3959. 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"
  3960. title={t('printers.queue.inQueue', { count: queueCount })}
  3961. >
  3962. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3963. {queueCount}
  3964. </button>
  3965. )}
  3966. {/* Firmware Version Badge */}
  3967. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3968. <button
  3969. onClick={() => setShowFirmwareModal(true)}
  3970. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3971. firmwareInfo.update_available
  3972. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3973. : 'bg-status-ok/20 text-status-ok'
  3974. }`}
  3975. title={
  3976. firmwareInfo.update_available
  3977. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3978. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3979. }
  3980. >
  3981. {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)]" />}
  3982. {firmwareInfo.current_version}
  3983. </button>
  3984. ) : status?.firmware_version ? (
  3985. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3986. {status.firmware_version}
  3987. </span>
  3988. ) : null}
  3989. {/* Enclosure Door Badge — models with an actual door sensor.
  3990. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3991. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3992. <span
  3993. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3994. status.door_open
  3995. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3996. : 'bg-status-ok/20 text-status-ok'
  3997. }`}
  3998. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3999. >
  4000. {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)]" />}
  4001. </span>
  4002. )}
  4003. </div>
  4004. </div>
  4005. )}
  4006. </div>
  4007. {/* Delete Confirmation */}
  4008. {showDeleteConfirm && (
  4009. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  4010. <Card className="w-full max-w-md mx-4">
  4011. <CardContent>
  4012. <div className="flex items-start gap-3 mb-4">
  4013. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  4014. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  4015. </div>
  4016. <div>
  4017. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  4018. <p className="text-sm text-bambu-gray mt-1">
  4019. {t('printers.confirm.deleteMessage', { name: printer.name })}
  4020. </p>
  4021. </div>
  4022. </div>
  4023. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  4024. <label className="flex items-start gap-3 cursor-pointer">
  4025. <input
  4026. type="checkbox"
  4027. checked={deleteArchives}
  4028. onChange={(e) => setDeleteArchives(e.target.checked)}
  4029. 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"
  4030. />
  4031. <div>
  4032. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  4033. <p className="text-xs text-bambu-gray mt-0.5">
  4034. {deleteArchives
  4035. ? t('printers.confirm.deleteArchivesNote')
  4036. : t('printers.confirm.keepArchivesNote')}
  4037. </p>
  4038. </div>
  4039. </label>
  4040. </div>
  4041. <div className="flex justify-end gap-2">
  4042. <Button
  4043. variant="secondary"
  4044. onClick={() => {
  4045. setShowDeleteConfirm(false);
  4046. setDeleteArchives(true);
  4047. }}
  4048. >
  4049. {t('common.cancel')}
  4050. </Button>
  4051. <Button
  4052. variant="danger"
  4053. onClick={() => {
  4054. deleteMutation.mutate({ deleteArchives });
  4055. setShowDeleteConfirm(false);
  4056. setDeleteArchives(true);
  4057. }}
  4058. >
  4059. Delete
  4060. </Button>
  4061. </div>
  4062. </CardContent>
  4063. </Card>
  4064. </div>
  4065. )}
  4066. {/* Status — see the equivalent defensive `=== false` check on the
  4067. header pill above for why this is not `!printer.is_active`. */}
  4068. {printer.is_active === false ? (
  4069. // Maintenance mode (#1476) — replaces the cover/progress container
  4070. // so the card keeps the same height. Renders for both compact and
  4071. // expanded view modes so the printer stays visible but plainly
  4072. // out-of-service.
  4073. <>
  4074. {viewMode === 'compact' ? (
  4075. <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">
  4076. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4077. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4078. {t('printers.maintenance.pillLabel')}
  4079. </span>
  4080. </div>
  4081. ) : (
  4082. <>
  4083. <div className="flex items-center gap-2 mb-2">
  4084. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4085. {t('printers.status.title', 'Status')}
  4086. </span>
  4087. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4088. </div>
  4089. <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">
  4090. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4091. <div className="flex-1 min-w-0">
  4092. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4093. {t('printers.maintenance.title')}
  4094. </p>
  4095. <p className="text-xs text-bambu-gray mt-0.5">
  4096. {t('printers.maintenance.subtitle')}
  4097. </p>
  4098. </div>
  4099. <Button
  4100. variant="secondary"
  4101. size="sm"
  4102. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4103. onClick={() => maintenanceMutation.mutate(true)}
  4104. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4105. >
  4106. {t('printers.maintenance.exitButton')}
  4107. </Button>
  4108. </div>
  4109. </>
  4110. )}
  4111. </>
  4112. ) : status?.connected && (
  4113. <>
  4114. {/* Compact: Simple status bar */}
  4115. {viewMode === 'compact' ? (
  4116. (() => {
  4117. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4118. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4119. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4120. ? Math.max(0, Math.min(100, status.progress || 0))
  4121. : showClearPlateButton
  4122. ? 100
  4123. : hasProblem
  4124. ? 100
  4125. : 0;
  4126. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4127. const compactProgressClass = hasProblem
  4128. ? 'bg-status-error'
  4129. : status.state === 'PAUSE'
  4130. ? 'bg-status-warning'
  4131. : 'bg-bambu-green';
  4132. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4133. const hasCompactLayers =
  4134. isActiveCompactPrint &&
  4135. status.layer_num != null &&
  4136. status.total_layers != null &&
  4137. status.total_layers > 0;
  4138. return (
  4139. <>
  4140. <div className="relative mt-2 flex items-center gap-2">
  4141. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4142. <div
  4143. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4144. style={{ width: `${compactProgress}%` }}
  4145. />
  4146. </div>
  4147. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4148. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4149. </span>
  4150. </div>
  4151. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4152. enough to answer "which printer finishes first", which is what a
  4153. wall-mounted fleet view is for. One line of the metrics the
  4154. expanded card already renders, using the same formatters and the
  4155. same ETA styling so S and M read alike. The row keeps its height
  4156. when idle so cards don't shift as prints start and stop. */}
  4157. <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">
  4158. {hasCompactEta && (
  4159. <>
  4160. <span className="flex shrink-0 items-center gap-1">
  4161. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4162. {formatDuration(status.remaining_time! * 60)}
  4163. </span>
  4164. <span
  4165. className="shrink-0 font-medium text-bambu-green"
  4166. title={t('printers.estimatedCompletion')}
  4167. >
  4168. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4169. </span>
  4170. </>
  4171. )}
  4172. {hasCompactLayers && (
  4173. <span className="flex min-w-0 items-center gap-1 truncate">
  4174. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4175. {status.layer_num}/{status.total_layers}
  4176. </span>
  4177. )}
  4178. </div>
  4179. </>
  4180. );
  4181. })()
  4182. ) : (
  4183. /* Expanded: Full status section */
  4184. <>
  4185. <div className="flex items-center gap-2 mb-2">
  4186. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4187. {t('printers.status.title', 'Status')}
  4188. </span>
  4189. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4190. </div>
  4191. {/* Current Print or Idle Placeholder */}
  4192. {(() => {
  4193. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4194. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4195. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4196. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4197. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4198. // A running print always has at least one object, so a count of
  4199. // zero means "not loaded", not "nothing to skip" — after a
  4200. // restart mid-print the list is empty until something rebuilds
  4201. // it. Treating that as nothing-to-skip disabled the only
  4202. // control that opens the modal, and the modal's own fetch is
  4203. // what rebuilds the list, so the print could never get it back.
  4204. // Exactly one object is the real nothing-to-skip case.
  4205. const objectCount = status.printable_objects_count ?? 0;
  4206. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4207. return (
  4208. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4209. <button
  4210. onClick={() => setShowSkipObjectsModal(true)}
  4211. disabled={!canSkipObjects}
  4212. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4213. canSkipObjects
  4214. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4215. : 'text-bambu-gray/30 cursor-not-allowed'
  4216. }`}
  4217. title={
  4218. !hasPermission('printers:control')
  4219. ? t('printers.permission.noControl')
  4220. : !isActivePrint
  4221. ? t('printers.skipObjects.onlyWhilePrinting')
  4222. : objectCount === 1
  4223. ? t('printers.skipObjects.requiresMultiple')
  4224. : t('printers.skipObjects.tooltip')
  4225. }
  4226. >
  4227. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4228. {objectsData && objectsData.skipped_count > 0 && (
  4229. <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">
  4230. {objectsData.skipped_count}
  4231. </span>
  4232. )}
  4233. </button>
  4234. <div className="flex items-stretch gap-2">
  4235. <CoverImage
  4236. url={coverUrl}
  4237. printName={printName || undefined}
  4238. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4239. />
  4240. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4241. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4242. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4243. {plateStatusPill}
  4244. </div>
  4245. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4246. {printName || t('printers.noActiveJob', 'No active job')}
  4247. </p>
  4248. <div className="flex h-3 items-center gap-2 text-sm">
  4249. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4250. <div
  4251. 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`}
  4252. style={{ width: `${progress}%` }}
  4253. />
  4254. </div>
  4255. <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>
  4256. </div>
  4257. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4258. {isActivePrint ? (
  4259. <>
  4260. {status.remaining_time != null && status.remaining_time > 0 && (
  4261. <>
  4262. <span className="flex items-center gap-1">
  4263. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4264. {formatDuration(status.remaining_time * 60)}
  4265. </span>
  4266. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4267. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4268. </span>
  4269. </>
  4270. )}
  4271. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4272. <span className="flex items-center gap-1">
  4273. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4274. {status.layer_num}/{status.total_layers}
  4275. </span>
  4276. )}
  4277. {currentPrintUser && (
  4278. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4279. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4280. {currentPrintUser}
  4281. </span>
  4282. )}
  4283. </>
  4284. ) : lastPrint ? (
  4285. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4286. Last: {lastPrint.print_name || lastPrint.filename}
  4287. {lastPrint.completed_at && (
  4288. <span className="ml-1 text-bambu-gray/60">
  4289. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4290. </span>
  4291. )}
  4292. </p>
  4293. ) : (
  4294. <span>{t('printers.readyToPrint')}</span>
  4295. )}
  4296. </div>
  4297. </div>
  4298. </div>
  4299. <PrinterQueueWidget
  4300. printerId={printer.id}
  4301. printerModel={printer.model}
  4302. loadedFilamentTypes={loadedFilamentTypes}
  4303. loadedFilaments={loadedFilaments}
  4304. loadedVariants={loadedVariants}
  4305. variant="panelExtension"
  4306. />
  4307. </div>
  4308. );
  4309. })()}
  4310. </>
  4311. )}
  4312. {/* Temperatures */}
  4313. {status.temperatures && viewMode === 'expanded' && (() => {
  4314. // Use actual heater states from MQTT stream
  4315. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4316. const bedHeating = status.temperatures.bed_heating || false;
  4317. const chamberHeating = status.temperatures.chamber_heating || false;
  4318. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4319. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4320. const kinds: HeaterSensorKind[] = ['nozzle'];
  4321. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4322. kinds.push('bed');
  4323. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4324. return kinds;
  4325. })();
  4326. // active_extruder: 0=right, 1=left
  4327. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4328. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4329. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4330. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4331. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4332. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4333. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4334. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4335. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4336. 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 ${
  4337. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4338. }`;
  4339. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4340. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4341. // the widget there is at best dead UI and at worst suggests a
  4342. // control that does nothing. Mirrors the enclosure-door badge
  4343. // gate above.
  4344. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4345. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4346. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4347. // show it only when the printer actually reports it (airduct part id 3,
  4348. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4349. // have a built-in chamber fan that's always present, so they keep the
  4350. // existing model-list gate and the "Chamber Fan" label.
  4351. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4352. const chamberFanLabel = isExhaustModel
  4353. ? t('printers.fans.exhaust')
  4354. : t('printers.fans.chamber');
  4355. // Composed rather than either/or so both lists stay live for
  4356. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4357. // where that fan is an add-on kit — actually report it. Written
  4358. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4359. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4360. // which reads as if removing them were safe.
  4361. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4362. const fanItems: {
  4363. key: string;
  4364. label: string;
  4365. value: number;
  4366. Icon: typeof Fan;
  4367. activeClass: string;
  4368. }[] = [
  4369. {
  4370. key: 'part',
  4371. label: t('printers.fans.partCooling'),
  4372. value: status.cooling_fan_speed ?? 0,
  4373. Icon: Fan,
  4374. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4375. },
  4376. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4377. // Only reported (non-null) when the firmware lists airduct part
  4378. // id 10, i.e. when the fan is physically installed. Placed
  4379. // before the right-hand auxiliary fan so the two aux badges read
  4380. // left-to-right in the same order as the physical hardware.
  4381. ...(status.left_aux_fan_speed != null
  4382. ? [
  4383. {
  4384. key: 'aux2',
  4385. label: t('printers.fans.leftAuxiliary'),
  4386. value: status.left_aux_fan_speed,
  4387. Icon: Wind,
  4388. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4389. },
  4390. ]
  4391. : []),
  4392. {
  4393. key: 'aux',
  4394. label: t('printers.fans.auxiliary'),
  4395. value: status.big_fan1_speed ?? 0,
  4396. Icon: Wind,
  4397. activeClass: 'text-blue-600 dark:text-blue-400',
  4398. },
  4399. ...(showChamberFan
  4400. ? [
  4401. {
  4402. key: 'chamber',
  4403. label: chamberFanLabel,
  4404. value: status.big_fan2_speed ?? 0,
  4405. Icon: AirVent,
  4406. activeClass: 'text-green-600 dark:text-green-400',
  4407. },
  4408. ]
  4409. : []),
  4410. ];
  4411. return (
  4412. <>
  4413. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4414. {/* Nozzle temp - combined for dual nozzle */}
  4415. <div
  4416. className={statusControlClass}
  4417. title={statusControlTitle}
  4418. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4419. >
  4420. <button
  4421. type="button"
  4422. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4423. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4424. onClick={(e) => {
  4425. e.stopPropagation();
  4426. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4427. }}
  4428. >
  4429. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4430. </button>
  4431. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4432. {status.temperatures.nozzle_2 !== undefined ? (
  4433. <>
  4434. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4435. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4436. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4437. </p>
  4438. </>
  4439. ) : singleNozzleSlot ? (
  4440. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4441. <div className="cursor-default">
  4442. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4443. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4444. {Math.round(status.temperatures.nozzle || 0)}°C
  4445. </p>
  4446. </div>
  4447. </NozzleSlotHoverCard>
  4448. ) : (
  4449. <>
  4450. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4451. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4452. {Math.round(status.temperatures.nozzle || 0)}°C
  4453. </p>
  4454. </>
  4455. )}
  4456. {statusControlMenu === 'nozzle-temp' && (
  4457. isDualNozzle ? (
  4458. <IndicatorControlPopover
  4459. title="Set Nozzle Temperatures"
  4460. widthClass="w-[300px]"
  4461. popoverWidth={300}
  4462. popoverHeight={260}
  4463. isPending={nozzleTemperatureMutation.isPending}
  4464. onClose={() => setStatusControlMenu(null)}
  4465. >
  4466. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4467. <NozzleTemperatureControlBox
  4468. label="Left Temp"
  4469. current={status.temperatures.nozzle}
  4470. target={status.temperatures.nozzle_target}
  4471. isActive={activeNozzle === 'L'}
  4472. isPending={nozzleTemperatureMutation.isPending}
  4473. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4474. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4475. />
  4476. <NozzleTemperatureControlBox
  4477. label="Right Temp"
  4478. current={status.temperatures.nozzle_2}
  4479. target={status.temperatures.nozzle_2_target}
  4480. isActive={activeNozzle === 'R'}
  4481. isPending={nozzleTemperatureMutation.isPending}
  4482. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4483. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4484. />
  4485. </div>
  4486. </IndicatorControlPopover>
  4487. ) : (
  4488. <IndicatorControlPopover
  4489. title="Set Nozzle Temperature"
  4490. unit="°C"
  4491. customMin={0}
  4492. customMax={320}
  4493. isPending={nozzleTemperatureMutation.isPending}
  4494. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4495. onClose={() => setStatusControlMenu(null)}
  4496. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4497. />
  4498. )
  4499. )}
  4500. </div>
  4501. <div
  4502. className={statusControlClass}
  4503. title={statusControlTitle}
  4504. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4505. >
  4506. <button
  4507. type="button"
  4508. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4509. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4510. onClick={(e) => {
  4511. e.stopPropagation();
  4512. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4513. }}
  4514. >
  4515. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4516. </button>
  4517. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4518. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4519. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4520. {Math.round(status.temperatures.bed || 0)}°C
  4521. </p>
  4522. {statusControlMenu === 'bed-temp' && (
  4523. <IndicatorControlPopover
  4524. title="Set Bed Temperature"
  4525. unit="°C"
  4526. customMin={0}
  4527. customMax={140}
  4528. isPending={bedTemperatureMutation.isPending}
  4529. options={buildPresetOptions(bedTempPresets, 'C')}
  4530. onClose={() => setStatusControlMenu(null)}
  4531. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4532. />
  4533. )}
  4534. </div>
  4535. {status.temperatures.chamber !== undefined && (() => {
  4536. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4537. // but can't act on M141, so we keep the card read-only there.
  4538. const hasChamberHeater = status.supports_chamber_heater === true;
  4539. return (
  4540. <div
  4541. className={hasChamberHeater
  4542. ? statusControlClass
  4543. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4544. title={hasChamberHeater ? statusControlTitle : undefined}
  4545. onClick={hasChamberHeater
  4546. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4547. : undefined}
  4548. >
  4549. <button
  4550. type="button"
  4551. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4552. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4553. onClick={(e) => {
  4554. e.stopPropagation();
  4555. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4556. }}
  4557. >
  4558. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4559. </button>
  4560. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4561. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4562. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4563. {Math.round(status.temperatures.chamber || 0)}°C
  4564. </p>
  4565. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4566. <IndicatorControlPopover
  4567. title="Set Chamber Temperature"
  4568. unit="°C"
  4569. customMin={0}
  4570. customMax={MAX_CHAMBER_TEMP_C}
  4571. isPending={chamberTemperatureMutation.isPending}
  4572. options={buildPresetOptions(chamberTempPresets, 'C')}
  4573. onClose={() => setStatusControlMenu(null)}
  4574. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4575. />
  4576. )}
  4577. </div>
  4578. );
  4579. })()}
  4580. {/* Active nozzle indicator for dual-nozzle printers */}
  4581. {isDualNozzle && (
  4582. <DualNozzleHoverCard
  4583. leftSlot={leftNozzleSlot}
  4584. rightSlot={rightNozzleSlot}
  4585. activeNozzle={activeNozzle}
  4586. filamentInfo={filamentInfo}
  4587. >
  4588. <div
  4589. 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 ${
  4590. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4591. }`}
  4592. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4593. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4594. >
  4595. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4596. <div className="flex items-center gap-2">
  4597. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4598. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4599. </span>
  4600. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4601. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4602. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4603. </span>
  4604. </div>
  4605. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4606. {statusControlMenu === 'nozzle-select' && (
  4607. <IndicatorControlPopover
  4608. title="Set Nozzle Selection"
  4609. widthClass="w-[300px]"
  4610. popoverWidth={300}
  4611. popoverHeight={140}
  4612. isPending={selectExtruderMutation.isPending}
  4613. options={[
  4614. { label: 'Left', value: 1 },
  4615. { label: 'Right', value: 0 },
  4616. ]}
  4617. onClose={() => setStatusControlMenu(null)}
  4618. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4619. />
  4620. )}
  4621. </div>
  4622. </DualNozzleHoverCard>
  4623. )}
  4624. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4625. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4626. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4627. )}
  4628. </div>
  4629. <div className="mt-2 flex items-center gap-1.5">
  4630. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4631. const active = value > 0;
  4632. return (
  4633. <div
  4634. key={key}
  4635. 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 ${
  4636. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4637. }`}
  4638. title={canUseStatusControls ? label : statusControlTitle}
  4639. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4640. >
  4641. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4642. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4643. {value}%
  4644. </span>
  4645. {statusControlMenu === `fan-${key}` && (
  4646. <IndicatorControlPopover
  4647. title={`Set ${label} Speed`}
  4648. unit="%"
  4649. customMin={0}
  4650. customMax={100}
  4651. isPending={fanSpeedMutation.isPending}
  4652. options={buildPresetOptions(fanSpeedPresets, '%')}
  4653. onClose={() => setStatusControlMenu(null)}
  4654. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4655. />
  4656. )}
  4657. </div>
  4658. );
  4659. })}
  4660. </div>
  4661. </>
  4662. );
  4663. })()}
  4664. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4665. {/* Controls */}
  4666. {viewMode === 'expanded' && (() => {
  4667. // Determine print state for control buttons
  4668. const isRunning = status.state === 'RUNNING';
  4669. const isPaused = status.state === 'PAUSE';
  4670. const isPrinting = isRunning || isPaused;
  4671. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4672. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4673. 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';
  4674. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4675. return (
  4676. <div className="mt-3">
  4677. {/* Section Header */}
  4678. <div className="flex items-center gap-2 mb-2">
  4679. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4680. {t('printers.controls')}
  4681. </span>
  4682. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4683. </div>
  4684. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4685. {/* Left: Secondary controls */}
  4686. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4687. <button
  4688. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4689. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4690. className={`${iconControlClass} ${
  4691. status.chamber_light
  4692. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4693. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4694. }`}
  4695. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4696. >
  4697. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4698. </button>
  4699. {/* Airduct Mode (P2S / X2D / H2*) */}
  4700. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4701. const isHeating = status.airduct_mode === 1;
  4702. const Icon = isHeating ? Flame : Snowflake;
  4703. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4704. 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';
  4705. return (
  4706. <div className="relative">
  4707. <button
  4708. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4709. disabled={!hasPermission('printers:control')}
  4710. className={`${iconControlClass} ${bg}`}
  4711. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4712. >
  4713. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4714. </button>
  4715. {showAirductMenu === printer.id && (
  4716. <>
  4717. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4718. <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]">
  4719. {([
  4720. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4721. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4722. ] as const).map(({ mode, label, modeId }) => (
  4723. <button
  4724. key={mode}
  4725. onClick={() => {
  4726. airductMutation.mutate(mode);
  4727. setShowAirductMenu(null);
  4728. }}
  4729. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4730. status.airduct_mode === modeId
  4731. ? 'text-bambu-green bg-bambu-green/10'
  4732. : 'text-white hover:bg-bambu-dark-tertiary'
  4733. }`}
  4734. >
  4735. {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)]" />}
  4736. {label}
  4737. </button>
  4738. ))}
  4739. </div>
  4740. </>
  4741. )}
  4742. </div>
  4743. );
  4744. })()}
  4745. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4746. {(() => {
  4747. const canControl = hasPermission('printers:control');
  4748. const disabled = isPrinting || !canControl;
  4749. 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';
  4750. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4751. // nozzle-bed gap that means the same thing on every printer, so the
  4752. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4753. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4754. // plate toward the nozzle and closes it.
  4755. const zMovesToolhead = isBedSlinger(printer.model);
  4756. const requestZJog = (arrow: 'up' | 'down') => {
  4757. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4758. // No not-homed gate here, and no endstop bypass to gate either:
  4759. // since #2579 the jog is a bare move that never touches M211. That
  4760. // does not make it clamped — the firmware ignores soft endstops on
  4761. // MQTT G-code entirely, which is what the banner above warns about.
  4762. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4763. };
  4764. const requestXyJog = (x: number, y: number) => {
  4765. xyJogMutation.mutate({ x, y });
  4766. };
  4767. const requestExtruderJog = (distance: number) => {
  4768. extruderJogMutation.mutate(distance);
  4769. };
  4770. return (
  4771. <div className="relative">
  4772. <button
  4773. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4774. disabled={disabled}
  4775. className={`${iconControlClass} ${
  4776. disabled
  4777. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4778. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4779. }`}
  4780. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4781. >
  4782. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4783. </button>
  4784. {showBedJogMenu === printer.id && (
  4785. <>
  4786. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4787. <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">
  4788. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4789. {t('printers.bedJog.title')}
  4790. </div>
  4791. <div className="h-px bg-bambu-dark-tertiary" />
  4792. {/* #2579: Bambu firmware does not enforce soft endstops on
  4793. G-code sent over MQTT, so manual moves can drive past the
  4794. travel limits and cause a collision. Not fixable from our
  4795. side — warn prominently. */}
  4796. <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">
  4797. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4798. <span>{t('printers.bedJog.limitWarning')}</span>
  4799. </div>
  4800. <div className="h-px bg-bambu-dark-tertiary" />
  4801. <div className="flex justify-center px-3 py-2.5">
  4802. <div className="flex items-center justify-center gap-3">
  4803. <div className="grid grid-cols-3 gap-1">
  4804. <div />
  4805. <button
  4806. onClick={() => requestXyJog(0, bedJogStep)}
  4807. disabled={xyJogMutation.isPending}
  4808. className={jogButtonClass}
  4809. aria-label="Move Y forward"
  4810. >
  4811. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4812. </button>
  4813. <div />
  4814. <button
  4815. onClick={() => requestXyJog(-bedJogStep, 0)}
  4816. disabled={xyJogMutation.isPending}
  4817. className={jogButtonClass}
  4818. aria-label="Move X left"
  4819. >
  4820. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4821. </button>
  4822. <button
  4823. onClick={() => {
  4824. setShowBedJogMenu(null);
  4825. homeAxesMutation.mutate('all');
  4826. }}
  4827. disabled={homeAxesMutation.isPending}
  4828. className={jogButtonClass}
  4829. aria-label={t('printers.bedJog.homeZ')}
  4830. >
  4831. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4832. </button>
  4833. <button
  4834. onClick={() => requestXyJog(bedJogStep, 0)}
  4835. disabled={xyJogMutation.isPending}
  4836. className={jogButtonClass}
  4837. aria-label="Move X right"
  4838. >
  4839. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4840. </button>
  4841. <div />
  4842. <button
  4843. onClick={() => requestXyJog(0, -bedJogStep)}
  4844. disabled={xyJogMutation.isPending}
  4845. className={jogButtonClass}
  4846. aria-label="Move Y back"
  4847. >
  4848. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4849. </button>
  4850. <div />
  4851. </div>
  4852. <div className="flex flex-col items-center gap-1">
  4853. <button
  4854. onClick={() => requestZJog('up')}
  4855. disabled={bedJogMutation.isPending}
  4856. className={jogButtonClass}
  4857. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4858. >
  4859. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4860. </button>
  4861. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4862. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4863. </div>
  4864. <button
  4865. onClick={() => requestZJog('down')}
  4866. disabled={bedJogMutation.isPending}
  4867. className={jogButtonClass}
  4868. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4869. >
  4870. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4871. </button>
  4872. </div>
  4873. <div className="flex flex-col items-center gap-1">
  4874. <button
  4875. onClick={() => requestExtruderJog(-bedJogStep)}
  4876. disabled={extruderJogMutation.isPending}
  4877. className={jogButtonClass}
  4878. aria-label="Retract filament"
  4879. >
  4880. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4881. </button>
  4882. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4883. <span className="text-sm font-semibold leading-none">E</span>
  4884. </div>
  4885. <button
  4886. onClick={() => requestExtruderJog(bedJogStep)}
  4887. disabled={extruderJogMutation.isPending}
  4888. className={jogButtonClass}
  4889. aria-label="Extrude filament"
  4890. >
  4891. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4892. </button>
  4893. </div>
  4894. </div>
  4895. </div>
  4896. <div className="h-px bg-bambu-dark-tertiary" />
  4897. <div className="px-3 pt-2.5 pb-3">
  4898. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4899. {t('printers.bedJog.step')}
  4900. </div>
  4901. <div className="flex gap-1">
  4902. {[1, 10, 50].map((step) => (
  4903. <button
  4904. key={step}
  4905. onClick={() => setBedJogStep(step)}
  4906. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4907. bedJogStep === step
  4908. ? 'bg-bambu-green/20 text-bambu-green'
  4909. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4910. }`}
  4911. >
  4912. {step}
  4913. </button>
  4914. ))}
  4915. </div>
  4916. </div>
  4917. </div>
  4918. </>
  4919. )}
  4920. </div>
  4921. );
  4922. })()}
  4923. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4924. <button
  4925. onClick={handleTogglePlateDetection}
  4926. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4927. className={`${iconControlClass} rounded-r-none ${
  4928. printer.plate_detection_enabled
  4929. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4930. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4931. }`}
  4932. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4933. >
  4934. {plateDetectionMutation.isPending ? (
  4935. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4936. ) : (
  4937. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4938. )}
  4939. </button>
  4940. <button
  4941. onClick={handleOpenPlateManagement}
  4942. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4943. 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 ${
  4944. printer.plate_detection_enabled
  4945. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4946. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4947. }`}
  4948. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4949. >
  4950. {isCheckingPlate ? (
  4951. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4952. ) : (
  4953. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4954. )}
  4955. </button>
  4956. </div>
  4957. {/* Print Speed */}
  4958. {(() => (
  4959. <div className="relative">
  4960. <button
  4961. data-testid="speed-control"
  4962. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4963. disabled={!isPrinting || !hasPermission('printers:control')}
  4964. className={`${iconControlClass} ${
  4965. isPrinting
  4966. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4967. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4968. }`}
  4969. title={isPrinting ? t('printers.speed.title') : undefined}
  4970. >
  4971. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4972. </button>
  4973. {showSpeedMenu === printer.id && (
  4974. <>
  4975. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4976. <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]">
  4977. {([
  4978. { mode: 1, label: t('printers.speed.silent') },
  4979. { mode: 2, label: t('printers.speed.standard') },
  4980. { mode: 3, label: t('printers.speed.sport') },
  4981. { mode: 4, label: t('printers.speed.ludicrous') },
  4982. ] as const).map(({ mode, label }) => (
  4983. <button
  4984. key={mode}
  4985. onClick={() => {
  4986. printSpeedMutation.mutate(mode);
  4987. setShowSpeedMenu(null);
  4988. }}
  4989. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4990. status.speed_level === mode
  4991. ? 'text-bambu-green bg-bambu-green/10'
  4992. : 'text-white hover:bg-bambu-dark-tertiary'
  4993. }`}
  4994. >
  4995. {label}
  4996. </button>
  4997. ))}
  4998. </div>
  4999. </>
  5000. )}
  5001. </div>
  5002. ))()}
  5003. </div>
  5004. {/* Right: Print Control Buttons */}
  5005. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  5006. {/* Pause/Resume button */}
  5007. {(() => {
  5008. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  5009. return (
  5010. <button
  5011. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  5012. disabled={pauseUnavailable}
  5013. className={`
  5014. ${printControlClass}
  5015. ${pauseUnavailable
  5016. ? unavailablePrintActionClass
  5017. : isPaused
  5018. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5019. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  5020. }
  5021. `}
  5022. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  5023. >
  5024. {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)]" />}
  5025. {isPaused ? t('printers.resume') : t('printers.pause')}
  5026. </button>
  5027. );
  5028. })()}
  5029. {/* Stop button */}
  5030. {(() => {
  5031. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  5032. return (
  5033. <button
  5034. onClick={() => setShowStopConfirm(true)}
  5035. disabled={stopUnavailable}
  5036. className={`
  5037. ${printControlClass}
  5038. ${stopUnavailable
  5039. ? unavailablePrintActionClass
  5040. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  5041. }
  5042. `}
  5043. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  5044. >
  5045. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5046. {t('printers.stop')}
  5047. </button>
  5048. );
  5049. })()}
  5050. </div>
  5051. </div>
  5052. </div>
  5053. );
  5054. })()}
  5055. {/* AMS Units - 2-Column Grid Layout */}
  5056. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  5057. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  5058. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  5059. const htAms = amsData.filter(ams => ams.tray.length === 1);
  5060. // The external spool can only be hidden while some AMS remains to
  5061. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  5062. // filament section, so the toggle is not offered there and a stored
  5063. // preference from a printer that later lost its AMS cannot blank the
  5064. // row either — both read through canHideExternalSpool.
  5065. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  5066. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5067. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5068. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5069. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5070. // floating point, and that lands verbatim in the DOM.
  5071. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5072. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5073. // already grow to fill the row, so the 3.5rem is a floor they sit
  5074. // well above in practice -- raising it just costs a unit its place
  5075. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5076. // its line, and flex-grow stretches its single slot across the whole
  5077. // card. The AMS-HT's own width does scale, below, because its
  5078. // readings sit beside the slot rather than under it.
  5079. const slotMinWidth = '3.5rem';
  5080. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5081. // The AMS-HT holds a single spool, and its slot is the only thing
  5082. // on that row able to grow -- so it swallowed every spare pixel and
  5083. // shoved the temperature and humidity hard against the card's edge.
  5084. // Capping it at roughly two ordinary slots keeps the readings clear
  5085. // of the edge; the cap scales because the text inside the slot does.
  5086. const htSlotStyle: React.CSSProperties = {
  5087. minWidth: slotMinWidth,
  5088. maxWidth: scaledRem(7.25),
  5089. };
  5090. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5091. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5092. });
  5093. // #1762 (comment 2): while a print is running/paused, overlay a small
  5094. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5095. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5096. // staged to a printer with mismatched filament: the wrong-slot pill
  5097. // is visible the instant printing starts.
  5098. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5099. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5100. ? status.ams_mapping
  5101. : [];
  5102. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5103. const boundedSlotCount = Math.max(1, slotCount);
  5104. const gapCount = Math.max(0, boundedSlotCount - 1);
  5105. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5106. return {
  5107. flex: `1 1 ${minWidth}`,
  5108. minWidth,
  5109. };
  5110. };
  5111. return (
  5112. <div className="mt-3">
  5113. {/* Section Header */}
  5114. <div className="flex items-center gap-2 mb-2">
  5115. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5116. {t('printers.filaments')}
  5117. </span>
  5118. <AmsBackupBadge
  5119. state={status.ams_filament_backup}
  5120. onClick={() => setAmsBackupModalOpen(true)}
  5121. />
  5122. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5123. {/* Offered only when an AMS is present: on a printer that
  5124. feeds from the external spool alone, hiding it would
  5125. empty the row entirely (#1782). */}
  5126. {canHideExternalSpool && (
  5127. <>
  5128. <ExternalSpoolToggle
  5129. hidden={externalSpoolHidden}
  5130. onClick={toggleExternalSpool}
  5131. />
  5132. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5133. </>
  5134. )}
  5135. </div>
  5136. {/* AMS Content */}
  5137. <div className="flex flex-wrap gap-2">
  5138. {/* Regular AMS units */}
  5139. {regularAms.map((ams) => {
  5140. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5141. return (
  5142. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5143. {/* Header: Label + Stats (no icon) */}
  5144. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5145. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5146. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5147. <AmsNameHoverCard
  5148. ams={ams}
  5149. printerId={printer.id}
  5150. label={getAmsLabel(ams.id, ams.tray.length)}
  5151. amsLabels={amsLabels}
  5152. canEdit={hasPermission('printers:update')}
  5153. onSaved={refetchAmsLabels}
  5154. >
  5155. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5156. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5157. </span>
  5158. </AmsNameHoverCard>
  5159. {sideBadge?.kind === 'inlet' ? (
  5160. <InletBadge
  5161. inlet={sideBadge.inlet}
  5162. title={t('printers.amsSwitchInletTooltip', {
  5163. inlet: sideBadge.inlet,
  5164. side: FTS_INLET_SIDE[sideBadge.inlet],
  5165. })}
  5166. />
  5167. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5168. <NozzleBadge side={sideBadge.side} />
  5169. ) : null}
  5170. </div>
  5171. {(ams.humidity != null || ams.temp != null) && (
  5172. <div className="flex shrink-0 items-center gap-1.5">
  5173. {ams.humidity != null && (
  5174. <HumidityIndicator
  5175. humidity={ams.humidity}
  5176. goodThreshold={amsThresholds?.humidityGood}
  5177. fairThreshold={amsThresholds?.humidityFair}
  5178. onClick={() => setAmsHistoryModal({
  5179. amsId: ams.id,
  5180. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5181. mode: 'humidity',
  5182. })}
  5183. compact
  5184. />
  5185. )}
  5186. {ams.temp != null && (
  5187. <div className="mr-1">
  5188. <TemperatureIndicator
  5189. temp={ams.temp}
  5190. goodThreshold={amsThresholds?.tempGood}
  5191. fairThreshold={amsThresholds?.tempFair}
  5192. onClick={() => setAmsHistoryModal({
  5193. amsId: ams.id,
  5194. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5195. mode: 'temperature',
  5196. })}
  5197. compact
  5198. />
  5199. </div>
  5200. )}
  5201. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5202. Screen-only models (P1 series) keep the control but can't
  5203. be commanded: it stays disabled and says why (#2533). */}
  5204. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5205. <button
  5206. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5207. onClick={(e) => {
  5208. if (ams.dry_time > 0) {
  5209. stopDryingMutation.mutate(ams.id);
  5210. } else if (dryingPopoverAmsId === ams.id) {
  5211. setDryingPopoverAmsId(null);
  5212. } else {
  5213. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5214. }
  5215. }}
  5216. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5217. ams.dry_time > 0
  5218. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5219. : status.drying_screen_only || ams.dry_sf_reason?.length
  5220. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5221. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5222. }`}
  5223. 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')}
  5224. >
  5225. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5226. </button>
  5227. )}
  5228. </div>
  5229. )}
  5230. </div>
  5231. {/* Drying status bar. A dry_time whose countdown is not
  5232. ticking, with no active drying phase (a parked command —
  5233. e.g. an H2D mid-print already powering other drying — or
  5234. a paused cycle), is shown as "not running", not as an
  5235. active cycle: the amber badge claiming a running dry
  5236. that the AMS never began is how this was found. */}
  5237. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5238. <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')}>
  5239. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5240. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5241. {ams.dry_filament && (
  5242. <span className="text-slate-500/90 dark:text-slate-400/80">
  5243. {ams.dry_target_temp != null
  5244. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5245. : ams.dry_filament}
  5246. </span>
  5247. )}
  5248. {!status.drying_screen_only && (
  5249. <button
  5250. onClick={() => stopDryingMutation.mutate(ams.id)}
  5251. disabled={stopDryingMutation.isPending}
  5252. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5253. title={t('printers.drying.stop')}
  5254. >
  5255. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5256. </button>
  5257. )}
  5258. </div>
  5259. )}
  5260. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5261. <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)]">
  5262. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5263. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5264. {/* The temperature is only ever known from the target we
  5265. cached when sending the command — the filament can also
  5266. be read off a uniformly loaded unit, so it can outlive
  5267. the temperature (#2759). */}
  5268. {ams.dry_filament && (
  5269. <span className="text-amber-700/80 dark:text-amber-300/70">
  5270. {ams.dry_target_temp != null
  5271. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5272. : ams.dry_filament}
  5273. </span>
  5274. )}
  5275. <span className="text-amber-700/80 dark:text-amber-300/70">
  5276. {t('printers.drying.timeRemaining', {
  5277. time: ams.dry_time >= 60
  5278. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5279. : `${ams.dry_time}m`
  5280. })}
  5281. </span>
  5282. {/* A cycle on a screen-only model was started at the printer
  5283. and can only be stopped there (#2533). */}
  5284. {!status.drying_screen_only && (
  5285. <button
  5286. onClick={() => stopDryingMutation.mutate(ams.id)}
  5287. disabled={stopDryingMutation.isPending}
  5288. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5289. title={t('printers.drying.stop')}
  5290. >
  5291. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5292. </button>
  5293. )}
  5294. </div>
  5295. )}
  5296. {/* Slots grid: 4 columns - always render 4 slots */}
  5297. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5298. {[0, 1, 2, 3].map((slotIdx) => {
  5299. // Find tray data for this slot (may be undefined if data incomplete)
  5300. // Use array index if available, as tray.id may not always be set
  5301. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5302. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5303. const isEmpty = !tray?.tray_type;
  5304. const emptyKind = getEmptySlotKind(tray);
  5305. // Check if this is the currently loaded tray
  5306. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5307. const globalTrayId = ams.id * 4 + slotIdx;
  5308. const isActive = effectiveTrayNow === globalTrayId;
  5309. // Runout guidance (#2587): the slot the paused print now
  5310. // expects filament in, and the slot that ran out.
  5311. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5312. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5313. // Get cloud preset info if available
  5314. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5315. // Get saved slot preset mapping (for user-configured slots)
  5316. const slotPreset = slotPresets?.[globalTrayId];
  5317. // Only trusted while it still describes what the printer reports in the
  5318. // slot: the row survives a spool swap, and the display chain below puts
  5319. // it ahead of the live filament id (see slotPresetDescribesTray).
  5320. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5321. ? slotPreset?.preset_name
  5322. : undefined;
  5323. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5324. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5325. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5326. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5327. // Slot-assigned-only spool fill (no tag link required)
  5328. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5329. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5330. : undefined;
  5331. const slotSpoolForFill = slotAssignmentForFill
  5332. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5333. : undefined;
  5334. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5335. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5336. : null;
  5337. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5338. const inventoryFill = (() => {
  5339. const sp = inventoryAssignment?.spool;
  5340. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5341. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5342. }
  5343. return null;
  5344. })();
  5345. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5346. // (inventory weight_used may be stale or over-counted — #676)
  5347. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5348. ? null : inventoryFill;
  5349. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5350. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5351. : resolvedInventoryFill !== null ? 'inventory' as const
  5352. : hasFillLevel ? 'ams' as const
  5353. : undefined;
  5354. // Build filament data for hover card
  5355. const filamentData = tray?.tray_type ? {
  5356. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5357. // Spoolman spool name wins over cloud lookup so a slot bound to
  5358. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5359. // Design PLA") instead of whatever the printer's filament_id
  5360. // resolves to in the cloud catalog (often "Generic PLA" for
  5361. // P-prefix local presets). Spoolman's filament.name is just the
  5362. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5363. // the hover card shows "Devil Design PLA Basic" rather than the
  5364. // vendor-less form. Strip the "@<printer>..." suffix that
  5365. // BambuStudio appends to user-preset names.
  5366. 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,
  5367. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5368. colorHex: tray.tray_color || null,
  5369. kFactor: formatKValue(tray.k),
  5370. fillLevel: effectiveFill,
  5371. trayUuid: tray.tray_uuid || null,
  5372. tagUid: tray.tag_uid || null,
  5373. fillSource,
  5374. } : null;
  5375. // Check if this specific slot is being refreshed
  5376. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5377. refreshingSlot?.slotId === slotIdx;
  5378. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5379. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5380. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5381. ? `P${activePrintSlotIdx + 1}`
  5382. : null;
  5383. // Slot visual content (goes inside hover card)
  5384. const slotVisual = (
  5385. <div
  5386. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5387. isExpectedSlot
  5388. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5389. : isRanOutSlot
  5390. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5391. : isActive
  5392. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5393. : ''
  5394. }`}
  5395. >
  5396. {isExpectedSlot && (
  5397. <span
  5398. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5399. title={t('printers.expectedSlot.title')}
  5400. 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"
  5401. >
  5402. ↓
  5403. </span>
  5404. )}
  5405. {activePrintSlotLabel && (
  5406. <span
  5407. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5408. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5409. 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"
  5410. >
  5411. {activePrintSlotLabel}
  5412. </span>
  5413. )}
  5414. {/* Filament color circle with 1-based slot number centered inside */}
  5415. <FilamentSlotCircle
  5416. trayColor={tray?.tray_color}
  5417. trayType={tray?.tray_type}
  5418. isEmpty={isEmpty}
  5419. emptyKind={emptyKind}
  5420. slotNumber={slotIdx + 1}
  5421. />
  5422. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5423. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5424. </div>
  5425. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5426. {/* Fill bar */}
  5427. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5428. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5429. <div
  5430. className="h-full rounded-full transition-all"
  5431. style={{
  5432. width: `${effectiveFill}%`,
  5433. backgroundColor: getFillBarColor(effectiveFill),
  5434. }}
  5435. />
  5436. )}
  5437. </div>
  5438. </div>
  5439. );
  5440. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5441. return (
  5442. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5443. {/* Loading overlay during RFID re-read */}
  5444. {isRefreshing && (
  5445. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5446. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5447. </div>
  5448. )}
  5449. {/* Hover card wraps only the visual content */}
  5450. {filamentData ? (
  5451. <FilamentHoverCard
  5452. data={filamentData}
  5453. actions={renderAmsSlotActions({
  5454. amsId: ams.id,
  5455. slotId: slotIdx,
  5456. loadTrayId: ams.id * 4 + slotIdx,
  5457. isRefreshing,
  5458. })}
  5459. spoolman={{
  5460. enabled: spoolmanEnabled,
  5461. // #1457: slot assignment is the user's most explicit action — it must
  5462. // outrank the tag-link, which can be stale when a non-RFID slot's
  5463. // fallback tag is still attached to a previous spool in Spoolman.
  5464. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5465. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5466. spoolmanUrl,
  5467. syncMode: spoolmanSyncMode,
  5468. // Suppress Link button when slot is already occupied by ANY assignment
  5469. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5470. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5471. // still appearing on slots with a local Devil Design PLA assigned.
  5472. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5473. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5474. setLinkSpoolModal({
  5475. tagUid: filamentData.tagUid || linkTag,
  5476. trayUuid: filamentData.trayUuid || '',
  5477. printerId: printer.id,
  5478. amsId: ams.id,
  5479. trayId: slotIdx,
  5480. });
  5481. } : undefined,
  5482. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5483. }}
  5484. inventory={(() => {
  5485. if (spoolmanEnabled) {
  5486. if (spoolmanLoading) return undefined;
  5487. const slotAssignment = slotAssignmentForFill;
  5488. const spoolmanSpool = slotSpoolForFill;
  5489. return {
  5490. assignedSpool: spoolmanSpool ? {
  5491. id: spoolmanSpool.id,
  5492. material: spoolmanSpool.material,
  5493. subtype: spoolmanSpool.subtype,
  5494. brand: spoolmanSpool.brand ?? null,
  5495. color_name: spoolmanSpool.color_name ?? null,
  5496. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5497. // The spool's own swatch (#2967). Spoolman carries the
  5498. // extra stops but has no effect field at all, so those
  5499. // rolls gradient and never shimmer.
  5500. rgba: spoolmanSpool.rgba ?? null,
  5501. extra_colors: spoolmanSpool.extra_colors ?? null,
  5502. effect_type: spoolmanSpool.effect_type ?? null,
  5503. remainingWeightGrams: spoolmanSpool.label_weight
  5504. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5505. : undefined,
  5506. } : null,
  5507. onAssignSpool: () => setAssignSpoolModal({
  5508. printerId: printer.id,
  5509. amsId: ams.id,
  5510. trayId: slotIdx,
  5511. trayInfo: {
  5512. type: tray?.tray_type || filamentData.profile,
  5513. material: tray?.tray_type ?? undefined,
  5514. profile: filamentData.profile,
  5515. color: filamentData.colorHex || '',
  5516. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5517. },
  5518. }),
  5519. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5520. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5521. };
  5522. }
  5523. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5524. return {
  5525. assignedSpool: assignment?.spool ? {
  5526. id: assignment.spool.id,
  5527. material: assignment.spool.material,
  5528. subtype: assignment.spool.subtype,
  5529. brand: assignment.spool.brand,
  5530. color_name: assignment.spool.color_name,
  5531. // The spool's own swatch (#2967).
  5532. rgba: assignment.spool.rgba ?? null,
  5533. extra_colors: assignment.spool.extra_colors ?? null,
  5534. effect_type: assignment.spool.effect_type ?? null,
  5535. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5536. } : null,
  5537. onAssignSpool: () => setAssignSpoolModal({
  5538. printerId: printer.id,
  5539. amsId: ams.id,
  5540. trayId: slotIdx,
  5541. trayInfo: {
  5542. type: tray?.tray_type || filamentData.profile,
  5543. material: tray?.tray_type ?? undefined,
  5544. profile: filamentData.profile,
  5545. color: filamentData.colorHex || '',
  5546. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5547. },
  5548. }),
  5549. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5550. isAssigned: !!assignment || isBambuLabSpool(tray),
  5551. };
  5552. })()}
  5553. configureSlot={{
  5554. enabled: hasPermission('printers:control'),
  5555. onConfigure: () => setConfigureSlotModal({
  5556. amsId: ams.id,
  5557. trayId: slotIdx,
  5558. trayCount: ams.tray.length,
  5559. trayType: tray?.tray_type || undefined,
  5560. trayColor: tray?.tray_color || undefined,
  5561. traySubBrands: tray?.tray_sub_brands || undefined,
  5562. trayInfoIdx: tray?.tray_info_idx || undefined,
  5563. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5564. caliIdx: tray?.cali_idx,
  5565. savedPresetId: slotPreset?.preset_id,
  5566. }),
  5567. }}
  5568. >
  5569. {slotVisual}
  5570. </FilamentHoverCard>
  5571. ) : (
  5572. <EmptySlotHoverCard
  5573. kind={emptyKind ?? undefined}
  5574. actions={renderAmsSlotActions({
  5575. amsId: ams.id,
  5576. slotId: slotIdx,
  5577. loadTrayId: ams.id * 4 + slotIdx,
  5578. isRefreshing,
  5579. })}
  5580. configureSlot={{
  5581. enabled: hasPermission('printers:control'),
  5582. onConfigure: () => setConfigureSlotModal({
  5583. amsId: ams.id,
  5584. trayId: slotIdx,
  5585. trayCount: ams.tray.length,
  5586. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5587. }),
  5588. }}
  5589. onAssignSpool={() => setAssignSpoolModal({
  5590. printerId: printer.id,
  5591. amsId: ams.id,
  5592. trayId: slotIdx,
  5593. trayInfo: {
  5594. type: '',
  5595. material: undefined,
  5596. profile: '',
  5597. color: '',
  5598. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5599. },
  5600. })}
  5601. >
  5602. {slotVisual}
  5603. </EmptySlotHoverCard>
  5604. )}
  5605. </div>
  5606. );
  5607. })}
  5608. </div>
  5609. </div>
  5610. );
  5611. })}
  5612. {/* HT AMS units */}
  5613. {htAms.map((ams) => {
  5614. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5615. const tray = ams.tray[0];
  5616. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5617. const isEmpty = !tray?.tray_type;
  5618. const emptyKind = getEmptySlotKind(tray);
  5619. // Check if this is the currently loaded tray
  5620. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5621. const isActive = effectiveTrayNow === globalTrayId;
  5622. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5623. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5624. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5625. // Get cloud preset info if available
  5626. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5627. // Get saved slot preset mapping (for user-configured slots)
  5628. const slotPreset = slotPresets?.[globalTrayId];
  5629. // Only trusted while it still describes what the printer reports in the
  5630. // slot: the row survives a spool swap, and the display chain below puts
  5631. // it ahead of the live filament id (see slotPresetDescribesTray).
  5632. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5633. ? slotPreset?.preset_name
  5634. : undefined;
  5635. const htSlotId = tray?.id ?? 0;
  5636. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5637. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5638. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5639. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5640. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5641. const htInventoryFill = (() => {
  5642. const sp = htInventoryAssignment?.spool;
  5643. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5644. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5645. }
  5646. return null;
  5647. })();
  5648. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5649. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5650. ? null : htInventoryFill;
  5651. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5652. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5653. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5654. : undefined;
  5655. const htSlotSpoolForFill = htSlotAssignmentForFill
  5656. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5657. : undefined;
  5658. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5659. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5660. : null;
  5661. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5662. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5663. : htResolvedInventoryFill !== null ? 'inventory' as const
  5664. : hasFillLevel ? 'ams' as const
  5665. : undefined;
  5666. // Build filament data for hover card
  5667. const filamentData = tray?.tray_type ? {
  5668. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5669. 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,
  5670. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5671. colorHex: tray.tray_color || null,
  5672. kFactor: formatKValue(tray.k),
  5673. fillLevel: htEffectiveFill,
  5674. trayUuid: tray.tray_uuid || null,
  5675. tagUid: tray.tag_uid || null,
  5676. fillSource: htFillSource,
  5677. } : null;
  5678. // Check if this specific slot is being refreshed
  5679. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5680. refreshingSlot?.slotId === htSlotId;
  5681. // #1762 (comment 2): active print-slot index for this HT slot.
  5682. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5683. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5684. ? `P${htActivePrintSlotIdx + 1}`
  5685. : null;
  5686. // Slot visual content (goes inside hover card)
  5687. const slotVisual = (
  5688. <div
  5689. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5690. isExpectedSlot
  5691. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5692. : isRanOutSlot
  5693. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5694. : isActive
  5695. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5696. : ''
  5697. }`}
  5698. >
  5699. {isExpectedSlot && (
  5700. <span
  5701. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5702. title={t('printers.expectedSlot.title')}
  5703. 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"
  5704. >
  5705. ↓
  5706. </span>
  5707. )}
  5708. {htActivePrintSlotLabel && (
  5709. <span
  5710. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5711. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5712. 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"
  5713. >
  5714. {htActivePrintSlotLabel}
  5715. </span>
  5716. )}
  5717. {/* Filament color circle with 1-based slot number centered inside */}
  5718. <FilamentSlotCircle
  5719. trayColor={tray?.tray_color}
  5720. trayType={tray?.tray_type}
  5721. isEmpty={isEmpty}
  5722. emptyKind={emptyKind}
  5723. slotNumber={1}
  5724. />
  5725. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5726. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5727. </div>
  5728. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5729. {/* Fill bar */}
  5730. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5731. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5732. <div
  5733. className="h-full rounded-full transition-all"
  5734. style={{
  5735. width: `${htEffectiveFill}%`,
  5736. backgroundColor: getFillBarColor(htEffectiveFill),
  5737. }}
  5738. />
  5739. )}
  5740. </div>
  5741. </div>
  5742. );
  5743. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5744. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5745. // Without this override, the L view squishes HT into a sliver next to the
  5746. // 4-slot AMS neighbors.
  5747. // 11rem holds one slot plus the temperature/humidity
  5748. // column beside it; both grow with the body scale.
  5749. const htCardWidth = scaledRem(11);
  5750. const htCardStyle: React.CSSProperties = {
  5751. flex: `1 1 ${htCardWidth}`,
  5752. minWidth: htCardWidth,
  5753. // An AMS-HT is never wider than a full AMS. Without a
  5754. // ceiling, a unit that wraps onto a line of its own is
  5755. // the only flex item there and grow stretches its single
  5756. // slot across the entire card, leaving the readings
  5757. // stranded at the far edge.
  5758. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5759. };
  5760. return (
  5761. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5762. {/* Row 1: Label + Nozzle + Drying */}
  5763. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5764. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5765. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5766. <AmsNameHoverCard
  5767. ams={ams}
  5768. printerId={printer.id}
  5769. label={getAmsLabel(ams.id, ams.tray.length)}
  5770. amsLabels={amsLabels}
  5771. canEdit={hasPermission('printers:update')}
  5772. onSaved={refetchAmsLabels}
  5773. >
  5774. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5775. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5776. </span>
  5777. </AmsNameHoverCard>
  5778. {sideBadge?.kind === 'inlet' ? (
  5779. <InletBadge
  5780. inlet={sideBadge.inlet}
  5781. title={t('printers.amsSwitchInletTooltip', {
  5782. inlet: sideBadge.inlet,
  5783. side: FTS_INLET_SIDE[sideBadge.inlet],
  5784. })}
  5785. />
  5786. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5787. <NozzleBadge side={sideBadge.side} />
  5788. ) : null}
  5789. </div>
  5790. {/* Drying button for HT AMS */}
  5791. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5792. <div className="relative ml-auto">
  5793. <button
  5794. disabled={status.drying_screen_only}
  5795. onClick={(e) => {
  5796. if (ams.dry_time > 0) {
  5797. stopDryingMutation.mutate(ams.id);
  5798. } else if (dryingPopoverAmsId === ams.id) {
  5799. setDryingPopoverAmsId(null);
  5800. } else {
  5801. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5802. }
  5803. }}
  5804. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5805. ams.dry_time > 0
  5806. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5807. : status.drying_screen_only
  5808. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5809. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5810. }`}
  5811. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5812. >
  5813. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5814. </button>
  5815. </div>
  5816. )}
  5817. </div>
  5818. {/* HT AMS drying status bar. Same not-running split as the
  5819. standard-AMS bar above: a frozen countdown is not a
  5820. running cycle. */}
  5821. {ams.dry_time > 0 && (
  5822. <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}>
  5823. {ams.dry_countdown_stalled
  5824. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5825. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5826. {ams.dry_countdown_stalled && (
  5827. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5828. )}
  5829. {ams.dry_filament && (
  5830. <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`}>
  5831. {ams.dry_target_temp != null
  5832. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5833. : ams.dry_filament}
  5834. </span>
  5835. )}
  5836. {!ams.dry_countdown_stalled && (
  5837. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5838. {ams.dry_time >= 60
  5839. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5840. : `${ams.dry_time}m`}
  5841. </span>
  5842. )}
  5843. {!status.drying_screen_only && (
  5844. <button
  5845. onClick={() => stopDryingMutation.mutate(ams.id)}
  5846. disabled={stopDryingMutation.isPending}
  5847. 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"
  5848. title={t('printers.drying.stop')}
  5849. >
  5850. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5851. </button>
  5852. )}
  5853. </div>
  5854. )}
  5855. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5856. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5857. {/* Slot wrapper with loading overlay */}
  5858. <div className="relative group flex-1" style={htSlotStyle}>
  5859. {/* Loading overlay during RFID re-read */}
  5860. {isHtRefreshing && (
  5861. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5862. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5863. </div>
  5864. )}
  5865. {/* Hover card wraps only the visual content */}
  5866. {filamentData ? (
  5867. <FilamentHoverCard
  5868. data={filamentData}
  5869. actions={renderAmsSlotActions({
  5870. amsId: ams.id,
  5871. slotId: htSlotId,
  5872. loadTrayId: ams.id * 4 + htSlotId,
  5873. isRefreshing: isHtRefreshing,
  5874. })}
  5875. spoolman={{
  5876. enabled: spoolmanEnabled,
  5877. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5878. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5879. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5880. spoolmanUrl,
  5881. syncMode: spoolmanSyncMode,
  5882. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5883. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5884. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5885. setLinkSpoolModal({
  5886. tagUid: filamentData.tagUid || linkTag,
  5887. trayUuid: filamentData.trayUuid || '',
  5888. printerId: printer.id,
  5889. amsId: ams.id,
  5890. trayId: htSlotId,
  5891. });
  5892. } : undefined,
  5893. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5894. }}
  5895. inventory={(() => {
  5896. if (spoolmanEnabled) {
  5897. if (spoolmanLoading) return undefined;
  5898. const slotAssignment = htSlotAssignmentForFill;
  5899. const spoolmanSpool = htSlotSpoolForFill;
  5900. return {
  5901. assignedSpool: spoolmanSpool ? {
  5902. id: spoolmanSpool.id,
  5903. material: spoolmanSpool.material,
  5904. subtype: spoolmanSpool.subtype,
  5905. brand: spoolmanSpool.brand ?? null,
  5906. color_name: spoolmanSpool.color_name ?? null,
  5907. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5908. // The spool's own swatch (#2967). Spoolman carries the
  5909. // extra stops but has no effect field at all, so those
  5910. // rolls gradient and never shimmer.
  5911. rgba: spoolmanSpool.rgba ?? null,
  5912. extra_colors: spoolmanSpool.extra_colors ?? null,
  5913. effect_type: spoolmanSpool.effect_type ?? null,
  5914. remainingWeightGrams: spoolmanSpool.label_weight
  5915. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5916. : undefined,
  5917. } : null,
  5918. onAssignSpool: () => setAssignSpoolModal({
  5919. printerId: printer.id,
  5920. amsId: ams.id,
  5921. trayId: htSlotId,
  5922. trayInfo: {
  5923. type: tray?.tray_type || filamentData.profile,
  5924. material: tray?.tray_type ?? undefined,
  5925. profile: filamentData.profile,
  5926. color: filamentData.colorHex || '',
  5927. location: getAmsLabel(ams.id, ams.tray.length),
  5928. },
  5929. }),
  5930. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5931. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5932. };
  5933. }
  5934. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5935. return {
  5936. assignedSpool: assignment?.spool ? {
  5937. id: assignment.spool.id,
  5938. material: assignment.spool.material,
  5939. subtype: assignment.spool.subtype,
  5940. brand: assignment.spool.brand,
  5941. color_name: assignment.spool.color_name,
  5942. // The spool's own swatch (#2967).
  5943. rgba: assignment.spool.rgba ?? null,
  5944. extra_colors: assignment.spool.extra_colors ?? null,
  5945. effect_type: assignment.spool.effect_type ?? null,
  5946. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5947. } : null,
  5948. onAssignSpool: () => setAssignSpoolModal({
  5949. printerId: printer.id,
  5950. amsId: ams.id,
  5951. trayId: htSlotId,
  5952. trayInfo: {
  5953. type: tray?.tray_type || filamentData.profile,
  5954. material: tray?.tray_type ?? undefined,
  5955. profile: filamentData.profile,
  5956. color: filamentData.colorHex || '',
  5957. location: getAmsLabel(ams.id, ams.tray.length),
  5958. },
  5959. }),
  5960. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5961. isAssigned: !!assignment || isBambuLabSpool(tray),
  5962. };
  5963. })()}
  5964. configureSlot={{
  5965. enabled: hasPermission('printers:control'),
  5966. onConfigure: () => setConfigureSlotModal({
  5967. amsId: ams.id,
  5968. trayId: htSlotId,
  5969. trayCount: ams.tray.length,
  5970. trayType: tray?.tray_type || undefined,
  5971. trayColor: tray?.tray_color || undefined,
  5972. traySubBrands: tray?.tray_sub_brands || undefined,
  5973. trayInfoIdx: tray?.tray_info_idx || undefined,
  5974. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5975. caliIdx: tray?.cali_idx,
  5976. savedPresetId: slotPreset?.preset_id,
  5977. }),
  5978. }}
  5979. >
  5980. {slotVisual}
  5981. </FilamentHoverCard>
  5982. ) : (
  5983. <EmptySlotHoverCard
  5984. kind={emptyKind ?? undefined}
  5985. actions={renderAmsSlotActions({
  5986. amsId: ams.id,
  5987. slotId: htSlotId,
  5988. loadTrayId: ams.id * 4 + htSlotId,
  5989. isRefreshing: isHtRefreshing,
  5990. })}
  5991. configureSlot={{
  5992. enabled: hasPermission('printers:control'),
  5993. onConfigure: () => setConfigureSlotModal({
  5994. amsId: ams.id,
  5995. trayId: htSlotId,
  5996. trayCount: ams.tray.length,
  5997. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5998. }),
  5999. }}
  6000. onAssignSpool={() => setAssignSpoolModal({
  6001. printerId: printer.id,
  6002. amsId: ams.id,
  6003. trayId: htSlotId,
  6004. trayInfo: {
  6005. type: '',
  6006. material: undefined,
  6007. profile: '',
  6008. color: '',
  6009. location: getAmsLabel(ams.id, ams.tray.length),
  6010. },
  6011. })}
  6012. >
  6013. {slotVisual}
  6014. </EmptySlotHoverCard>
  6015. )}
  6016. </div>
  6017. {/* Stats stacked vertically: Temp on top, Humidity below */}
  6018. {(ams.humidity != null || ams.temp != null) && (
  6019. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  6020. {ams.temp != null && (
  6021. <TemperatureIndicator
  6022. temp={ams.temp}
  6023. goodThreshold={amsThresholds?.tempGood}
  6024. fairThreshold={amsThresholds?.tempFair}
  6025. onClick={() => setAmsHistoryModal({
  6026. amsId: ams.id,
  6027. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  6028. mode: 'temperature',
  6029. })}
  6030. compact
  6031. />
  6032. )}
  6033. {ams.humidity != null && (
  6034. <HumidityIndicator
  6035. humidity={ams.humidity}
  6036. goodThreshold={amsThresholds?.humidityGood}
  6037. fairThreshold={amsThresholds?.humidityFair}
  6038. onClick={() => setAmsHistoryModal({
  6039. amsId: ams.id,
  6040. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  6041. mode: 'humidity',
  6042. })}
  6043. compact
  6044. />
  6045. )}
  6046. </div>
  6047. )}
  6048. </div>
  6049. </div>
  6050. );
  6051. })}
  6052. {/* External spool(s) - grouped in one card like regular AMS */}
  6053. {status.vt_tray.length > 0 && showExternalSpool && (
  6054. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  6055. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  6056. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  6057. </div>
  6058. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  6059. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  6060. const extTrayId = extTray.id ?? 254;
  6061. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  6062. // generically — use active_extruder to determine L vs R:
  6063. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  6064. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  6065. ? (extTrayId === 254 && status.active_extruder === 1) ||
  6066. (extTrayId === 255 && status.active_extruder === 0)
  6067. : effectiveTrayNow === extTrayId;
  6068. const slotTrayId = extTrayId - 254; // 0 or 1
  6069. const extLabel = isDualNozzle
  6070. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6071. : '';
  6072. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6073. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6074. // Only trusted while it still describes what the printer reports in the
  6075. // slot: the row survives a spool swap, and the display chain below puts
  6076. // it ahead of the live filament id (see slotPresetDescribesTray).
  6077. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx)
  6078. ? extSlotPreset?.preset_name
  6079. : undefined;
  6080. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6081. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6082. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6083. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6084. const extInventoryFill = (() => {
  6085. const sp = extInventoryAssignment?.spool;
  6086. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6087. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6088. }
  6089. return null;
  6090. })();
  6091. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6092. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6093. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6094. ? null : extInventoryFill;
  6095. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6096. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6097. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6098. : undefined;
  6099. const extSlotSpoolForFill = extSlotAssignmentForFill
  6100. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6101. : undefined;
  6102. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6103. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6104. : null;
  6105. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6106. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6107. : extResolvedInventoryFill !== null ? 'inventory' as const
  6108. : extHasFillLevel ? 'ams' as const
  6109. : undefined;
  6110. const extFilamentData = {
  6111. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6112. 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',
  6113. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6114. colorHex: extTray.tray_color || null,
  6115. kFactor: formatKValue(extTray.k),
  6116. fillLevel: extEffectiveFill,
  6117. trayUuid: extTray.tray_uuid || null,
  6118. tagUid: extTray.tag_uid || null,
  6119. fillSource: extFillSource,
  6120. };
  6121. const isEmpty = !extTray.tray_type;
  6122. const emptyKind = getEmptySlotKind(extTray);
  6123. const extSlotContent = (
  6124. <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' : ''}`}>
  6125. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6126. the separate Ext-L/Ext-R caption that made the row taller than
  6127. regular AMS slots), 1-based slot number on single-nozzle. */}
  6128. <FilamentSlotCircle
  6129. trayColor={extTray.tray_color}
  6130. trayType={extTray.tray_type}
  6131. isEmpty={isEmpty}
  6132. emptyKind={emptyKind}
  6133. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6134. />
  6135. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6136. {extTray.tray_type || t('ams.slotEmpty')}
  6137. </div>
  6138. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6139. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6140. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6141. <div
  6142. className="h-full rounded-full transition-all"
  6143. style={{
  6144. width: `${extEffectiveFill}%`,
  6145. backgroundColor: getFillBarColor(extEffectiveFill),
  6146. }}
  6147. />
  6148. )}
  6149. </div>
  6150. </div>
  6151. );
  6152. return (
  6153. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6154. {!isEmpty ? (
  6155. <FilamentHoverCard
  6156. data={extFilamentData}
  6157. actions={renderAmsSlotActions({
  6158. amsId: 255,
  6159. slotId: slotTrayId,
  6160. loadTrayId: extTrayId,
  6161. includeRfid: false,
  6162. })}
  6163. spoolman={{
  6164. enabled: spoolmanEnabled,
  6165. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6166. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6167. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6168. spoolmanUrl,
  6169. syncMode: spoolmanSyncMode,
  6170. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6171. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6172. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6173. setLinkSpoolModal({
  6174. tagUid: extFilamentData.tagUid || linkTag,
  6175. trayUuid: extFilamentData.trayUuid || '',
  6176. printerId: printer.id,
  6177. amsId: 255,
  6178. trayId: slotTrayId,
  6179. });
  6180. } : undefined,
  6181. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6182. }}
  6183. inventory={(() => {
  6184. if (spoolmanEnabled) {
  6185. if (spoolmanLoading) return undefined;
  6186. const slotAssignment = extSlotAssignmentForFill;
  6187. const spoolmanSpool = extSlotSpoolForFill;
  6188. return {
  6189. assignedSpool: spoolmanSpool ? {
  6190. id: spoolmanSpool.id,
  6191. material: spoolmanSpool.material,
  6192. subtype: spoolmanSpool.subtype,
  6193. brand: spoolmanSpool.brand ?? null,
  6194. color_name: spoolmanSpool.color_name ?? null,
  6195. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6196. // The spool's own swatch (#2967). Spoolman carries the
  6197. // extra stops but has no effect field at all, so those
  6198. // rolls gradient and never shimmer.
  6199. rgba: spoolmanSpool.rgba ?? null,
  6200. extra_colors: spoolmanSpool.extra_colors ?? null,
  6201. effect_type: spoolmanSpool.effect_type ?? null,
  6202. remainingWeightGrams: spoolmanSpool.label_weight
  6203. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6204. : undefined,
  6205. } : null,
  6206. onAssignSpool: () => setAssignSpoolModal({
  6207. printerId: printer.id,
  6208. amsId: 255,
  6209. trayId: slotTrayId,
  6210. trayInfo: {
  6211. type: extTray.tray_type || extFilamentData.profile,
  6212. material: extTray.tray_type ?? undefined,
  6213. profile: extFilamentData.profile,
  6214. color: extFilamentData.colorHex || '',
  6215. location: extLabel || t('printers.external'),
  6216. },
  6217. }),
  6218. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6219. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6220. };
  6221. }
  6222. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6223. return {
  6224. assignedSpool: assignment?.spool ? {
  6225. id: assignment.spool.id,
  6226. material: assignment.spool.material,
  6227. subtype: assignment.spool.subtype,
  6228. brand: assignment.spool.brand,
  6229. color_name: assignment.spool.color_name,
  6230. // The spool's own swatch (#2967).
  6231. rgba: assignment.spool.rgba ?? null,
  6232. extra_colors: assignment.spool.extra_colors ?? null,
  6233. effect_type: assignment.spool.effect_type ?? null,
  6234. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6235. } : null,
  6236. onAssignSpool: () => setAssignSpoolModal({
  6237. printerId: printer.id,
  6238. amsId: 255,
  6239. trayId: slotTrayId,
  6240. trayInfo: {
  6241. type: extTray.tray_type || extFilamentData.profile,
  6242. material: extTray.tray_type ?? undefined,
  6243. profile: extFilamentData.profile,
  6244. color: extFilamentData.colorHex || '',
  6245. location: extLabel || t('printers.external'),
  6246. },
  6247. }),
  6248. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6249. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6250. };
  6251. })()}
  6252. configureSlot={{
  6253. enabled: hasPermission('printers:control'),
  6254. onConfigure: () => setConfigureSlotModal({
  6255. amsId: 255,
  6256. trayId: slotTrayId,
  6257. trayCount: 1,
  6258. trayType: extTray.tray_type || undefined,
  6259. trayColor: extTray.tray_color || undefined,
  6260. traySubBrands: extTray.tray_sub_brands || undefined,
  6261. trayInfoIdx: extTray.tray_info_idx || undefined,
  6262. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6263. caliIdx: extTray.cali_idx,
  6264. savedPresetId: extSlotPreset?.preset_id,
  6265. }),
  6266. }}
  6267. >
  6268. {extSlotContent}
  6269. </FilamentHoverCard>
  6270. ) : (
  6271. <EmptySlotHoverCard
  6272. kind={emptyKind ?? undefined}
  6273. actions={renderAmsSlotActions({
  6274. amsId: 255,
  6275. slotId: slotTrayId,
  6276. loadTrayId: extTrayId,
  6277. includeRfid: false,
  6278. })}
  6279. configureSlot={{
  6280. enabled: hasPermission('printers:control'),
  6281. onConfigure: () => setConfigureSlotModal({
  6282. amsId: 255,
  6283. trayId: slotTrayId,
  6284. trayCount: 1,
  6285. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6286. }),
  6287. }}
  6288. onAssignSpool={() => setAssignSpoolModal({
  6289. printerId: printer.id,
  6290. amsId: 255,
  6291. trayId: slotTrayId,
  6292. trayInfo: {
  6293. type: '',
  6294. material: undefined,
  6295. profile: '',
  6296. color: '',
  6297. location: `External Slot ${slotTrayId + 1}`,
  6298. },
  6299. })}
  6300. >
  6301. {extSlotContent}
  6302. </EmptySlotHoverCard>
  6303. )}
  6304. </div>
  6305. );
  6306. })}
  6307. </div>
  6308. </div>
  6309. )}
  6310. </div>
  6311. </div>
  6312. );
  6313. })()}
  6314. </>
  6315. )}
  6316. {/* Powered-down printer with a dirty plate: the status block above renders
  6317. nothing without a live connection, so the plate-clear control gets its own
  6318. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6319. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6320. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6321. expandedClearPlateButton
  6322. )}
  6323. {/* Bottom block (power row + action bar). Wrapped together so the
  6324. power row hugs the action bar at the card bottom instead of
  6325. floating up when there's less filament content above. */}
  6326. {viewMode === 'expanded' && (
  6327. <div className="mt-auto">
  6328. {smartPlug && (
  6329. <div className="pt-3">
  6330. <div className="flex items-center gap-2 mb-2">
  6331. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6332. {t('printers.power', 'Power')}
  6333. </span>
  6334. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6335. </div>
  6336. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6337. {/* Plug name + current power */}
  6338. <div className="flex items-center gap-2 min-w-0 pl-1">
  6339. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6340. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6341. <span
  6342. 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"
  6343. title={t('smartPlugs.power')}
  6344. >
  6345. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6346. </span>
  6347. </div>
  6348. {/* Spacer */}
  6349. <div className="flex-1" />
  6350. <div className="flex items-center gap-2">
  6351. {/* Auto-off */}
  6352. <button
  6353. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6354. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6355. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6356. 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 ${
  6357. !hasPermission('smart_plugs:control')
  6358. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6359. : smartPlug.auto_off || smartPlug.auto_off_executed
  6360. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6361. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6362. }`}
  6363. >
  6364. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6365. </button>
  6366. <button
  6367. onClick={() => {
  6368. if (plugStatus?.state === 'ON') {
  6369. setShowPowerOffConfirm(true);
  6370. } else {
  6371. setShowPowerOnConfirm(true);
  6372. }
  6373. }}
  6374. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6375. 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 ${
  6376. !hasPermission('smart_plugs:control')
  6377. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6378. : plugStatus?.state === 'ON'
  6379. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6380. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6381. }`}
  6382. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6383. >
  6384. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6385. </button>
  6386. </div>
  6387. </div>
  6388. {/* HA entity buttons row */}
  6389. {scriptPlugs && scriptPlugs.length > 0 && (
  6390. <div className="flex items-center gap-2 mt-2">
  6391. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6392. <span className="text-xs text-bambu-gray">HA:</span>
  6393. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6394. <div className="flex flex-wrap gap-1">
  6395. {scriptPlugs.map(script => {
  6396. const isScript = script.ha_entity_id?.startsWith('script.');
  6397. return (
  6398. <button
  6399. key={script.id}
  6400. onClick={() => {
  6401. if (isScript) {
  6402. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6403. } else {
  6404. setHaToggleConfirm(script);
  6405. }
  6406. }}
  6407. disabled={runScriptMutation.isPending}
  6408. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6409. 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"
  6410. >
  6411. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6412. {script.name}
  6413. </button>
  6414. );
  6415. })}
  6416. </div>
  6417. </div>
  6418. )}
  6419. </div>
  6420. )}
  6421. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6422. a printer can have an enclosure door contact without having a plug,
  6423. and nesting it there would hide the row on exactly those setups. */}
  6424. <PrinterHASensorRow printerId={printer.id} />
  6425. {/* Connection Info & Actions */}
  6426. <div className="pt-4">
  6427. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6428. <div className="flex items-center justify-between gap-2">
  6429. {printerActionsMenu}
  6430. <div className="flex items-center justify-end gap-2 flex-wrap">
  6431. {/* Camera split button: the icon opens whichever view was used
  6432. last, the caret picks between the two and remembers it.
  6433. Replaces the old Settings > General > Camera switch, which
  6434. made choosing between an overlay and a window a trip to
  6435. another page for something you decide per camera. */}
  6436. <div className="flex items-center flex-shrink-0">
  6437. <Button
  6438. variant="secondary"
  6439. size="sm"
  6440. onClick={() => openCameraIn(cameraViewMode)}
  6441. disabled={!status?.connected || !hasPermission('camera:view')}
  6442. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6443. className={`${footerIconButtonClass} !rounded-r-none`}
  6444. >
  6445. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6446. </Button>
  6447. <Button
  6448. variant="secondary"
  6449. size="sm"
  6450. onClick={(e) => {
  6451. // No open/close toggle: the menu's own outside-mousedown
  6452. // handler has already dismissed it by the time this lands.
  6453. const rect = e.currentTarget.getBoundingClientRect();
  6454. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6455. }}
  6456. disabled={!status?.connected || !hasPermission('camera:view')}
  6457. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6458. aria-label={t('settings.cameraViewMode')}
  6459. // Not footerIconButtonClass plus an override: both widths
  6460. // would carry !important and the stylesheet's own order,
  6461. // not this one, would decide which won.
  6462. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6463. >
  6464. <ChevronDown className="w-3 h-3" />
  6465. </Button>
  6466. </div>
  6467. {cameraMenuAnchor && (
  6468. <ContextMenu
  6469. x={cameraMenuAnchor.x}
  6470. y={cameraMenuAnchor.y}
  6471. items={cameraViewModeMenuItems}
  6472. onClose={() => setCameraMenuAnchor(null)}
  6473. />
  6474. )}
  6475. <Button
  6476. variant="secondary"
  6477. size="sm"
  6478. onClick={() => setShowFileManager(true)}
  6479. disabled={!hasPermission('printers:files')}
  6480. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6481. className={footerIconButtonClass}
  6482. >
  6483. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6484. </Button>
  6485. {/* Shown whatever the printer is doing (#2849): this uploads a
  6486. file and queues it, which a busy or offline printer is no
  6487. reason to refuse -- it only means the item waits. Hiding it
  6488. while the drop zone accepted the same file would have left
  6489. the two routes into this flow disagreeing. */}
  6490. <Button
  6491. size="sm"
  6492. onClick={() => setShowUploadForPrint(true)}
  6493. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6494. title={
  6495. !hasPermission('library:upload')
  6496. ? t('fileManager.noPermissionUpload')
  6497. : !hasPermission('queue:create')
  6498. ? t('fileManager.noPermissionAddToQueue')
  6499. : t('common.print')
  6500. }
  6501. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6502. >
  6503. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6504. {t('common.print')}
  6505. </Button>
  6506. </div>
  6507. </div>
  6508. </div>
  6509. </div>
  6510. )}
  6511. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6512. card's horizontal padding instead of running full-bleed into the
  6513. rounded bottom edge. */}
  6514. <ScheduledDryingBanner
  6515. printerId={printer.id}
  6516. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6517. timeFormat={timeFormat}
  6518. />
  6519. </CardContent>
  6520. {/* File Manager Modal */}
  6521. {showFileManager && (
  6522. <FileManagerModal
  6523. printerId={printer.id}
  6524. printerName={printer.name}
  6525. onClose={() => setShowFileManager(false)}
  6526. />
  6527. )}
  6528. {/* Upload for Print Modal */}
  6529. {showUploadForPrint && (
  6530. <FileUploadModal
  6531. folderId={null}
  6532. onClose={() => setShowUploadForPrint(false)}
  6533. onUploadComplete={() => {}}
  6534. autoUpload
  6535. accept=".gcode,.3mf"
  6536. validateFile={(file) => {
  6537. const lower = file.name.toLowerCase();
  6538. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6539. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6540. }
  6541. }}
  6542. onFileUploaded={(uploadedFile) => {
  6543. // Check printer compatibility if sliced_for_model is available in metadata
  6544. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6545. const printerModel = mapModelCode(printer.model);
  6546. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6547. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6548. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6549. }
  6550. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6551. }}
  6552. />
  6553. )}
  6554. {/* Print Modal (after upload) */}
  6555. {printAfterUpload && (
  6556. <PrintModal
  6557. mode="create"
  6558. libraryFileId={printAfterUpload.id}
  6559. archiveName={printAfterUpload.filename}
  6560. initialSelectedPrinterIds={[printer.id]}
  6561. onClose={() => setPrintAfterUpload(null)}
  6562. onSuccess={() => setPrintAfterUpload(null)}
  6563. cleanupLibraryAfterDispatch
  6564. />
  6565. )}
  6566. {/* MQTT Debug Modal */}
  6567. {showMQTTDebug && (
  6568. <MQTTDebugModal
  6569. printerId={printer.id}
  6570. printerName={printer.name}
  6571. onClose={() => setShowMQTTDebug(false)}
  6572. />
  6573. )}
  6574. {showDiagnostic && (
  6575. <ConnectionDiagnosticModal
  6576. printerId={printer.id}
  6577. printerName={printer.name}
  6578. onClose={() => setShowDiagnostic(false)}
  6579. />
  6580. )}
  6581. {showPrinterInfo && (
  6582. <PrinterInfoModal
  6583. printer={printer}
  6584. status={status}
  6585. totalPrintHours={maintenanceInfo?.total_print_hours}
  6586. onClose={closePrinterInfo}
  6587. />
  6588. )}
  6589. {/* Plate Check Result Modal */}
  6590. {plateCheckResult && (
  6591. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6592. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6593. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6594. <div className="flex items-center gap-2">
  6595. {plateCheckResult.needs_calibration ? (
  6596. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6597. ) : plateCheckResult.is_empty ? (
  6598. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6599. ) : (
  6600. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6601. )}
  6602. <h2 className="text-lg font-semibold text-white">
  6603. Build Plate Check
  6604. </h2>
  6605. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6606. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6607. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6608. </span>
  6609. )}
  6610. </div>
  6611. <button
  6612. onClick={() => closePlateCheckModal()}
  6613. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6614. >
  6615. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6616. </button>
  6617. </div>
  6618. <div className="p-4 space-y-4">
  6619. {plateCheckResult.needs_calibration ? (
  6620. <>
  6621. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6622. <p className="font-medium text-blue-700 dark:text-blue-400">
  6623. {t('printers.plateDetection.calibrationRequired')}
  6624. </p>
  6625. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6626. </div>
  6627. <div className="text-sm text-bambu-gray space-y-2">
  6628. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6629. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6630. </div>
  6631. </>
  6632. ) : (
  6633. <>
  6634. <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'}`}>
  6635. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6636. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6637. </p>
  6638. <p className="text-sm text-bambu-gray mt-1">
  6639. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6640. </p>
  6641. </div>
  6642. {plateCheckResult.debug_image_url && (
  6643. <div>
  6644. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6645. <img
  6646. src={plateCheckResult.debug_image_url}
  6647. alt={t('printers.plateDetection.analysisPreview')}
  6648. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6649. />
  6650. <p className="text-xs text-bambu-gray mt-2">
  6651. {t('printers.plateDetection.analysisLegend')}
  6652. </p>
  6653. </div>
  6654. )}
  6655. <p className="text-xs text-bambu-gray">
  6656. {plateCheckResult.message}
  6657. </p>
  6658. </>
  6659. )}
  6660. {/* Saved References Grid */}
  6661. {plateReferences && plateReferences.references.length > 0 && (
  6662. <div className="mt-4">
  6663. <div className="flex items-center gap-2 mb-2">
  6664. <p className="text-sm font-medium text-white shrink-0">
  6665. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6666. </p>
  6667. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6668. </div>
  6669. <div className="grid grid-cols-5 gap-2">
  6670. {plateReferences.references.map((ref) => (
  6671. <div key={ref.index} className="relative group">
  6672. <img
  6673. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6674. alt={ref.label || `Reference ${ref.index + 1}`}
  6675. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6676. />
  6677. {/* Delete button */}
  6678. <button
  6679. onClick={() => handleDeleteRef(ref.index)}
  6680. 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"
  6681. title={t('printers.plateDetection.deleteReference')}
  6682. >
  6683. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6684. </button>
  6685. {/* Label */}
  6686. {editingRefLabel?.index === ref.index ? (
  6687. <input
  6688. type="text"
  6689. value={editingRefLabel.label}
  6690. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6691. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6692. onKeyDown={(e) => {
  6693. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6694. if (e.key === 'Escape') setEditingRefLabel(null);
  6695. }}
  6696. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6697. autoFocus
  6698. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6699. />
  6700. ) : (
  6701. <p
  6702. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6703. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6704. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6705. >
  6706. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6707. </p>
  6708. )}
  6709. {/* Timestamp */}
  6710. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6711. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6712. </p>
  6713. </div>
  6714. ))}
  6715. </div>
  6716. </div>
  6717. )}
  6718. {/* ROI Editor */}
  6719. {!plateCheckResult.needs_calibration && (
  6720. <div className="mt-4">
  6721. <div className="flex items-center justify-between mb-2">
  6722. <div className="flex min-w-0 flex-1 items-center gap-2">
  6723. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6724. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6725. </div>
  6726. {!editingRoi ? (
  6727. <Button
  6728. variant="ghost"
  6729. size="sm"
  6730. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6731. >
  6732. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6733. {t('common.edit')}
  6734. </Button>
  6735. ) : (
  6736. <div className="flex gap-1">
  6737. <Button
  6738. variant="ghost"
  6739. size="sm"
  6740. onClick={() => setEditingRoi(null)}
  6741. disabled={isSavingRoi}
  6742. >
  6743. {t('common.cancel')}
  6744. </Button>
  6745. <Button
  6746. size="sm"
  6747. onClick={handleSaveRoi}
  6748. disabled={isSavingRoi}
  6749. >
  6750. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6751. </Button>
  6752. </div>
  6753. )}
  6754. </div>
  6755. {editingRoi ? (
  6756. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6757. <div className="grid grid-cols-2 gap-3">
  6758. <div>
  6759. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6760. <input
  6761. type="range"
  6762. min="0"
  6763. max="0.9"
  6764. step="0.01"
  6765. value={editingRoi.x}
  6766. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6767. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6768. />
  6769. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6770. </div>
  6771. <div>
  6772. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6773. <input
  6774. type="range"
  6775. min="0"
  6776. max="0.9"
  6777. step="0.01"
  6778. value={editingRoi.y}
  6779. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6780. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6781. />
  6782. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6783. </div>
  6784. <div>
  6785. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6786. <input
  6787. type="range"
  6788. min="0.1"
  6789. max="1"
  6790. step="0.01"
  6791. value={editingRoi.w}
  6792. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6793. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6794. />
  6795. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6796. </div>
  6797. <div>
  6798. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6799. <input
  6800. type="range"
  6801. min="0.1"
  6802. max="1"
  6803. step="0.01"
  6804. value={editingRoi.h}
  6805. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6806. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6807. />
  6808. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6809. </div>
  6810. </div>
  6811. <p className="text-xs text-bambu-gray">
  6812. {t('printers.roi.instruction')}
  6813. </p>
  6814. </div>
  6815. ) : (
  6816. <p className="text-xs text-bambu-gray">
  6817. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6818. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6819. </p>
  6820. )}
  6821. </div>
  6822. )}
  6823. </div>
  6824. <div className="flex justify-end gap-2 p-4">
  6825. {plateCheckResult.needs_calibration ? (
  6826. <>
  6827. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6828. {t('common.cancel')}
  6829. </Button>
  6830. <Button
  6831. onClick={() => handleCalibratePlate()}
  6832. disabled={isCalibrating}
  6833. >
  6834. {isCalibrating ? (
  6835. <>
  6836. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6837. Calibrating...
  6838. </>
  6839. ) : (
  6840. 'Calibrate Empty Plate'
  6841. )}
  6842. </Button>
  6843. </>
  6844. ) : (
  6845. <>
  6846. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6847. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6848. </Button>
  6849. <Button onClick={() => closePlateCheckModal()}>
  6850. Close
  6851. </Button>
  6852. </>
  6853. )}
  6854. </div>
  6855. </div>
  6856. </div>
  6857. )}
  6858. {/* Power On Confirmation */}
  6859. {showPowerOnConfirm && smartPlug && (
  6860. <ConfirmModal
  6861. title={t('printers.confirm.powerOnTitle')}
  6862. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6863. confirmText={t('printers.confirm.powerOnButton')}
  6864. variant="default"
  6865. onConfirm={() => {
  6866. powerControlMutation.mutate('on');
  6867. setShowPowerOnConfirm(false);
  6868. }}
  6869. onCancel={() => setShowPowerOnConfirm(false)}
  6870. />
  6871. )}
  6872. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6873. disconnects MQTT, which stops progress tracking + completion
  6874. notifications for the in-flight job. Idle / FINISH / FAILED states
  6875. skip this dialog and toggle directly. */}
  6876. {confirmMaintenanceEnter && (
  6877. <ConfirmModal
  6878. title={t('printers.maintenance.confirmMidPrintTitle')}
  6879. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6880. confirmText={t('printers.maintenance.menuEnter')}
  6881. variant="danger"
  6882. onConfirm={() => {
  6883. maintenanceMutation.mutate(false);
  6884. setConfirmMaintenanceEnter(false);
  6885. }}
  6886. onCancel={() => setConfirmMaintenanceEnter(false)}
  6887. />
  6888. )}
  6889. {/* Power Off Confirmation */}
  6890. {showPowerOffConfirm && smartPlug && (
  6891. <ConfirmModal
  6892. title={t('printers.confirm.powerOffTitle')}
  6893. message={
  6894. status?.state === 'RUNNING'
  6895. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6896. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6897. }
  6898. confirmText={t('printers.confirm.powerOffButton')}
  6899. variant="danger"
  6900. onConfirm={() => {
  6901. powerControlMutation.mutate('off');
  6902. setShowPowerOffConfirm(false);
  6903. }}
  6904. onCancel={() => setShowPowerOffConfirm(false)}
  6905. />
  6906. )}
  6907. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6908. {haToggleConfirm && (
  6909. <ConfirmModal
  6910. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6911. message={
  6912. status?.state === 'RUNNING'
  6913. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6914. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6915. }
  6916. confirmText={t('printers.confirm.haToggleButton')}
  6917. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6918. onConfirm={() => {
  6919. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6920. setHaToggleConfirm(null);
  6921. }}
  6922. onCancel={() => setHaToggleConfirm(null)}
  6923. />
  6924. )}
  6925. {/* Stop Print Confirmation */}
  6926. {showStopConfirm && (
  6927. <ConfirmModal
  6928. title={t('printers.confirm.stopTitle')}
  6929. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6930. confirmText={t('printers.confirm.stopButton')}
  6931. variant="danger"
  6932. onConfirm={() => {
  6933. stopPrintMutation.mutate();
  6934. setShowStopConfirm(false);
  6935. }}
  6936. onCancel={() => setShowStopConfirm(false)}
  6937. />
  6938. )}
  6939. {/* Pause Print Confirmation */}
  6940. {showPauseConfirm && (
  6941. <ConfirmModal
  6942. title={t('printers.confirm.pauseTitle')}
  6943. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6944. confirmText={t('printers.confirm.pauseButton')}
  6945. variant="default"
  6946. onConfirm={() => {
  6947. pausePrintMutation.mutate();
  6948. setShowPauseConfirm(false);
  6949. }}
  6950. onCancel={() => setShowPauseConfirm(false)}
  6951. />
  6952. )}
  6953. {/* Resume Print Confirmation */}
  6954. {showResumeConfirm && (
  6955. <ConfirmModal
  6956. title={t('printers.confirm.resumeTitle')}
  6957. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6958. confirmText={t('printers.confirm.resumeButton')}
  6959. variant="default"
  6960. onConfirm={() => {
  6961. resumePrintMutation.mutate();
  6962. setShowResumeConfirm(false);
  6963. }}
  6964. onCancel={() => setShowResumeConfirm(false)}
  6965. />
  6966. )}
  6967. {/* Skip Objects Modal */}
  6968. <SkipObjectsModal
  6969. printerId={printer.id}
  6970. isOpen={showSkipObjectsModal}
  6971. onClose={() => setShowSkipObjectsModal(false)}
  6972. />
  6973. {/* HMS Error Modal */}
  6974. {showHMSModal && (
  6975. <HMSErrorModal
  6976. printerName={printer.name}
  6977. errors={status?.hms_errors || []}
  6978. onClose={() => setShowHMSModal(false)}
  6979. printerId={printer.id}
  6980. hasPermission={hasPermission}
  6981. runoutGuidance={runoutGuidance}
  6982. />
  6983. )}
  6984. {/* AI failure detection modal (#1546) */}
  6985. {showAiModal && (
  6986. <AiDetectionModal
  6987. printerName={printer.name}
  6988. detection={aiDetection}
  6989. lastError={aiLastError}
  6990. onClose={() => setShowAiModal(false)}
  6991. />
  6992. )}
  6993. {/* AMS Filament Backup status / control modal (#1762) */}
  6994. {amsBackupModalOpen && status && (
  6995. <AmsBackupModal
  6996. isOpen={amsBackupModalOpen}
  6997. state={status.ams_filament_backup}
  6998. amsUnits={status.ams}
  6999. amsExtruderMap={status.ams_extruder_map}
  7000. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  7001. canToggle={hasPermission('printers:control')}
  7002. pending={setAmsBackupMutation.isPending}
  7003. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  7004. onClose={() => setAmsBackupModalOpen(false)}
  7005. />
  7006. )}
  7007. {/* AMS History Modal */}
  7008. {amsHistoryModal && (
  7009. <AMSHistoryModal
  7010. isOpen={!!amsHistoryModal}
  7011. onClose={() => setAmsHistoryModal(null)}
  7012. printerId={printer.id}
  7013. printerName={printer.name}
  7014. amsId={amsHistoryModal.amsId}
  7015. amsLabel={amsHistoryModal.amsLabel}
  7016. initialMode={amsHistoryModal.mode}
  7017. thresholds={amsThresholds}
  7018. />
  7019. )}
  7020. {/* Heater History Modal (nozzle / bed / chamber) */}
  7021. {heaterHistoryModal && (
  7022. <HeaterHistoryModal
  7023. isOpen={!!heaterHistoryModal}
  7024. onClose={() => setHeaterHistoryModal(null)}
  7025. printerId={printer.id}
  7026. printerName={printer.name}
  7027. initialKind={heaterHistoryModal.initialKind}
  7028. availableKinds={heaterHistoryModal.availableKinds}
  7029. />
  7030. )}
  7031. {/* Link Spool Modal */}
  7032. {linkSpoolModal && (
  7033. <LinkSpoolModal
  7034. isOpen={!!linkSpoolModal}
  7035. onClose={() => setLinkSpoolModal(null)}
  7036. tagUid={linkSpoolModal.tagUid}
  7037. trayUuid={linkSpoolModal.trayUuid}
  7038. printerId={linkSpoolModal.printerId}
  7039. amsId={linkSpoolModal.amsId}
  7040. trayId={linkSpoolModal.trayId}
  7041. />
  7042. )}
  7043. {/* Assign Spool Modal */}
  7044. {assignSpoolModal && (
  7045. <AssignSpoolModal
  7046. isOpen={!!assignSpoolModal}
  7047. onClose={() => setAssignSpoolModal(null)}
  7048. printerId={assignSpoolModal.printerId}
  7049. amsId={assignSpoolModal.amsId}
  7050. trayId={assignSpoolModal.trayId}
  7051. trayInfo={assignSpoolModal.trayInfo}
  7052. spoolmanEnabled={!!spoolmanEnabled}
  7053. />
  7054. )}
  7055. {/* Configure AMS Slot Modal */}
  7056. {configureSlotModal && (
  7057. <ConfigureAmsSlotModal
  7058. isOpen={!!configureSlotModal}
  7059. onClose={() => setConfigureSlotModal(null)}
  7060. printerId={printer.id}
  7061. slotInfo={configureSlotModal}
  7062. printerModel={mapModelCode(printer.model) || undefined}
  7063. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  7064. onSuccess={() => {
  7065. // Refresh slot presets to show updated profile name
  7066. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7067. // Printer status will update automatically via WebSocket when AMS data changes
  7068. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7069. }}
  7070. />
  7071. )}
  7072. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7073. {feedDirectionRequest && (
  7074. <FeedDirectionModal
  7075. slotLabel={feedDirectionRequest.slotLabel}
  7076. amsId={feedDirectionRequest.amsId}
  7077. slotId={feedDirectionRequest.slotId}
  7078. extruderSlots={status?.extruder_slots ?? {}}
  7079. isLoading={loadAmsTrayMutation.isPending}
  7080. onConfirm={(extruderId) =>
  7081. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7082. }
  7083. onCancel={() => setFeedDirectionRequest(null)}
  7084. />
  7085. )}
  7086. {/* Edit Printer Modal */}
  7087. {showEditModal && (
  7088. <EditPrinterModal
  7089. printer={printer}
  7090. onClose={() => setShowEditModal(false)}
  7091. />
  7092. )}
  7093. {/* Firmware Update Modal */}
  7094. {showFirmwareModal && firmwareInfo && (
  7095. <FirmwareUpdateModal
  7096. printer={printer}
  7097. firmwareInfo={firmwareInfo}
  7098. onClose={() => setShowFirmwareModal(false)}
  7099. />
  7100. )}
  7101. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7102. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7103. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7104. const sliderMin = 35;
  7105. const sliderMax = maxTemp + 10;
  7106. return (
  7107. <>
  7108. {/* Backdrop */}
  7109. <div
  7110. className="fixed inset-0 z-[100]"
  7111. data-testid="drying-popover-backdrop"
  7112. onMouseDown={() => {
  7113. // The click that dismisses the native datetime picker lands
  7114. // here; it must not close the popover. The input is still
  7115. // focused at mousedown, so remember that and swallow the
  7116. // matching click.
  7117. dryingBackdropSkipCloseRef.current =
  7118. dryingAtTimeInputRef.current !== null &&
  7119. document.activeElement === dryingAtTimeInputRef.current;
  7120. }}
  7121. onClick={() => {
  7122. if (dryingBackdropSkipCloseRef.current) {
  7123. dryingBackdropSkipCloseRef.current = false;
  7124. return;
  7125. }
  7126. setDryingPopoverAmsId(null);
  7127. }}
  7128. />
  7129. {/* An 'above' popover is anchored by its bottom edge (CSS
  7130. bottom) so late-appearing content grows it upward, staying on
  7131. screen and glued to the trigger. maxHeight caps to the space
  7132. on the anchored side; when the viewport is too short the body
  7133. scrolls and the footer stays pinned. dvh so iOS Safari's
  7134. bottom toolbar doesn't clip the footer. */}
  7135. <div
  7136. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7137. style={{
  7138. left: dryingPopoverPos.left,
  7139. ...(dryingPopoverPos.placement === 'above'
  7140. ? {
  7141. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7142. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7143. }
  7144. : {
  7145. top: dryingPopoverPos.top,
  7146. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7147. }),
  7148. }}
  7149. onClick={e => e.stopPropagation()}
  7150. >
  7151. {/* Header */}
  7152. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7153. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7154. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7155. </div>
  7156. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7157. {/* Body */}
  7158. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7159. {/* Filament type select */}
  7160. <div>
  7161. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7162. <ToolbarDropdown
  7163. value={dryingFilament}
  7164. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7165. onChange={fil => {
  7166. setDryingFilament(fil);
  7167. const preset = dryingPresets[fil];
  7168. if (preset) {
  7169. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7170. setDryingTemp(preset[key]);
  7171. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7172. }
  7173. }}
  7174. fullWidth
  7175. />
  7176. </div>
  7177. {/* Temperature */}
  7178. <div>
  7179. <div className="flex items-center justify-between mb-1">
  7180. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7181. <div className="flex items-center gap-1">
  7182. <NumberInput
  7183. min={45}
  7184. max={maxTemp}
  7185. value={dryingTemp}
  7186. onChange={setDryingTemp}
  7187. fallback={45}
  7188. 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"
  7189. />
  7190. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7191. </div>
  7192. </div>
  7193. <input
  7194. type="range"
  7195. min={sliderMin}
  7196. max={sliderMax}
  7197. value={dryingTemp}
  7198. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7199. className="w-full h-1 accent-bambu-green cursor-pointer"
  7200. />
  7201. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7202. <span>45°C</span>
  7203. <span>{maxTemp}°C</span>
  7204. </div>
  7205. </div>
  7206. {/* Duration */}
  7207. <div>
  7208. <div className="flex items-center justify-between mb-1">
  7209. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7210. <div className="flex items-center gap-1">
  7211. <NumberInput
  7212. min={1}
  7213. max={24}
  7214. value={dryingDuration}
  7215. onChange={setDryingDuration}
  7216. fallback={1}
  7217. 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"
  7218. />
  7219. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7220. </div>
  7221. </div>
  7222. <input
  7223. type="range"
  7224. min={1}
  7225. max={24}
  7226. value={dryingDuration}
  7227. onChange={e => setDryingDuration(Number(e.target.value))}
  7228. className="w-full h-1 accent-bambu-green cursor-pointer"
  7229. />
  7230. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7231. <span>1h</span>
  7232. <span>24h</span>
  7233. </div>
  7234. </div>
  7235. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7236. filament threaded out into the feed tube. The whole AMS
  7237. rotates as one mechanism (all 4 spools turn together), so a
  7238. single loaded slot locks the entire unit. Bambu per-tray
  7239. `state`: 9 = empty, 10 = spool present but not loaded
  7240. (rotation possible), 11 = loaded into tube (rotation impossible).
  7241. Catches both mid-print (active feed) AND idle-with-threaded-
  7242. filament — the H2D's post-print state leaves filament in the
  7243. tube but tray_now resets to 255, which a tray_now-only check
  7244. would silently miss. */}
  7245. {(() => {
  7246. const targetAms = dryingPopoverAmsId !== null
  7247. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7248. : undefined;
  7249. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7250. tray => tray.state === 11,
  7251. );
  7252. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7253. return (
  7254. <button
  7255. type="button"
  7256. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7257. aria-pressed={rotateChecked}
  7258. disabled={trayLoadedInThisAms}
  7259. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7260. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7261. rotateChecked
  7262. ? 'bg-bambu-green border-bambu-green text-white'
  7263. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7264. }`}
  7265. >
  7266. {t('printers.drying.rotateTray')}
  7267. </button>
  7268. );
  7269. })()}
  7270. {/* Start mode: now / after delay / at time (#2638) */}
  7271. <div>
  7272. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7273. <div className="grid grid-cols-3 gap-1">
  7274. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7275. <button
  7276. key={mode}
  7277. type="button"
  7278. onClick={() => setDryingStartMode(mode)}
  7279. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7280. dryingStartMode === mode
  7281. ? 'bg-bambu-green border-bambu-green text-white'
  7282. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7283. }`}
  7284. >
  7285. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7286. </button>
  7287. ))}
  7288. </div>
  7289. {dryingStartMode === 'delay' && (
  7290. // Inline chips: a dropdown menu would be clipped by
  7291. // the popover's scrollable body.
  7292. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7293. {DRYING_DELAY_OPTIONS.map(min => (
  7294. <button
  7295. key={min}
  7296. type="button"
  7297. aria-pressed={dryingDelayMinutes === min}
  7298. onClick={() => setDryingDelayMinutes(min)}
  7299. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7300. dryingDelayMinutes === min
  7301. ? 'bg-bambu-green border-bambu-green text-white'
  7302. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7303. }`}
  7304. >
  7305. {formatDurationFromHours(min / 60)}
  7306. </button>
  7307. ))}
  7308. </div>
  7309. )}
  7310. {dryingStartMode === 'at_time' && (
  7311. <input
  7312. ref={dryingAtTimeInputRef}
  7313. type="datetime-local"
  7314. data-testid="drying-start-at"
  7315. value={dryingStartAt}
  7316. onChange={e => setDryingStartAt(e.target.value)}
  7317. 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]"
  7318. />
  7319. )}
  7320. </div>
  7321. </div>
  7322. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7323. {/* Footer */}
  7324. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7325. <button
  7326. onClick={() => {
  7327. if (dryingPopoverAmsId !== null) {
  7328. // Clamp rotateTray off when any tray in this AMS is loaded into
  7329. // the tube — the rotate UI is disabled there, but the state may
  7330. // linger as `true` from a previous AMS, or a print may have
  7331. // started while the popover was open. Without this clamp the
  7332. // Start payload would carry rotate_tray=true and firmware would
  7333. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7334. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7335. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7336. tray => tray.state === 11,
  7337. );
  7338. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7339. if (dryingStartMode === 'now') {
  7340. startDryingMutation.mutate({
  7341. amsId: dryingPopoverAmsId,
  7342. temp: dryingTemp,
  7343. duration: dryingDuration,
  7344. filament: dryingFilament,
  7345. rotateTray: rotate,
  7346. });
  7347. } else {
  7348. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7349. if (startAfter) {
  7350. scheduleDryingMutation.mutate({
  7351. amsId: dryingPopoverAmsId,
  7352. temp: dryingTemp,
  7353. duration: dryingDuration,
  7354. filament: dryingFilament,
  7355. rotateTray: rotate,
  7356. startAfter,
  7357. });
  7358. }
  7359. }
  7360. }
  7361. }}
  7362. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7363. data-testid="drying-start-confirm"
  7364. 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"
  7365. >
  7366. {dryingStartMode === 'now'
  7367. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7368. : t('printers.drying.schedule')}
  7369. </button>
  7370. </div>
  7371. </div>
  7372. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7373. since the popover clips its own overflow. */}
  7374. <div
  7375. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7376. style={{
  7377. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7378. top: dryingPopoverPos.anchorY - 5,
  7379. ...(dryingPopoverPos.placement === 'above'
  7380. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7381. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7382. }}
  7383. />
  7384. </>
  7385. );
  7386. })()}
  7387. </Card>
  7388. );
  7389. }
  7390. export function AddPrinterModal({
  7391. onClose,
  7392. onAdd,
  7393. existingSerials,
  7394. }: {
  7395. onClose: () => void;
  7396. onAdd: (data: PrinterCreate) => void;
  7397. existingSerials: string[];
  7398. }) {
  7399. const { t } = useTranslation();
  7400. const [form, setForm] = useState<PrinterCreate>({
  7401. name: '',
  7402. serial_number: '',
  7403. ip_address: '',
  7404. access_code: '',
  7405. model: '',
  7406. location: '',
  7407. auto_archive: true,
  7408. });
  7409. // Discovery state
  7410. const [discovering, setDiscovering] = useState(false);
  7411. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7412. const [discoveryError, setDiscoveryError] = useState('');
  7413. const [hasScanned, setHasScanned] = useState(false);
  7414. const [isDocker, setIsDocker] = useState(false);
  7415. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7416. const [subnet, setSubnet] = useState('');
  7417. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7418. // text input so users can scan a subnet Bambuddy isn't directly on
  7419. // (printer behind a router on a different L3 segment — SSDP multicast
  7420. // won't cross that boundary, only an active unicast scan will). #1564
  7421. const [customSubnet, setCustomSubnet] = useState('');
  7422. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7423. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7424. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7425. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7426. // (not block) when checks fail, so the user doesn't add a printer that
  7427. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7428. // failed result awaiting an explicit "save anyway".
  7429. const [checkingSave, setCheckingSave] = useState(false);
  7430. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7431. // Fetch discovery info on mount + restore the last custom CIDR the user
  7432. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7433. // time they open this modal).
  7434. useEffect(() => {
  7435. discoveryApi.getInfo().then(info => {
  7436. setIsDocker(info.is_docker);
  7437. if (info.subnets.length > 0) {
  7438. setDetectedSubnets(info.subnets);
  7439. setSubnet(info.subnets[0]);
  7440. }
  7441. }).catch(() => {
  7442. // Ignore errors, assume not Docker
  7443. });
  7444. try {
  7445. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7446. if (saved) setCustomSubnet(saved);
  7447. } catch {
  7448. // localStorage unavailable (private mode, quota); recall is opportunistic
  7449. }
  7450. }, []);
  7451. // Filter out already-added printers
  7452. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7453. const handleAddSubmit = async (e: React.FormEvent) => {
  7454. e.preventDefault();
  7455. setCheckingSave(true);
  7456. try {
  7457. const result = await api.diagnoseConnection({
  7458. ip_address: form.ip_address.trim(),
  7459. serial_number: form.serial_number.trim() || undefined,
  7460. access_code: form.access_code || undefined,
  7461. });
  7462. if (result.checks.some((c) => c.status === 'fail')) {
  7463. setSaveWarning(result);
  7464. return;
  7465. }
  7466. } catch {
  7467. // Diagnostic infrastructure failed — never block the save on it.
  7468. } finally {
  7469. setCheckingSave(false);
  7470. }
  7471. onAdd(form);
  7472. };
  7473. const startDiscovery = async () => {
  7474. setDiscoveryError('');
  7475. setDiscovered([]);
  7476. setDiscovering(true);
  7477. setHasScanned(false);
  7478. setScanProgress({ scanned: 0, total: 0 });
  7479. // Native installs fall back to subnet scanning when the user picks
  7480. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7481. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7482. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7483. const wantsSubnetScan = isDocker || useCustomSubnet;
  7484. if (wantsSubnetScan && useCustomSubnet) {
  7485. try {
  7486. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7487. } catch {
  7488. // localStorage write best-effort; user just retypes next time
  7489. }
  7490. }
  7491. try {
  7492. if (wantsSubnetScan) {
  7493. await discoveryApi.startSubnetScan(scanCidr);
  7494. // Poll for scan status and results
  7495. const pollInterval = setInterval(async () => {
  7496. try {
  7497. const status = await discoveryApi.getScanStatus();
  7498. setScanProgress({ scanned: status.scanned, total: status.total });
  7499. const printers = await discoveryApi.getDiscoveredPrinters();
  7500. setDiscovered(printers);
  7501. if (!status.running) {
  7502. clearInterval(pollInterval);
  7503. setDiscovering(false);
  7504. setHasScanned(true);
  7505. }
  7506. } catch (e) {
  7507. console.error('Failed to get scan status:', e);
  7508. }
  7509. }, 500);
  7510. } else {
  7511. // Use SSDP discovery for native installs
  7512. await discoveryApi.startDiscovery(10);
  7513. // Poll for discovered printers every second
  7514. const pollInterval = setInterval(async () => {
  7515. try {
  7516. const printers = await discoveryApi.getDiscoveredPrinters();
  7517. setDiscovered(printers);
  7518. } catch (e) {
  7519. console.error('Failed to get discovered printers:', e);
  7520. }
  7521. }, 1000);
  7522. // Stop after 10 seconds
  7523. setTimeout(async () => {
  7524. clearInterval(pollInterval);
  7525. try {
  7526. await discoveryApi.stopDiscovery();
  7527. } catch {
  7528. // Ignore stop errors
  7529. }
  7530. setDiscovering(false);
  7531. setHasScanned(true);
  7532. // Final fetch
  7533. try {
  7534. const printers = await discoveryApi.getDiscoveredPrinters();
  7535. setDiscovered(printers);
  7536. } catch (e) {
  7537. console.error('Failed to get final discovered printers:', e);
  7538. }
  7539. }, 10000);
  7540. }
  7541. } catch (e) {
  7542. console.error('Failed to start discovery:', e);
  7543. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7544. setDiscovering(false);
  7545. setHasScanned(true);
  7546. }
  7547. };
  7548. // Reuse module-level mapModelCode
  7549. const selectPrinter = (printer: DiscoveredPrinter) => {
  7550. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7551. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7552. setForm({
  7553. ...form,
  7554. name: printer.name || '',
  7555. serial_number: serialNumber,
  7556. ip_address: printer.ip_address,
  7557. model: mapModelCode(printer.model),
  7558. });
  7559. // Clear discovery results after selection
  7560. setDiscovered([]);
  7561. };
  7562. // Cleanup discovery on unmount
  7563. useEffect(() => {
  7564. return () => {
  7565. discoveryApi.stopDiscovery().catch(() => {});
  7566. discoveryApi.stopSubnetScan().catch(() => {});
  7567. };
  7568. }, []);
  7569. // Close on Escape key
  7570. useEffect(() => {
  7571. const handleKeyDown = (e: KeyboardEvent) => {
  7572. if (e.key === 'Escape') onClose();
  7573. };
  7574. window.addEventListener('keydown', handleKeyDown);
  7575. return () => window.removeEventListener('keydown', handleKeyDown);
  7576. }, [onClose]);
  7577. return (
  7578. <>
  7579. <div
  7580. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7581. onClick={onClose}
  7582. >
  7583. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7584. <CardContent>
  7585. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7586. {/* Discovery Section */}
  7587. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7588. {/* Subnet picker — always visible. The dropdown lists detected
  7589. interface subnets and a "Custom..." sentinel that reveals
  7590. a CIDR text input for printers on a different L3 segment
  7591. (router, VLAN, etc.). #1564 */}
  7592. <div className="mb-3">
  7593. <label className="block text-sm text-bambu-gray mb-1">
  7594. {t('printers.discovery.subnetToScan')}
  7595. </label>
  7596. {detectedSubnets.length > 0 ? (
  7597. <select
  7598. 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"
  7599. value={useCustomSubnet ? '__custom__' : subnet}
  7600. onChange={(e) => {
  7601. if (e.target.value === '__custom__') {
  7602. setUseCustomSubnet(true);
  7603. } else {
  7604. setUseCustomSubnet(false);
  7605. setSubnet(e.target.value);
  7606. }
  7607. }}
  7608. disabled={discovering}
  7609. >
  7610. {detectedSubnets.map(s => (
  7611. <option key={s} value={s}>{s}</option>
  7612. ))}
  7613. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7614. </select>
  7615. ) : (
  7616. <input
  7617. type="text"
  7618. 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"
  7619. value={subnet}
  7620. onChange={(e) => setSubnet(e.target.value)}
  7621. placeholder="192.168.1.0/24"
  7622. disabled={discovering}
  7623. />
  7624. )}
  7625. {useCustomSubnet && (
  7626. <input
  7627. type="text"
  7628. aria-label={t('printers.discovery.customSubnetLabel')}
  7629. 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"
  7630. value={customSubnet}
  7631. onChange={(e) => setCustomSubnet(e.target.value)}
  7632. placeholder="10.1.1.0/24"
  7633. disabled={discovering}
  7634. />
  7635. )}
  7636. <p className="mt-1 text-xs text-bambu-gray">
  7637. {isDocker
  7638. ? t('printers.discovery.dockerNote')
  7639. : t('printers.discovery.customSubnetNote')}
  7640. </p>
  7641. </div>
  7642. <Button
  7643. type="button"
  7644. variant="secondary"
  7645. onClick={startDiscovery}
  7646. disabled={discovering}
  7647. className="w-full"
  7648. >
  7649. {discovering ? (
  7650. <>
  7651. <Loader2 className="w-4 h-4 animate-spin" />
  7652. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7653. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7654. : t('printers.discovery.scanning')}
  7655. </>
  7656. ) : (
  7657. <>
  7658. <Search className="w-4 h-4" />
  7659. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7660. </>
  7661. )}
  7662. </Button>
  7663. {discoveryError && (
  7664. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7665. )}
  7666. {newPrinters.length > 0 && (
  7667. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7668. {newPrinters.map((printer) => (
  7669. <div
  7670. key={printer.serial}
  7671. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7672. onClick={() => selectPrinter(printer)}
  7673. >
  7674. <div className="min-w-0 flex-1">
  7675. <p className="font-medium text-white text-sm truncate">
  7676. {printer.name || printer.serial}
  7677. </p>
  7678. <p className="text-xs text-bambu-gray truncate">
  7679. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7680. {printer.serial.startsWith('unknown-') && (
  7681. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7682. )}
  7683. </p>
  7684. </div>
  7685. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7686. </div>
  7687. ))}
  7688. </div>
  7689. )}
  7690. {discovering && (
  7691. <p className="mt-2 text-sm text-bambu-gray text-center">
  7692. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7693. </p>
  7694. )}
  7695. {hasScanned && !discovering && discovered.length === 0 && (
  7696. <p className="mt-2 text-sm text-bambu-gray text-center">
  7697. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7698. </p>
  7699. )}
  7700. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7701. <p className="mt-2 text-sm text-bambu-gray text-center">
  7702. {t('printers.discovery.allConfigured')}
  7703. </p>
  7704. )}
  7705. </div>
  7706. <form onSubmit={handleAddSubmit} className="space-y-4">
  7707. <div>
  7708. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7709. <input
  7710. type="text"
  7711. required
  7712. 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"
  7713. value={form.name}
  7714. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7715. placeholder={t('printers.modal.myPrinter')}
  7716. />
  7717. </div>
  7718. <div>
  7719. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7720. <input
  7721. type="text"
  7722. required
  7723. 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])?)*)"
  7724. 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"
  7725. value={form.ip_address}
  7726. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7727. placeholder="192.168.1.100 or printer.local"
  7728. />
  7729. </div>
  7730. <div>
  7731. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7732. <input
  7733. type="text"
  7734. required
  7735. 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"
  7736. value={form.serial_number}
  7737. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7738. placeholder="01P00A000000000"
  7739. />
  7740. </div>
  7741. <div>
  7742. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7743. <input
  7744. type="password"
  7745. required
  7746. 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"
  7747. value={form.access_code}
  7748. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7749. placeholder={t('printers.modal.fromPrinterSettings')}
  7750. />
  7751. </div>
  7752. <div>
  7753. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7754. <select
  7755. 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"
  7756. value={form.model || ''}
  7757. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7758. >
  7759. <option value="">{t('printers.modal.selectModel')}</option>
  7760. <optgroup label="A1 Series">
  7761. <option value="A1">A1</option>
  7762. <option value="A1 Mini">A1 Mini</option>
  7763. </optgroup>
  7764. <optgroup label="A2 Series">
  7765. <option value="A2L">A2L</option>
  7766. </optgroup>
  7767. <optgroup label="H2 Series">
  7768. <option value="H2C">H2C</option>
  7769. <option value="H2D">H2D</option>
  7770. <option value="H2D Pro">H2D Pro</option>
  7771. <option value="H2S">H2S</option>
  7772. </optgroup>
  7773. <optgroup label="P Series">
  7774. <option value="P1P">P1P</option>
  7775. <option value="P1S">P1S</option>
  7776. <option value="P2S">P2S</option>
  7777. </optgroup>
  7778. <optgroup label="X1 Series">
  7779. <option value="X1">X1</option>
  7780. <option value="X1C">X1 Carbon</option>
  7781. <option value="X1E">X1E</option>
  7782. </optgroup>
  7783. <optgroup label="X2 Series">
  7784. <option value="X2D">X2D</option>
  7785. </optgroup>
  7786. </select>
  7787. </div>
  7788. <div>
  7789. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7790. <input
  7791. type="text"
  7792. 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"
  7793. value={form.location || ''}
  7794. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7795. placeholder={t('printers.modal.locationPlaceholder')}
  7796. />
  7797. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7798. </div>
  7799. <div className="flex items-center gap-2">
  7800. <input
  7801. type="checkbox"
  7802. id="auto_archive"
  7803. checked={form.auto_archive}
  7804. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7805. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7806. />
  7807. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7808. {t('printers.modal.autoArchiveLabel')}
  7809. </label>
  7810. </div>
  7811. <button
  7812. type="button"
  7813. onClick={() => setShowDiagnostic(true)}
  7814. disabled={!form.ip_address.trim()}
  7815. 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"
  7816. >
  7817. <Stethoscope className="w-4 h-4" />
  7818. {t('diagnostic.runButton')}
  7819. </button>
  7820. {saveWarning ? (
  7821. <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">
  7822. <div className="flex items-start gap-2">
  7823. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7824. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7825. </div>
  7826. <DiagnosticChecklist result={saveWarning} />
  7827. <div className="flex gap-3">
  7828. <Button
  7829. type="button"
  7830. variant="secondary"
  7831. onClick={() => setSaveWarning(null)}
  7832. className="flex-1"
  7833. >
  7834. {t('printers.addPreflight.back')}
  7835. </Button>
  7836. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7837. {t('printers.addPreflight.saveAnyway')}
  7838. </Button>
  7839. </div>
  7840. </div>
  7841. ) : (
  7842. <div className="flex gap-3 pt-2">
  7843. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7844. {t('common.cancel')}
  7845. </Button>
  7846. <Button type="submit" disabled={checkingSave} className="flex-1">
  7847. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7848. </Button>
  7849. </div>
  7850. )}
  7851. </form>
  7852. </CardContent>
  7853. </Card>
  7854. </div>
  7855. {showDiagnostic && (
  7856. <ConnectionDiagnosticModal
  7857. connection={{
  7858. ip_address: form.ip_address.trim(),
  7859. serial_number: form.serial_number.trim() || undefined,
  7860. access_code: form.access_code || undefined,
  7861. }}
  7862. printerName={form.name || null}
  7863. onClose={() => setShowDiagnostic(false)}
  7864. />
  7865. )}
  7866. </>
  7867. );
  7868. }
  7869. function FirmwareUpdateModal({
  7870. printer,
  7871. firmwareInfo,
  7872. onClose,
  7873. }: {
  7874. printer: Printer;
  7875. firmwareInfo: FirmwareUpdateInfo;
  7876. onClose: () => void;
  7877. }) {
  7878. const { t } = useTranslation();
  7879. const queryClient = useQueryClient();
  7880. const { showToast } = useToast();
  7881. const { hasPermission } = useAuth();
  7882. const canUpdate = hasPermission('firmware:update');
  7883. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7884. const [isUploading, setIsUploading] = useState(false);
  7885. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7886. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7887. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7888. );
  7889. // Prepare check query — runs when a version is selected and user can update
  7890. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7891. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7892. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7893. staleTime: 30000,
  7894. enabled: !!selectedVersion && canUpdate && !isUploading,
  7895. });
  7896. // Start upload mutation
  7897. const uploadMutation = useMutation({
  7898. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7899. onSuccess: () => {
  7900. setIsUploading(true);
  7901. // Start polling for status
  7902. const interval = setInterval(async () => {
  7903. try {
  7904. const status = await firmwareApi.getUploadStatus(printer.id);
  7905. setUploadStatus(status);
  7906. if (status.status === 'complete' || status.status === 'error') {
  7907. clearInterval(interval);
  7908. setPollInterval(null);
  7909. setIsUploading(false);
  7910. if (status.status === 'complete') {
  7911. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7912. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7913. }
  7914. }
  7915. } catch {
  7916. // Ignore errors during polling
  7917. }
  7918. }, 2000);
  7919. setPollInterval(interval);
  7920. },
  7921. onError: (error: Error) => {
  7922. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7923. setIsUploading(false);
  7924. },
  7925. });
  7926. // Cleanup on unmount
  7927. useEffect(() => {
  7928. return () => {
  7929. if (pollInterval) clearInterval(pollInterval);
  7930. };
  7931. }, [pollInterval]);
  7932. const handleStartUpload = () => {
  7933. setUploadStatus(null);
  7934. uploadMutation.mutate();
  7935. };
  7936. return (
  7937. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7938. <Card className="w-full max-w-md mx-4">
  7939. <CardContent>
  7940. <div className="flex items-start gap-3 mb-4">
  7941. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7942. {firmwareInfo.update_available
  7943. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7944. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7945. </div>
  7946. <div className="flex-1">
  7947. <h3 className="text-lg font-semibold text-white">
  7948. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7949. </h3>
  7950. <p className="text-sm text-bambu-gray mt-1">
  7951. {printer.name}
  7952. </p>
  7953. </div>
  7954. </div>
  7955. {/* Version Info */}
  7956. {(() => {
  7957. const selectedEntry = selectedVersion
  7958. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7959. : null;
  7960. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7961. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7962. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7963. return (
  7964. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7965. <div className="flex justify-between items-center text-sm">
  7966. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7967. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7968. {firmwareInfo.current_version || t('common.unknown')}
  7969. </span>
  7970. </div>
  7971. {showSecondLine && (
  7972. <div className="flex justify-between items-center text-sm mt-1">
  7973. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7974. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7975. </div>
  7976. )}
  7977. {displayNotes && (
  7978. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7979. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7980. {t('printers.firmwareModal.releaseNotes')}
  7981. </summary>
  7982. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7983. {displayNotes}
  7984. </div>
  7985. </details>
  7986. )}
  7987. </div>
  7988. );
  7989. })()}
  7990. {/* Available versions list */}
  7991. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7992. <div className="mb-4">
  7993. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7994. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7995. {firmwareInfo.available_versions.map((v) => {
  7996. const isCurrent = firmwareInfo.current_version === v.version;
  7997. const isSelected = selectedVersion === v.version;
  7998. const cmp = firmwareInfo.current_version
  7999. ? compareFwVersions(v.version, firmwareInfo.current_version)
  8000. : 0;
  8001. const relLabel = isCurrent
  8002. ? t('printers.firmwareModal.currentBadge')
  8003. : cmp > 0
  8004. ? t('printers.firmwareModal.newerBadge')
  8005. : t('printers.firmwareModal.olderBadge');
  8006. const relClass = isCurrent
  8007. ? 'text-bambu-gray'
  8008. : cmp > 0
  8009. ? 'text-orange-700 dark:text-orange-400'
  8010. : 'text-blue-700 dark:text-blue-400';
  8011. return (
  8012. <button
  8013. key={v.version}
  8014. type="button"
  8015. disabled={!v.file_available || !canUpdate || isCurrent}
  8016. onClick={() => setSelectedVersion(v.version)}
  8017. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  8018. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  8019. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  8020. >
  8021. <div className="flex items-center gap-2 min-w-0">
  8022. <span className="font-mono text-white">{v.version}</span>
  8023. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  8024. </div>
  8025. <span className={`text-xs px-2 py-0.5 rounded-full ${
  8026. isCurrent
  8027. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  8028. : v.file_available
  8029. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  8030. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  8031. }`}>
  8032. {isCurrent
  8033. ? t('printers.firmwareModal.installed')
  8034. : v.file_available
  8035. ? t('printers.firmwareModal.usable')
  8036. : t('printers.firmwareModal.unavailable')}
  8037. </span>
  8038. </button>
  8039. );
  8040. })}
  8041. </div>
  8042. </div>
  8043. )}
  8044. {/* Status / Progress (only when a version is selected) */}
  8045. {!selectedVersion ? null : isPreparing ? (
  8046. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  8047. <Loader2 className="w-4 h-4 animate-spin" />
  8048. {t('printers.firmwareModal.checkingPrereqs')}
  8049. </div>
  8050. ) : prepareInfo && !isUploading && !uploadStatus ? (
  8051. <div className="mb-4">
  8052. {prepareInfo.can_proceed ? (
  8053. <div className="flex items-center gap-2 text-bambu-green text-sm">
  8054. <Box className="w-4 h-4" />
  8055. {t('printers.firmwareModal.sdCardReady')}
  8056. </div>
  8057. ) : (
  8058. <div className="space-y-1">
  8059. {prepareInfo.errors.map((error, i) => (
  8060. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  8061. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  8062. {error}
  8063. </div>
  8064. ))}
  8065. </div>
  8066. )}
  8067. </div>
  8068. ) : null}
  8069. {/* Upload Progress */}
  8070. {(isUploading || uploadStatus) && uploadStatus && (
  8071. <div className="mb-4">
  8072. <div className="flex items-center justify-between text-sm mb-1">
  8073. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8074. <span className="text-white">{uploadStatus.progress}%</span>
  8075. </div>
  8076. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8077. <div
  8078. className={`h-2 rounded-full transition-all ${
  8079. uploadStatus.status === 'error' ? 'bg-status-error' :
  8080. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8081. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8082. style={{ width: `${uploadStatus.progress}%` }}
  8083. />
  8084. </div>
  8085. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8086. {uploadStatus.error && (
  8087. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8088. )}
  8089. </div>
  8090. )}
  8091. {/* Success Message */}
  8092. {uploadStatus?.status === 'complete' && (
  8093. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8094. <p className="text-sm text-bambu-green font-medium mb-2">
  8095. {t('printers.firmwareModal.uploadedSuccess')}
  8096. </p>
  8097. <p className="text-xs text-bambu-gray">
  8098. {t('printers.firmwareModal.applyInstructions')}
  8099. </p>
  8100. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8101. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8102. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8103. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8104. <li>{t('printers.firmwareModal.step4')}</li>
  8105. </ol>
  8106. </div>
  8107. )}
  8108. {/* Buttons */}
  8109. <div className="flex gap-2 justify-end">
  8110. <Button variant="secondary" onClick={onClose}>
  8111. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8112. </Button>
  8113. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8114. <Button
  8115. onClick={handleStartUpload}
  8116. disabled={uploadMutation.isPending}
  8117. >
  8118. {uploadMutation.isPending ? (
  8119. <>
  8120. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8121. {t('printers.firmwareModal.starting')}
  8122. </>
  8123. ) : (
  8124. <>
  8125. <Download className="w-4 h-4 mr-2" />
  8126. {t('printers.firmwareModal.uploadFirmware')}
  8127. </>
  8128. )}
  8129. </Button>
  8130. )}
  8131. </div>
  8132. </CardContent>
  8133. </Card>
  8134. </div>
  8135. );
  8136. }
  8137. function EditPrinterModal({
  8138. printer,
  8139. onClose,
  8140. }: {
  8141. printer: Printer;
  8142. onClose: () => void;
  8143. }) {
  8144. const { t } = useTranslation();
  8145. const queryClient = useQueryClient();
  8146. const { showToast } = useToast();
  8147. const [form, setForm] = useState({
  8148. name: printer.name,
  8149. ip_address: printer.ip_address,
  8150. access_code: '',
  8151. model: printer.model || '',
  8152. location: printer.location || '',
  8153. auto_archive: printer.auto_archive,
  8154. is_active: printer.is_active,
  8155. });
  8156. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8157. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8158. const [checkingSave, setCheckingSave] = useState(false);
  8159. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8160. const updateMutation = useMutation({
  8161. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8162. onSuccess: () => {
  8163. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8164. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8165. onClose();
  8166. },
  8167. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8168. });
  8169. // Close on Escape key
  8170. useEffect(() => {
  8171. const handleKeyDown = (e: KeyboardEvent) => {
  8172. if (e.key === 'Escape') onClose();
  8173. };
  8174. window.addEventListener('keydown', handleKeyDown);
  8175. return () => window.removeEventListener('keydown', handleKeyDown);
  8176. }, [onClose]);
  8177. const doSave = () => {
  8178. const data: Partial<PrinterCreate> = {
  8179. name: form.name,
  8180. ip_address: form.ip_address,
  8181. model: form.model || undefined,
  8182. location: form.location || undefined,
  8183. auto_archive: form.auto_archive,
  8184. is_active: form.is_active,
  8185. };
  8186. // Only include access_code if it was changed
  8187. if (form.access_code) {
  8188. data.access_code = form.access_code;
  8189. }
  8190. updateMutation.mutate(data);
  8191. };
  8192. const handleSubmit = async (e: React.FormEvent) => {
  8193. e.preventDefault();
  8194. setCheckingSave(true);
  8195. try {
  8196. const result = await api.diagnoseConnection({
  8197. ip_address: form.ip_address.trim(),
  8198. serial_number: printer.serial_number,
  8199. access_code: form.access_code || undefined,
  8200. });
  8201. if (result.checks.some((c) => c.status === 'fail')) {
  8202. setSaveWarning(result);
  8203. return;
  8204. }
  8205. } catch {
  8206. // Diagnostic infrastructure failed — never block the save on it.
  8207. } finally {
  8208. setCheckingSave(false);
  8209. }
  8210. doSave();
  8211. };
  8212. return (
  8213. <div
  8214. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8215. onClick={onClose}
  8216. >
  8217. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8218. <CardContent>
  8219. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8220. <form onSubmit={handleSubmit} className="space-y-4">
  8221. <div>
  8222. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8223. <input
  8224. type="text"
  8225. required
  8226. 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"
  8227. value={form.name}
  8228. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8229. placeholder={t('printers.modal.myPrinter')}
  8230. />
  8231. </div>
  8232. <div>
  8233. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8234. <input
  8235. type="text"
  8236. required
  8237. 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])?)*)"
  8238. 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"
  8239. value={form.ip_address}
  8240. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8241. placeholder="192.168.1.100 or printer.local"
  8242. />
  8243. </div>
  8244. <div>
  8245. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8246. <input
  8247. type="text"
  8248. disabled
  8249. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8250. value={printer.serial_number}
  8251. />
  8252. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8253. </div>
  8254. <div>
  8255. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8256. <input
  8257. type="password"
  8258. 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"
  8259. value={form.access_code}
  8260. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8261. placeholder={t('printers.accessCodePlaceholder')}
  8262. />
  8263. </div>
  8264. <div>
  8265. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8266. <select
  8267. 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"
  8268. value={form.model}
  8269. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8270. >
  8271. <option value="">{t('printers.modal.selectModel')}</option>
  8272. <optgroup label="A1 Series">
  8273. <option value="A1">A1</option>
  8274. <option value="A1 Mini">A1 Mini</option>
  8275. </optgroup>
  8276. <optgroup label="A2 Series">
  8277. <option value="A2L">A2L</option>
  8278. </optgroup>
  8279. <optgroup label="H2 Series">
  8280. <option value="H2C">H2C</option>
  8281. <option value="H2D">H2D</option>
  8282. <option value="H2D Pro">H2D Pro</option>
  8283. <option value="H2S">H2S</option>
  8284. </optgroup>
  8285. <optgroup label="P Series">
  8286. <option value="P1P">P1P</option>
  8287. <option value="P1S">P1S</option>
  8288. <option value="P2S">P2S</option>
  8289. </optgroup>
  8290. <optgroup label="X1 Series">
  8291. <option value="X1">X1</option>
  8292. <option value="X1C">X1 Carbon</option>
  8293. <option value="X1E">X1E</option>
  8294. </optgroup>
  8295. <optgroup label="X2 Series">
  8296. <option value="X2D">X2D</option>
  8297. </optgroup>
  8298. </select>
  8299. </div>
  8300. <div>
  8301. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8302. <input
  8303. type="text"
  8304. 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"
  8305. value={form.location}
  8306. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8307. placeholder={t('printers.modal.locationPlaceholder')}
  8308. />
  8309. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8310. </div>
  8311. <div className="flex items-center gap-2">
  8312. <input
  8313. type="checkbox"
  8314. id="edit_auto_archive"
  8315. checked={form.auto_archive}
  8316. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8317. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8318. />
  8319. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8320. {t('printers.modal.autoArchiveLabel')}
  8321. </label>
  8322. </div>
  8323. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8324. is_active because the user-facing concept is "is this printer
  8325. in maintenance" not "is it active". */}
  8326. <div>
  8327. <div className="flex items-center gap-2">
  8328. <input
  8329. type="checkbox"
  8330. id="edit_maintenance_mode"
  8331. checked={!form.is_active}
  8332. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8333. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8334. />
  8335. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8336. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8337. {t('printers.maintenance.editFieldLabel')}
  8338. </label>
  8339. </div>
  8340. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8341. {t('printers.maintenance.editFieldHelp')}
  8342. </p>
  8343. </div>
  8344. {saveWarning ? (
  8345. <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">
  8346. <div className="flex items-start gap-2">
  8347. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8348. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8349. </div>
  8350. <DiagnosticChecklist result={saveWarning} />
  8351. <div className="flex gap-3">
  8352. <Button
  8353. type="button"
  8354. variant="secondary"
  8355. onClick={() => setSaveWarning(null)}
  8356. className="flex-1"
  8357. >
  8358. {t('printers.addPreflight.back')}
  8359. </Button>
  8360. <Button
  8361. type="button"
  8362. onClick={doSave}
  8363. className="flex-1"
  8364. disabled={updateMutation.isPending}
  8365. >
  8366. {t('printers.addPreflight.saveAnyway')}
  8367. </Button>
  8368. </div>
  8369. </div>
  8370. ) : (
  8371. <div className="flex gap-3 pt-4">
  8372. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8373. {t('common.cancel')}
  8374. </Button>
  8375. <Button
  8376. type="submit"
  8377. className="flex-1"
  8378. disabled={updateMutation.isPending || checkingSave}
  8379. >
  8380. {checkingSave
  8381. ? t('printers.addPreflight.checking')
  8382. : updateMutation.isPending
  8383. ? t('common.saving')
  8384. : t('printers.modal.saveChanges')}
  8385. </Button>
  8386. </div>
  8387. )}
  8388. </form>
  8389. </CardContent>
  8390. </Card>
  8391. </div>
  8392. );
  8393. }
  8394. // Component to check if a printer is offline (for power dropdown)
  8395. function usePrinterOfflineStatus(printerId: number) {
  8396. const { data: status } = useQuery({
  8397. queryKey: ['printerStatus', printerId],
  8398. queryFn: () => api.getPrinterStatus(printerId),
  8399. refetchInterval: 30000,
  8400. });
  8401. return !status?.connected;
  8402. }
  8403. // Power dropdown item for an offline printer
  8404. function PowerDropdownItem({
  8405. printer,
  8406. plug,
  8407. onPowerOn,
  8408. isPowering,
  8409. }: {
  8410. printer: Printer;
  8411. plug: { id: number; name: string };
  8412. onPowerOn: (plugId: number) => void;
  8413. isPowering: boolean;
  8414. }) {
  8415. const isOffline = usePrinterOfflineStatus(printer.id);
  8416. // Fetch plug status
  8417. const { data: plugStatus } = useQuery({
  8418. queryKey: ['smartPlugStatus', plug.id],
  8419. queryFn: () => api.getSmartPlugStatus(plug.id),
  8420. refetchInterval: 10000,
  8421. });
  8422. // Only show if printer is offline
  8423. if (!isOffline) {
  8424. return null;
  8425. }
  8426. return (
  8427. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8428. <div className="flex items-center gap-2 min-w-0">
  8429. <span className="text-sm text-white truncate">{printer.name}</span>
  8430. {plugStatus && (
  8431. <span
  8432. className={`text-xs px-1.5 py-0.5 rounded ${
  8433. plugStatus.state === 'ON'
  8434. ? 'bg-bambu-green/20 text-bambu-green'
  8435. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8436. }`}
  8437. >
  8438. {plugStatus.state || '?'}
  8439. </span>
  8440. )}
  8441. </div>
  8442. <button
  8443. onClick={() => onPowerOn(plug.id)}
  8444. disabled={isPowering || plugStatus?.state === 'ON'}
  8445. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8446. plugStatus?.state === 'ON'
  8447. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8448. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8449. }`}
  8450. >
  8451. <Power className="w-3 h-3" />
  8452. {isPowering ? '...' : 'On'}
  8453. </button>
  8454. </div>
  8455. );
  8456. }
  8457. export function PrintersPage() {
  8458. const { t } = useTranslation();
  8459. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8460. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8461. const accentButtonClass = {
  8462. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8463. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8464. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8465. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8466. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8467. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8468. }[activeAccent];
  8469. const [showAddModal, setShowAddModal] = useState(false);
  8470. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8471. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8472. });
  8473. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8474. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8475. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8476. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8477. });
  8478. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8479. return localStorage.getItem('printerSortAsc') !== 'false';
  8480. });
  8481. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8482. const [cardSize, setCardSize] = useState<number>(() => {
  8483. const saved = localStorage.getItem('printerCardSize');
  8484. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8485. });
  8486. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8487. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8488. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8489. });
  8490. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8491. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8492. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8493. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8494. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8495. });
  8496. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8497. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8498. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8499. });
  8500. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8501. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8502. // Defaulting to 'full' because the cards already show this info — users who
  8503. // pick cam-wall view still want to glance the same details without flipping.
  8504. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8505. const saved = localStorage.getItem('camWallStatusMode');
  8506. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8507. });
  8508. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8509. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8510. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8511. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8512. requestAnimationFrame(() => {
  8513. requestAnimationFrame(() => {
  8514. const card = document.getElementById(`printer-card-${printerId}`);
  8515. if (!card) return;
  8516. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8517. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8518. window.scrollTo({
  8519. top: Math.max(0, top),
  8520. behavior: 'smooth',
  8521. });
  8522. });
  8523. });
  8524. }, []);
  8525. const openCompactCard = useCallback((printerId: number) => {
  8526. setCompactDrilldownPrinterId(printerId);
  8527. setCardSize(2);
  8528. localStorage.setItem('printerCardSize', '2');
  8529. scrollPrinterIntoView(printerId);
  8530. }, [scrollPrinterIntoView]);
  8531. const returnToCompactCards = useCallback(() => {
  8532. const printerId = compactDrilldownPrinterId;
  8533. setCompactDrilldownPrinterId(null);
  8534. setCardSize(1);
  8535. localStorage.setItem('printerCardSize', '1');
  8536. if (printerId != null) {
  8537. scrollPrinterIntoView(printerId);
  8538. }
  8539. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8540. const [search, setSearch] = useState('');
  8541. // Both filters persist like every other preference on this page (#2833).
  8542. // `search` deliberately does not: a box that silently refills itself on
  8543. // return is more surprising than a dropdown that remembers.
  8544. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8545. // Validated on read: a value the dropdown no longer offers would filter
  8546. // every printer out, and nothing would explain why.
  8547. const saved = localStorage.getItem('printerStatusFilter');
  8548. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8549. });
  8550. const [locationFilter, setLocationFilter] = useState<string>(
  8551. () => localStorage.getItem('printerLocationFilter') || 'all'
  8552. );
  8553. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8554. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8555. try {
  8556. const saved = localStorage.getItem('printerCollapsedSections');
  8557. return saved ? JSON.parse(saved) : {};
  8558. } catch { return {}; }
  8559. });
  8560. const queryClient = useQueryClient();
  8561. const { showToast } = useToast();
  8562. const { hasPermission } = useAuth();
  8563. // Which way the camera buttons open a stream. Chosen per click from the
  8564. // button's own menu; null until this browser has made a choice, so the
  8565. // stored setting below can act as the default a fresh browser starts from.
  8566. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8567. () => readStoredCameraViewMode()
  8568. );
  8569. // Embedded camera viewer state - supports multiple simultaneous viewers
  8570. // Persisted to localStorage so cameras reopen after navigation
  8571. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8572. const saved = localStorage.getItem('openEmbeddedCameras');
  8573. if (saved) {
  8574. try {
  8575. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8576. return new Map(cameras.map(c => [c.id, c]));
  8577. } catch {
  8578. return new Map();
  8579. }
  8580. }
  8581. return new Map();
  8582. });
  8583. // Persist open cameras to localStorage when they change
  8584. useEffect(() => {
  8585. const cameras = Array.from(embeddedCameraPrinters.values());
  8586. if (cameras.length > 0) {
  8587. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8588. } else {
  8589. localStorage.removeItem('openEmbeddedCameras');
  8590. }
  8591. }, [embeddedCameraPrinters]);
  8592. const { data: printers, isLoading } = useQuery({
  8593. queryKey: ['printers'],
  8594. queryFn: api.getPrinters,
  8595. });
  8596. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8597. // so users with printers:read but no settings:read still get the values needed
  8598. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8599. const { data: settings } = useQuery({
  8600. queryKey: ['ui-preferences'],
  8601. queryFn: api.getUiPreferences,
  8602. });
  8603. // Parse user-configured temperature/fan presets once, with defensive fallback
  8604. // to built-in defaults on parse failure (validators on the backend already
  8605. // reject malformed writes, so this is just forward-compat).
  8606. const effectiveNozzleTempPresets = useMemo(
  8607. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8608. [settings?.nozzle_temp_presets],
  8609. );
  8610. const effectiveBedTempPresets = useMemo(
  8611. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8612. [settings?.bed_temp_presets],
  8613. );
  8614. const effectiveChamberTempPresets = useMemo(
  8615. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8616. [settings?.chamber_temp_presets],
  8617. );
  8618. const effectiveFanSpeedPresets = useMemo(
  8619. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8620. [settings?.fan_speed_presets],
  8621. );
  8622. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8623. const effectiveDryingPresets = useMemo(() => {
  8624. if (settings?.drying_presets) {
  8625. try {
  8626. const userPresets = JSON.parse(settings.drying_presets);
  8627. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8628. return { ...DRYING_PRESETS, ...userPresets };
  8629. }
  8630. } catch { /* ignore parse errors, use defaults */ }
  8631. }
  8632. return DRYING_PRESETS;
  8633. }, [settings?.drying_presets]);
  8634. // The local choice wins over the stored one: someone without settings:update
  8635. // cannot write their pick back, and a preference that silently reverted on
  8636. // the next render would be worse than none at all.
  8637. const cameraViewMode: CameraViewMode =
  8638. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8639. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8640. storeCameraViewMode(mode);
  8641. setChosenCameraViewMode(mode);
  8642. // Best effort, and only a default for other browsers -- the choice is
  8643. // already in effect here. Users below settings:update simply keep theirs
  8644. // locally, which is why the failure is logged rather than surfaced.
  8645. if (hasPermission('settings:update')) {
  8646. api.updateSettings({ camera_view_mode: mode })
  8647. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8648. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8649. }
  8650. }, [hasPermission, queryClient]);
  8651. // Fetch all smart plugs to know which printers have them
  8652. const { data: smartPlugs } = useQuery({
  8653. queryKey: ['smart-plugs'],
  8654. queryFn: api.getSmartPlugs,
  8655. });
  8656. // Fetch maintenance overview for all printers to show badges
  8657. const { data: maintenanceOverview } = useQuery({
  8658. queryKey: ['maintenanceOverview'],
  8659. queryFn: api.getMaintenanceOverview,
  8660. staleTime: 60 * 1000, // 1 minute
  8661. });
  8662. // Live AI failure detection state for the card badges (#1546). Matches the
  8663. // 10s refetch of the Failure Detection settings panel.
  8664. const { data: obicoPrinterStatus } = useQuery({
  8665. queryKey: ['obico-printer-status'],
  8666. queryFn: api.getObicoPrinterStatus,
  8667. refetchInterval: 10000,
  8668. });
  8669. // Badge visibility: detection enabled AND this printer in the monitored set
  8670. // (monitored_printers null = all). Live per-print state is passed separately.
  8671. const isAiMonitored = useCallback(
  8672. (printerId: number) =>
  8673. obicoPrinterStatus?.enabled === true &&
  8674. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8675. [obicoPrinterStatus],
  8676. );
  8677. // Fetch Spoolman status to enable link spool feature
  8678. const { data: spoolmanStatus } = useQuery({
  8679. queryKey: ['spoolman-status'],
  8680. queryFn: api.getSpoolmanStatus,
  8681. staleTime: 60 * 1000, // 1 minute
  8682. });
  8683. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8684. // Fetch Spoolman settings to get sync mode
  8685. const { data: spoolmanSettings } = useQuery({
  8686. queryKey: ['spoolman-settings'],
  8687. queryFn: api.getSpoolmanSettings,
  8688. enabled: !!spoolmanEnabled,
  8689. staleTime: 60 * 1000, // 1 minute
  8690. });
  8691. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8692. // Fetch unlinked spools to know if link button should be enabled
  8693. const { data: unlinkedSpools } = useQuery({
  8694. queryKey: ['unlinked-spools'],
  8695. queryFn: api.getUnlinkedSpools,
  8696. enabled: !!spoolmanEnabled,
  8697. staleTime: 30 * 1000, // 30 seconds
  8698. });
  8699. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8700. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8701. const { data: linkedSpoolsData } = useQuery({
  8702. queryKey: ['linked-spools'],
  8703. queryFn: api.getLinkedSpools,
  8704. enabled: !!spoolmanEnabled,
  8705. staleTime: 30 * 1000, // 30 seconds
  8706. });
  8707. const linkedSpools = linkedSpoolsData?.linked;
  8708. // Fetch spool assignments for inventory feature
  8709. const { data: spoolAssignments } = useQuery({
  8710. queryKey: ['spool-assignments'],
  8711. queryFn: () => api.getAssignments(),
  8712. enabled: hasPermission('inventory:view_assignments'),
  8713. staleTime: 30 * 1000,
  8714. });
  8715. const unassignMutation = useMutation({
  8716. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8717. api.unassignSpool(printerId, amsId, trayId),
  8718. onSuccess: () => {
  8719. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8720. },
  8721. });
  8722. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8723. queryKey: ['spoolman-inventory-spools'],
  8724. queryFn: () => api.getSpoolmanInventorySpools(false),
  8725. enabled: !!spoolmanEnabled,
  8726. staleTime: 30 * 1000,
  8727. });
  8728. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8729. queryKey: ['spoolman-slot-assignments'],
  8730. queryFn: () => api.getSpoolmanSlotAssignments(),
  8731. enabled: !!spoolmanEnabled,
  8732. staleTime: 30 * 1000,
  8733. });
  8734. const unassignSpoolmanMutation = useMutation({
  8735. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8736. onSuccess: () => {
  8737. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8738. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8739. },
  8740. });
  8741. // Helper to find assignment for a specific slot
  8742. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8743. return spoolAssignments?.find(
  8744. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8745. );
  8746. };
  8747. // Create a map of printer_id -> maintenance info for quick lookup
  8748. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8749. (acc, overview) => {
  8750. acc[overview.printer_id] = {
  8751. due_count: overview.due_count,
  8752. warning_count: overview.warning_count,
  8753. total_print_hours: overview.total_print_hours,
  8754. };
  8755. return acc;
  8756. },
  8757. {} as Record<number, PrinterMaintenanceInfo>
  8758. ) || {};
  8759. // Create a map of printer_id -> smart plug
  8760. const smartPlugByPrinter = smartPlugs?.reduce(
  8761. (acc, plug) => {
  8762. if (plug.printer_id) {
  8763. acc[plug.printer_id] = plug;
  8764. }
  8765. return acc;
  8766. },
  8767. {} as Record<number, typeof smartPlugs[0]>
  8768. ) || {};
  8769. const addMutation = useMutation({
  8770. mutationFn: api.createPrinter,
  8771. onSuccess: () => {
  8772. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8773. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8774. setShowAddModal(false);
  8775. },
  8776. onError: (error: Error) => {
  8777. // Localized message when the backend returns a stable error code;
  8778. // the raw message is an English fallback for non-UI clients.
  8779. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8780. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8781. return;
  8782. }
  8783. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8784. },
  8785. });
  8786. const powerOnMutation = useMutation({
  8787. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8788. onSuccess: () => {
  8789. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8790. setPoweringOn(null);
  8791. },
  8792. onError: () => {
  8793. setPoweringOn(null);
  8794. },
  8795. });
  8796. // Bulk selection state
  8797. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8798. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8799. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8800. const [bulkActionPending, setBulkActionPending] = useState(false);
  8801. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8802. const toggleSelect = useCallback((id: number) => {
  8803. setSelectedPrinterIds(prev => {
  8804. const next = new Set(prev);
  8805. if (next.has(id)) next.delete(id);
  8806. else next.add(id);
  8807. return next;
  8808. });
  8809. }, []);
  8810. const clearSelection = useCallback(() => {
  8811. setSelectedPrinterIds(new Set());
  8812. setIsSelectionMode(false);
  8813. }, []);
  8814. // Escape key exits selection mode
  8815. useEffect(() => {
  8816. const handleKeyDown = (e: KeyboardEvent) => {
  8817. if (e.key === 'Escape' && selectionMode) {
  8818. clearSelection();
  8819. }
  8820. };
  8821. window.addEventListener('keydown', handleKeyDown);
  8822. return () => window.removeEventListener('keydown', handleKeyDown);
  8823. }, [selectionMode, clearSelection]);
  8824. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8825. setBulkActionPending(true);
  8826. const ids = Array.from(selectedPrinterIds);
  8827. // Filter to only applicable printers based on cached state
  8828. const applicableIds = ids.filter(id => {
  8829. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8830. // clearPlate is checked before the connection filter: it only releases a
  8831. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8832. // down — every other action here needs to reach the machine (#2864).
  8833. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8834. if (!status?.connected) return false;
  8835. switch (action) {
  8836. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8837. case 'pause': return status.state === 'RUNNING';
  8838. case 'resume': return status.state === 'PAUSE';
  8839. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8840. default: return false;
  8841. }
  8842. });
  8843. if (applicableIds.length === 0) {
  8844. showToast(t('printers.bulk.noneApplicable'), 'error');
  8845. setBulkActionPending(false);
  8846. setBulkConfirmAction(null);
  8847. return;
  8848. }
  8849. const apiCall = {
  8850. stop: api.stopPrint,
  8851. pause: api.pausePrint,
  8852. resume: api.resumePrint,
  8853. clearPlate: api.clearPlate,
  8854. clearHMS: api.clearHMSErrors,
  8855. }[action];
  8856. const results = await Promise.allSettled(
  8857. applicableIds.map(id => apiCall(id))
  8858. );
  8859. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8860. const failed = results.filter(r => r.status === 'rejected').length;
  8861. if (failed === 0) {
  8862. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8863. } else {
  8864. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8865. }
  8866. // Invalidate status queries for affected printers
  8867. applicableIds.forEach(id => {
  8868. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8869. });
  8870. setBulkActionPending(false);
  8871. setBulkConfirmAction(null);
  8872. }, [selectedPrinterIds, queryClient, showToast, t]);
  8873. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8874. // Actions that need confirmation
  8875. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8876. setBulkConfirmAction(action);
  8877. } else {
  8878. executeBulkAction(action);
  8879. }
  8880. }, [executeBulkAction]);
  8881. const toggleHideDisconnected = () => {
  8882. const newValue = !hideDisconnected;
  8883. setHideDisconnected(newValue);
  8884. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8885. };
  8886. const handleSortChange = (newSort: SortOption) => {
  8887. setSortBy(newSort);
  8888. localStorage.setItem('printerSortBy', newSort);
  8889. };
  8890. const handleStatusFilterChange = (value: string) => {
  8891. setStatusFilter(value);
  8892. localStorage.setItem('printerStatusFilter', value);
  8893. };
  8894. const handleLocationFilterChange = (value: string) => {
  8895. setLocationFilter(value);
  8896. localStorage.setItem('printerLocationFilter', value);
  8897. };
  8898. const toggleSortDirection = () => {
  8899. const newAsc = !sortAsc;
  8900. setSortAsc(newAsc);
  8901. localStorage.setItem('printerSortAsc', String(newAsc));
  8902. };
  8903. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8904. const getGridClasses = () => {
  8905. switch (cardSize) {
  8906. 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
  8907. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8908. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8909. case 4: return 'grid-cols-1'; // XL: single column, full width
  8910. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8911. }
  8912. };
  8913. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8914. // Increment version counter whenever a printer status cache entry is updated so
  8915. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8916. useEffect(() => {
  8917. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8918. if (
  8919. event.type === 'updated' &&
  8920. Array.isArray(event.query.queryKey) &&
  8921. event.query.queryKey[0] === 'printerStatus'
  8922. ) {
  8923. setStatusCacheVersion(v => v + 1);
  8924. }
  8925. });
  8926. return unsubscribe;
  8927. }, [queryClient]);
  8928. // Filter printers by search term, status, and location
  8929. const filteredPrinters = useMemo(() => {
  8930. if (!printers) return [];
  8931. let result = printers;
  8932. // Text search
  8933. if (search.trim()) {
  8934. const q = search.trim().toLowerCase();
  8935. result = result.filter(p =>
  8936. p.name.toLowerCase().includes(q) ||
  8937. (p.model || '').toLowerCase().includes(q) ||
  8938. (p.location || '').toLowerCase().includes(q) ||
  8939. (p.serial_number || '').toLowerCase().includes(q)
  8940. );
  8941. }
  8942. // Location filter
  8943. if (locationFilter !== 'all') {
  8944. result = result.filter(p => (p.location || '') === locationFilter);
  8945. }
  8946. // Status filter
  8947. if (statusFilter !== 'all') {
  8948. result = result.filter(p => {
  8949. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8950. if (!status?.connected) return statusFilter === 'offline';
  8951. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8952. switch (statusFilter) {
  8953. case 'printing': return status.state === 'RUNNING';
  8954. case 'paused': return status.state === 'PAUSE';
  8955. case 'finished': return status.state === 'FINISH';
  8956. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8957. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8958. case 'offline': return false; // Connected printers are never offline
  8959. default: return true;
  8960. }
  8961. });
  8962. }
  8963. return result;
  8964. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8965. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8966. // Derive unique locations for the location filter dropdown
  8967. const availableLocations = useMemo(() => {
  8968. if (!printers) return [];
  8969. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8970. }, [printers]);
  8971. // A saved location can outlive what it matched -- renamed, cleared, or the
  8972. // only printer that had it deleted. The dropdown is rendered only while some
  8973. // printer has a location, so a stale one would hide every printer *and* the
  8974. // control to undo it, leaving an empty page and no way back (#2833).
  8975. // Deliberately waits for `printers`: it is undefined while the query is in
  8976. // flight, and acting on the empty list that produces would throw the saved
  8977. // filter away every time the page loads.
  8978. useEffect(() => {
  8979. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8980. setLocationFilter('all');
  8981. localStorage.setItem('printerLocationFilter', 'all');
  8982. }, [printers, availableLocations, locationFilter]);
  8983. // Sort printers based on selected option
  8984. const sortedPrinters = useMemo(() => {
  8985. const sorted = [...filteredPrinters];
  8986. switch (sortBy) {
  8987. case 'name':
  8988. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8989. break;
  8990. case 'model':
  8991. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8992. break;
  8993. case 'location':
  8994. // Sort by location, with ungrouped printers last
  8995. sorted.sort((a, b) => {
  8996. const locA = a.location || '';
  8997. const locB = b.location || '';
  8998. if (!locA && locB) return 1;
  8999. if (locA && !locB) return -1;
  9000. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  9001. });
  9002. break;
  9003. case 'status':
  9004. // Sort by status: HMS errors > printing > idle > offline
  9005. sorted.sort((a, b) => {
  9006. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  9007. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  9008. const getPriority = (s: typeof statusA) => {
  9009. if (!s?.connected) return 3; // offline
  9010. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  9011. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  9012. if (s.state === 'RUNNING') return 1; // printing
  9013. return 2; // idle
  9014. };
  9015. return getPriority(statusA) - getPriority(statusB);
  9016. });
  9017. break;
  9018. case 'eta':
  9019. sorted.sort((a, b) => {
  9020. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  9021. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  9022. const tier = (s: typeof statusA) => {
  9023. if (!s?.connected) return 3; // offline last
  9024. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  9025. if (s.state === 'RUNNING') return 1; // printing without ETA
  9026. return 2; // idle
  9027. };
  9028. const ta = tier(statusA);
  9029. const tb = tier(statusB);
  9030. if (ta !== tb) return ta - tb;
  9031. if (ta === 0) {
  9032. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  9033. if (diff !== 0) return diff;
  9034. }
  9035. return a.name.localeCompare(b.name);
  9036. });
  9037. break;
  9038. }
  9039. // Apply ascending/descending
  9040. if (!sortAsc) {
  9041. sorted.reverse();
  9042. }
  9043. return sorted;
  9044. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  9045. const selectAll = useCallback(() => {
  9046. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  9047. setIsSelectionMode(true);
  9048. }, [sortedPrinters]);
  9049. const selectByState = useCallback((state: PrinterState) => {
  9050. setSelectedPrinterIds(prev => {
  9051. const next = new Set(prev);
  9052. sortedPrinters.forEach(p => {
  9053. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  9054. if (classifyPrinterStatus(status) === state) next.add(p.id);
  9055. });
  9056. return next;
  9057. });
  9058. setIsSelectionMode(true);
  9059. }, [sortedPrinters, queryClient]);
  9060. const selectByLocation = useCallback((location: string) => {
  9061. setSelectedPrinterIds(prev => {
  9062. const next = new Set(prev);
  9063. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9064. return next;
  9065. });
  9066. setIsSelectionMode(true);
  9067. }, [sortedPrinters]);
  9068. const selectByModel = useCallback((model: string) => {
  9069. setSelectedPrinterIds(prev => {
  9070. const next = new Set(prev);
  9071. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9072. return next;
  9073. });
  9074. setIsSelectionMode(true);
  9075. }, [sortedPrinters]);
  9076. const toggleSectionCollapse = useCallback((key: string) => {
  9077. setCollapsedSections(prev => {
  9078. const next = { ...prev, [key]: !prev[key] };
  9079. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9080. return next;
  9081. });
  9082. }, []);
  9083. // Group printers when sorted by location, status, or model
  9084. const groupedPrinters = useMemo(() => {
  9085. if (sortBy === 'name' || sortBy === 'eta') return null;
  9086. const groups: Record<string, typeof sortedPrinters> = {};
  9087. if (sortBy === 'location') {
  9088. sortedPrinters.forEach(printer => {
  9089. const location = printer.location || 'Ungrouped';
  9090. if (!groups[location]) groups[location] = [];
  9091. groups[location].push(printer);
  9092. });
  9093. } else if (sortBy === 'model') {
  9094. sortedPrinters.forEach(printer => {
  9095. const model = printer.model || 'Unknown';
  9096. if (!groups[model]) groups[model] = [];
  9097. groups[model].push(printer);
  9098. });
  9099. } else if (sortBy === 'status') {
  9100. sortedPrinters.forEach(printer => {
  9101. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9102. const group = classifyPrinterStatus(status);
  9103. if (!groups[group]) groups[group] = [];
  9104. groups[group].push(printer);
  9105. });
  9106. }
  9107. return groups;
  9108. // 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
  9109. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9110. const toolbarRef = useRef<HTMLDivElement>(null);
  9111. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9112. const expandedToolbarWidthRef = useRef(0);
  9113. const [compactToolbar, setCompactToolbar] = useState(false);
  9114. const measureToolbar = useCallback(() => {
  9115. const toolbar = toolbarRef.current;
  9116. if (!toolbar) return;
  9117. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9118. if (measuredControlsWidth) {
  9119. expandedToolbarWidthRef.current = measuredControlsWidth;
  9120. }
  9121. const searchMinimumWidth = 220;
  9122. const gapWidth = 8;
  9123. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9124. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9125. }, []);
  9126. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9127. useLayoutEffect(() => {
  9128. measureToolbar();
  9129. const toolbar = toolbarRef.current;
  9130. if (!toolbar) return;
  9131. if (typeof ResizeObserver === 'undefined') {
  9132. window.addEventListener('resize', measureToolbar);
  9133. return () => window.removeEventListener('resize', measureToolbar);
  9134. }
  9135. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9136. resizeObserver.observe(toolbar);
  9137. window.addEventListener('resize', measureToolbar);
  9138. return () => {
  9139. resizeObserver.disconnect();
  9140. window.removeEventListener('resize', measureToolbar);
  9141. };
  9142. }, [
  9143. measureToolbar,
  9144. printers?.length,
  9145. availableLocations.length,
  9146. hideDisconnected,
  9147. smartPlugCount,
  9148. ]);
  9149. const renderFilterControls = (inMenu = false) => (
  9150. <>
  9151. {/* Status filter */}
  9152. {printers && printers.length > 0 && (
  9153. <ToolbarDropdown
  9154. value={statusFilter}
  9155. onChange={handleStatusFilterChange}
  9156. fullWidth={inMenu}
  9157. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9158. />
  9159. )}
  9160. {/* Location filter — only shown when at least one printer has a location */}
  9161. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9162. <ToolbarDropdown
  9163. value={locationFilter}
  9164. onChange={handleLocationFilterChange}
  9165. fullWidth={inMenu}
  9166. options={[
  9167. { value: 'all', label: t('printers.filter.allLocations') },
  9168. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9169. ]}
  9170. />
  9171. )}
  9172. <button
  9173. type="button"
  9174. onClick={toggleHideDisconnected}
  9175. aria-pressed={hideDisconnected}
  9176. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9177. hideDisconnected
  9178. ? 'bg-bambu-green border-bambu-green text-white'
  9179. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9180. }`}
  9181. >
  9182. {t('printers.hideOffline')}
  9183. </button>
  9184. </>
  9185. );
  9186. const renderViewControls = (inMenu = false) => (
  9187. <>
  9188. {/* Sort dropdown */}
  9189. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9190. <ToolbarDropdown<SortOption>
  9191. value={sortBy}
  9192. onChange={handleSortChange}
  9193. fullWidth={inMenu}
  9194. options={[
  9195. { value: 'name', label: t('printers.sort.name') },
  9196. { value: 'status', label: t('printers.sort.status') },
  9197. { value: 'model', label: t('printers.sort.model') },
  9198. { value: 'location', label: t('printers.sort.location') },
  9199. { value: 'eta', label: t('printers.sort.eta') },
  9200. ]}
  9201. />
  9202. <button
  9203. onClick={toggleSortDirection}
  9204. 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"
  9205. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9206. >
  9207. {sortAsc ? (
  9208. <ArrowUp className="w-4 h-4 text-white" />
  9209. ) : (
  9210. <ArrowDown className="w-4 h-4 text-white" />
  9211. )}
  9212. </button>
  9213. </div>
  9214. {/* Page view toggle: Cards / Cam Wall */}
  9215. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9216. <button
  9217. type="button"
  9218. onClick={() => {
  9219. setPageView('cards');
  9220. localStorage.setItem('printerPageView', 'cards');
  9221. }}
  9222. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9223. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9224. }`}
  9225. title={t('printers.pageView.cards')}
  9226. aria-pressed={pageView === 'cards'}
  9227. >
  9228. <LayoutGrid className="w-3.5 h-3.5" />
  9229. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9230. </button>
  9231. <button
  9232. type="button"
  9233. onClick={() => {
  9234. setPageView('camwall');
  9235. localStorage.setItem('printerPageView', 'camwall');
  9236. }}
  9237. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9238. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9239. }`}
  9240. title={t('printers.pageView.camWall')}
  9241. aria-pressed={pageView === 'camwall'}
  9242. disabled={!hasPermission('camera:view')}
  9243. >
  9244. <MonitorPlay className="w-3.5 h-3.5" />
  9245. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9246. </button>
  9247. </div>
  9248. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9249. view, and the page a kiosk token points at. Only offered once the wall
  9250. is the active view, so it doesn't compete with the toggle above. */}
  9251. {pageView === 'camwall' && hasPermission('camera:view') && (
  9252. <RouterLink
  9253. to="/camwall"
  9254. 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' : ''}`}
  9255. title={t('printers.pageView.openCamWallPage')}
  9256. >
  9257. <ExternalLink className="w-3.5 h-3.5" />
  9258. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9259. </RouterLink>
  9260. )}
  9261. {/* Card size selector */}
  9262. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${pageView === 'camwall' ? 'opacity-40 pointer-events-none' : ''} ${inMenu ? 'w-full' : ''}`}>
  9263. {cardSizeLabels.map((label, index) => {
  9264. const size = index + 1;
  9265. const isSelected = cardSize === size;
  9266. return (
  9267. <button
  9268. key={label}
  9269. onClick={() => {
  9270. setCompactDrilldownPrinterId(null);
  9271. setCardSize(size);
  9272. localStorage.setItem('printerCardSize', String(size));
  9273. }}
  9274. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9275. index === 0 ? 'rounded-l-lg' : ''
  9276. } ${
  9277. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9278. } ${
  9279. isSelected
  9280. ? 'bg-bambu-green text-white'
  9281. : 'text-white hover:bg-bambu-dark-tertiary'
  9282. }`}
  9283. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  9284. >
  9285. {label}
  9286. </button>
  9287. );
  9288. })}
  9289. </div>
  9290. </>
  9291. );
  9292. const renderActionControls = (inMenu = false) => (
  9293. <>
  9294. {/* Bulk select toggle */}
  9295. <button
  9296. onClick={() => {
  9297. if (selectionMode) clearSelection();
  9298. else setIsSelectionMode(true);
  9299. }}
  9300. 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' : ''} ${
  9301. selectionMode
  9302. ? 'bg-bambu-green border-bambu-green text-white'
  9303. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9304. }`}
  9305. title={t('printers.bulk.select')}
  9306. disabled={!hasPermission('printers:control')}
  9307. >
  9308. <CheckSquare className="w-4 h-4" />
  9309. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9310. </button>
  9311. {/* Power dropdown for offline printers with smart plugs */}
  9312. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9313. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9314. <button
  9315. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9316. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9317. inMenu
  9318. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9319. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9320. }`}
  9321. >
  9322. <span className="flex items-center gap-1.5">
  9323. <Power className="w-4 h-4" />
  9324. {t('printers.powerOn')}
  9325. </span>
  9326. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9327. </button>
  9328. {showPowerDropdown && (
  9329. <>
  9330. {/* Backdrop to close dropdown */}
  9331. <div
  9332. className="fixed inset-0 z-10"
  9333. onClick={() => setShowPowerDropdown(false)}
  9334. />
  9335. <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">
  9336. <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">
  9337. {t('printers.offlinePrintersWithPlugs')}
  9338. </div>
  9339. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9340. <PowerDropdownItem
  9341. key={printer.id}
  9342. printer={printer}
  9343. plug={smartPlugByPrinter[printer.id]}
  9344. onPowerOn={(plugId) => {
  9345. setPoweringOn(plugId);
  9346. powerOnMutation.mutate(plugId);
  9347. }}
  9348. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9349. />
  9350. ))}
  9351. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9352. <div className="px-3 py-2 text-sm text-bambu-gray">
  9353. No printers with smart plugs
  9354. </div>
  9355. )}
  9356. </div>
  9357. </>
  9358. )}
  9359. </div>
  9360. )}
  9361. <Button
  9362. onClick={() => setShowAddModal(true)}
  9363. disabled={!hasPermission('printers:create')}
  9364. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9365. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9366. >
  9367. <Plus className="w-4 h-4" />
  9368. {t('printers.addPrinter')}
  9369. </Button>
  9370. </>
  9371. );
  9372. return (
  9373. <div className="p-4 md:p-8">
  9374. <div className="space-y-3 mb-6">
  9375. <div>
  9376. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9377. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9378. {t('printers.title')}
  9379. </h1>
  9380. <StatusSummaryBar printers={printers} />
  9381. </div>
  9382. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9383. {/* Only show search bar when printers exist */}
  9384. {printers && printers.length > 0 && (
  9385. <div className="relative min-w-0 flex-1">
  9386. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9387. <input
  9388. type="search"
  9389. name="printer-search"
  9390. autoComplete="off"
  9391. data-1p-ignore
  9392. data-lpignore="true"
  9393. value={search}
  9394. onChange={(e) => setSearch(e.target.value)}
  9395. placeholder={t('printers.search')}
  9396. aria-label={t('printers.search')}
  9397. 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"
  9398. />
  9399. {search && (
  9400. <button
  9401. type="button"
  9402. aria-label={t('common.clear')}
  9403. onClick={() => setSearch('')}
  9404. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9405. >
  9406. <X className="w-4 h-4" />
  9407. </button>
  9408. )}
  9409. </div>
  9410. )}
  9411. <div
  9412. ref={expandedToolbarControlsRef}
  9413. aria-hidden={compactToolbar}
  9414. inert={compactToolbar}
  9415. 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`}
  9416. >
  9417. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9418. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9419. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9420. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9421. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9422. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9423. </div>
  9424. {compactToolbar && (
  9425. <div className="ml-auto flex items-center justify-end gap-1">
  9426. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9427. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9428. </ToolbarMenu>
  9429. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9430. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9431. </ToolbarMenu>
  9432. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9433. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9434. </ToolbarMenu>
  9435. </div>
  9436. )}
  9437. </div>
  9438. </div>
  9439. {isLoading ? (
  9440. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9441. ) : printers?.length === 0 ? (
  9442. <Card>
  9443. <CardContent className="text-center py-12">
  9444. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9445. <Button
  9446. onClick={() => setShowAddModal(true)}
  9447. disabled={!hasPermission('printers:create')}
  9448. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9449. >
  9450. <Plus className="w-4 h-4" />
  9451. {t('printers.addPrinter')}
  9452. </Button>
  9453. </CardContent>
  9454. </Card>
  9455. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9456. <Card>
  9457. <CardContent className="text-center py-12">
  9458. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9459. </CardContent>
  9460. </Card>
  9461. ) : pageView === 'camwall' ? (
  9462. <CameraWall
  9463. printers={sortedPrinters}
  9464. maxLive={camWallMaxLive}
  9465. snapshotIntervalSec={camWallSnapshotSec}
  9466. onTileClick={(id, name) => {
  9467. // A wall tile has no room for a split button, so it follows the
  9468. // mode the card buttons last chose.
  9469. if (cameraViewMode === 'embedded') {
  9470. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9471. } else {
  9472. openCameraWindow(id);
  9473. }
  9474. }}
  9475. statusMode={camWallStatusMode}
  9476. onChangeMaxLive={(next) => {
  9477. setCamWallMaxLive(next);
  9478. localStorage.setItem('camWallMaxLive', String(next));
  9479. }}
  9480. onChangeSnapshotIntervalSec={(next) => {
  9481. setCamWallSnapshotSec(next);
  9482. localStorage.setItem('camWallSnapshotSec', String(next));
  9483. }}
  9484. onChangeStatusMode={(next) => {
  9485. setCamWallStatusMode(next);
  9486. localStorage.setItem('camWallStatusMode', next);
  9487. }}
  9488. />
  9489. ) : groupedPrinters ? (
  9490. /* Grouped view (location, status, or model) */
  9491. <div className="space-y-6">
  9492. {(() => {
  9493. const keys = sortBy === 'status'
  9494. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9495. : Object.keys(groupedPrinters);
  9496. // For status grouping, asc/desc flips the fixed priority order
  9497. // (asc = error→offline, desc = offline→error). This matches the
  9498. // sort-toggle behaviour for other groupings.
  9499. return (sortAsc ? keys : [...keys].reverse());
  9500. })().map((groupKey) => {
  9501. const groupPrinters = groupedPrinters[groupKey];
  9502. const collapseKey = `${sortBy}:${groupKey}`;
  9503. const isOpen = !collapsedSections[collapseKey];
  9504. const dot = sortBy === 'status'
  9505. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9506. : 'bg-bambu-green';
  9507. const label = sortBy === 'status'
  9508. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9509. : groupKey;
  9510. return (
  9511. <Collapsible
  9512. key={groupKey}
  9513. open={isOpen}
  9514. onToggle={() => toggleSectionCollapse(collapseKey)}
  9515. summaryClassName="py-1"
  9516. summary={
  9517. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9518. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9519. {label}
  9520. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9521. {selectionMode && (
  9522. <button
  9523. onClick={(e) => {
  9524. e.stopPropagation();
  9525. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9526. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9527. else if (sortBy === 'model') selectByModel(groupKey);
  9528. }}
  9529. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9530. >
  9531. {t('printers.bulk.selectAll')}
  9532. </button>
  9533. )}
  9534. </h2>
  9535. }
  9536. >
  9537. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9538. {groupPrinters.map((printer) => (
  9539. <PrinterCard
  9540. key={printer.id}
  9541. printer={printer}
  9542. hideIfDisconnected={hideDisconnected}
  9543. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9544. viewMode={viewMode}
  9545. cardSize={cardSize}
  9546. amsThresholds={settings ? {
  9547. humidityGood: Number(settings.ams_humidity_good) || 40,
  9548. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9549. tempGood: Number(settings.ams_temp_good) || 28,
  9550. tempFair: Number(settings.ams_temp_fair) || 35,
  9551. } : undefined}
  9552. spoolmanEnabled={spoolmanEnabled}
  9553. hasUnlinkedSpools={hasUnlinkedSpools}
  9554. linkedSpools={linkedSpools}
  9555. spoolmanUrl={spoolmanStatus?.url}
  9556. spoolmanSyncMode={spoolmanSyncMode}
  9557. onGetAssignment={getAssignment}
  9558. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9559. spoolmanSpools={spoolmanSpools}
  9560. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9561. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9562. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9563. timeFormat={settings?.time_format || 'system'}
  9564. cameraViewMode={cameraViewMode}
  9565. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9566. onSelectCameraViewMode={selectCameraViewMode}
  9567. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9568. dryingPresets={effectiveDryingPresets}
  9569. nozzleTempPresets={effectiveNozzleTempPresets}
  9570. bedTempPresets={effectiveBedTempPresets}
  9571. chamberTempPresets={effectiveChamberTempPresets}
  9572. fanSpeedPresets={effectiveFanSpeedPresets}
  9573. requirePlateClear={settings?.require_plate_clear === true}
  9574. selectionMode={selectionMode}
  9575. isSelected={selectedPrinterIds.has(printer.id)}
  9576. onToggleSelect={toggleSelect}
  9577. onOpenCompactCard={openCompactCard}
  9578. aiDetectionEnabled={isAiMonitored(printer.id)}
  9579. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9580. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9581. />
  9582. ))}
  9583. </div>
  9584. </Collapsible>
  9585. );
  9586. })}
  9587. </div>
  9588. ) : (
  9589. /* Regular grid view */
  9590. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9591. {sortedPrinters.map((printer) => (
  9592. <PrinterCard
  9593. key={printer.id}
  9594. printer={printer}
  9595. hideIfDisconnected={hideDisconnected}
  9596. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9597. viewMode={viewMode}
  9598. cardSize={cardSize}
  9599. spoolmanEnabled={spoolmanEnabled}
  9600. hasUnlinkedSpools={hasUnlinkedSpools}
  9601. linkedSpools={linkedSpools}
  9602. spoolmanUrl={spoolmanStatus?.url}
  9603. spoolmanSyncMode={spoolmanSyncMode}
  9604. onGetAssignment={getAssignment}
  9605. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9606. spoolmanSpools={spoolmanSpools}
  9607. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9608. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9609. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9610. amsThresholds={settings ? {
  9611. humidityGood: Number(settings.ams_humidity_good) || 40,
  9612. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9613. tempGood: Number(settings.ams_temp_good) || 28,
  9614. tempFair: Number(settings.ams_temp_fair) || 35,
  9615. } : undefined}
  9616. timeFormat={settings?.time_format || 'system'}
  9617. cameraViewMode={cameraViewMode}
  9618. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9619. onSelectCameraViewMode={selectCameraViewMode}
  9620. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9621. dryingPresets={effectiveDryingPresets}
  9622. nozzleTempPresets={effectiveNozzleTempPresets}
  9623. bedTempPresets={effectiveBedTempPresets}
  9624. chamberTempPresets={effectiveChamberTempPresets}
  9625. fanSpeedPresets={effectiveFanSpeedPresets}
  9626. requirePlateClear={settings?.require_plate_clear === true}
  9627. selectionMode={selectionMode}
  9628. isSelected={selectedPrinterIds.has(printer.id)}
  9629. onToggleSelect={toggleSelect}
  9630. onOpenCompactCard={openCompactCard}
  9631. aiDetectionEnabled={isAiMonitored(printer.id)}
  9632. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9633. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9634. />
  9635. ))}
  9636. </div>
  9637. )}
  9638. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9639. <button
  9640. type="button"
  9641. onClick={returnToCompactCards}
  9642. 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}`}
  9643. title={t('common.back', 'Back')}
  9644. >
  9645. <ArrowLeft className="w-4 h-4" />
  9646. {t('common.back', 'Back')}
  9647. </button>
  9648. )}
  9649. {showAddModal && (
  9650. <AddPrinterModal
  9651. onClose={() => setShowAddModal(false)}
  9652. onAdd={(data) => addMutation.mutate(data)}
  9653. existingSerials={printers?.map(p => p.serial_number) || []}
  9654. />
  9655. )}
  9656. {/* Bulk selection toolbar */}
  9657. {selectionMode && printers && (
  9658. <BulkPrinterToolbar
  9659. selectedIds={selectedPrinterIds}
  9660. printers={printers}
  9661. onClose={clearSelection}
  9662. onSelectAll={selectAll}
  9663. onSelectByLocation={selectByLocation}
  9664. onSelectByState={selectByState}
  9665. onAction={handleBulkAction}
  9666. actionPending={bulkActionPending}
  9667. />
  9668. )}
  9669. {/* Bulk action confirmation modals */}
  9670. {bulkConfirmAction === 'stop' && (
  9671. <ConfirmModal
  9672. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9673. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9674. confirmText={t('printers.bulk.confirm.stopButton')}
  9675. variant="danger"
  9676. isLoading={bulkActionPending}
  9677. onConfirm={() => executeBulkAction('stop')}
  9678. onCancel={() => setBulkConfirmAction(null)}
  9679. />
  9680. )}
  9681. {bulkConfirmAction === 'pause' && (
  9682. <ConfirmModal
  9683. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9684. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9685. confirmText={t('printers.bulk.confirm.pauseButton')}
  9686. isLoading={bulkActionPending}
  9687. onConfirm={() => executeBulkAction('pause')}
  9688. onCancel={() => setBulkConfirmAction(null)}
  9689. />
  9690. )}
  9691. {bulkConfirmAction === 'clearPlate' && (
  9692. <ConfirmModal
  9693. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9694. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9695. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9696. isLoading={bulkActionPending}
  9697. onConfirm={() => executeBulkAction('clearPlate')}
  9698. onCancel={() => setBulkConfirmAction(null)}
  9699. />
  9700. )}
  9701. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9702. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9703. <EmbeddedCameraViewer
  9704. key={camera.id}
  9705. printerId={camera.id}
  9706. printerName={camera.name}
  9707. viewerIndex={index}
  9708. onClose={() => setEmbeddedCameraPrinters(prev => {
  9709. const next = new Map(prev);
  9710. next.delete(camera.id);
  9711. return next;
  9712. })}
  9713. />
  9714. ))}
  9715. </div>
  9716. );
  9717. }