PrintersPage.tsx 496 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { mapModelCode } from '../utils/printerModel';
  5. import { formatPrintName } from '../utils/printName';
  6. import { isBedSlinger } from '../utils/bedSlinger';
  7. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  8. import {
  9. openCameraWindow,
  10. readStoredCameraViewMode,
  11. storeCameraViewMode,
  12. type CameraViewMode,
  13. } from '../utils/camera';
  14. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  15. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  16. import {
  17. isExternalSpoolHidden,
  18. setExternalSpoolHidden as persistExternalSpoolHidden,
  19. } from '../utils/printerCardPrefs';
  20. import {
  21. BED_TEMP_DEFAULTS,
  22. CHAMBER_TEMP_DEFAULTS,
  23. FAN_SPEED_DEFAULTS,
  24. NOZZLE_TEMP_DEFAULTS,
  25. buildPresetOptions,
  26. parsePresetTriple,
  27. } from '../utils/temperatureFanPresets';
  28. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  29. // covers header + filament select + temp slider + duration + rotate-tray
  30. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  31. // earlier); under-estimating leaves the popover clipped off the bottom (the
  32. // original bug at #1447).
  33. const DRYING_POPOVER_WIDTH = 240;
  34. // Height in "now" mode plus the tallest start-mode control; a conservative
  35. // over-estimate just flips the popover above the trigger sooner.
  36. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  37. // Delay presets for the "After delay" drying start mode, in minutes.
  38. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  39. // Every printer card reads the same fleet-wide scheduled-drying list.
  40. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  41. // Why a due run has not started yet: every waiting_reason the scheduler can
  42. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  43. // for ..." with no hint why nothing is happening.
  44. const WAITING_REASON_KEYS: Record<string, string> = {
  45. ams_power_required: 'printers.drying.powerRequired',
  46. ams_retract_filament: 'printers.drying.retractFilament',
  47. ams_blocked: 'printers.drying.cannotDryNow',
  48. ams_not_found: 'printers.drying.waitingAmsNotFound',
  49. printer_offline: 'printers.drying.waitingOffline',
  50. printer_busy: 'printers.drying.waitingPrinterBusy',
  51. already_drying: 'printers.drying.waitingAlreadyDrying',
  52. interrupted: 'printers.drying.waitingInterrupted',
  53. };
  54. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  55. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  56. }
  57. // Why a scheduled drying failed, by the code the scheduler stores. A row with
  58. // no code (failed before codes existed) or an unknown one shows the backend's
  59. // English error_message instead.
  60. const FAILED_REASON_KEYS: Record<string, string> = {
  61. screen_only: 'printers.drying.screenOnly',
  62. unsupported: 'printers.drying.notSupported',
  63. did_not_start: 'printers.drying.scheduleFailedDidNotStart',
  64. };
  65. function failedReasonKey(code: string | null | undefined): string | undefined {
  66. return code ? FAILED_REASON_KEYS[code] : undefined;
  67. }
  68. // Which cannot-dry code to name when the firmware reports several at once.
  69. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  70. // button's tooltip and a scheduled row's waiting reason describe one blocked
  71. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  72. // left at the outlet, and both need the user to go and do something. The rest
  73. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  74. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  75. const codes = (reasons ?? []).map(r => Number(r));
  76. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  77. if (codes.includes(3)) return 'printers.drying.retractFilament';
  78. return 'printers.drying.cannotDryNow';
  79. }
  80. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  81. import { useTranslation } from 'react-i18next';
  82. import { useTheme } from '../contexts/ThemeContext';
  83. import { useAuth } from '../contexts/AuthContext';
  84. import {
  85. Plus,
  86. Link,
  87. Unlink,
  88. Signal,
  89. Clock,
  90. MoreVertical,
  91. Trash2,
  92. RefreshCw,
  93. RotateCw,
  94. Box,
  95. HardDrive,
  96. AlertTriangle,
  97. AlertCircle,
  98. Terminal,
  99. Power,
  100. Zap,
  101. Wrench,
  102. ChevronDown,
  103. Eye,
  104. EyeOff,
  105. Filter,
  106. Pencil,
  107. ArrowLeft,
  108. ArrowRight,
  109. ArrowUp,
  110. ArrowDown,
  111. Layers,
  112. Video,
  113. Search,
  114. Loader2,
  115. Square,
  116. Pause,
  117. Play,
  118. X,
  119. Fan,
  120. Wind,
  121. AirVent,
  122. Download,
  123. ScanSearch,
  124. CheckCircle,
  125. CheckSquare,
  126. XCircle,
  127. User,
  128. Home,
  129. Printer as PrinterIcon,
  130. Info,
  131. Cable,
  132. Flame,
  133. Hourglass,
  134. Repeat,
  135. Snowflake,
  136. Gauge,
  137. DoorOpen,
  138. DoorClosed,
  139. Move,
  140. LogIn,
  141. LogOut,
  142. MoreHorizontal,
  143. SlidersHorizontal,
  144. Stethoscope,
  145. ScanEye,
  146. LineChart as LineChartIcon,
  147. LayoutGrid,
  148. MonitorPlay,
  149. ExternalLink,
  150. PictureInPicture2,
  151. ThumbsUp,
  152. ThumbsDown,
  153. } from 'lucide-react';
  154. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  155. // Aliased: lucide-react already exports a `Link` icon into this module.
  156. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  157. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  158. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  159. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  160. import { Card, CardContent } from '../components/Card';
  161. import { Button } from '../components/Button';
  162. import { ConfirmModal } from '../components/ConfirmModal';
  163. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  164. import { FileManagerModal } from '../components/FileManagerModal';
  165. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  166. import { CameraWall } from '../components/CameraWall';
  167. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  168. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  169. import { HMSErrorModal, filterKnownHMSErrors, isSevereHMSError } from '../components/HMSErrorModal';
  170. import { AiDetectionModal } from '../components/AiDetectionModal';
  171. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  172. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  173. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  174. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  175. import { AmsBackupModal } from '../components/AmsBackupModal';
  176. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  177. import type { HeaterSensorKind } from '../api/client';
  178. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  179. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  180. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  181. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  182. import { useToast } from '../contexts/ToastContext';
  183. import { ChamberLight } from '../components/icons/ChamberLight';
  184. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  185. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  186. import { FileUploadModal } from '../components/FileUploadModal';
  187. import { PrintModal } from '../components/PrintModal';
  188. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  189. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  190. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  191. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  192. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  193. import { Collapsible } from '../components/Collapsible';
  194. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  195. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  196. import { NumberInput } from '../components/NumberInput';
  197. // The status filter's options, and the only values it may hold. One list so a
  198. // saved filter cannot be validated against a set the dropdown has since moved
  199. // on from (#2833). Labels stay literal so they remain greppable.
  200. const STATUS_FILTER_OPTIONS = [
  201. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  202. { value: 'printing', labelKey: 'printers.status.printing' },
  203. { value: 'paused', labelKey: 'printers.status.paused' },
  204. { value: 'idle', labelKey: 'printers.status.idle' },
  205. { value: 'finished', labelKey: 'printers.status.finished' },
  206. { value: 'error', labelKey: 'printers.status.error' },
  207. { value: 'offline', labelKey: 'printers.status.offline' },
  208. ] as const;
  209. function isKnownStatusFilter(value: string | null): boolean {
  210. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  211. }
  212. export interface SpoolmanSlotAssignmentRow {
  213. printer_id: number;
  214. ams_id: number;
  215. tray_id: number;
  216. spoolman_spool_id: number;
  217. }
  218. // Color names resolve via getColorName() which reads the backend color_catalog
  219. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  220. // Format K value with 3 decimal places, default to 0.020 if null
  221. function formatKValue(k: number | null | undefined): string {
  222. const value = k ?? 0.020;
  223. return value.toFixed(3);
  224. }
  225. // K-profile value shown on the slot card itself (#2532) rather than only inside
  226. // the hover popup, the way BambuStudio shows it per slot.
  227. //
  228. // `k` arrives already gated on the slot being loaded; falsy means the printer
  229. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  230. // missing value, which is captioned inside the hover card but would read as a
  231. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  232. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  233. // reported 0 makes that expression evaluate to the number 0, and React renders
  234. // numbers, putting a bare "0" under the material name.
  235. //
  236. // `reserve` holds the row's height open on the slots without a value whenever
  237. // some other slot on the same card has one, so every fill bar stays on one line.
  238. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  239. const { t } = useTranslation();
  240. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  241. if (!k) {
  242. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  243. }
  244. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  245. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  246. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  247. // family per browser and so measured differently in Safari.
  248. return (
  249. <div className={className} title={t('ams.kFactor')}>
  250. {t('ams.kFactorShort')} {formatKValue(k)}
  251. </div>
  252. );
  253. }
  254. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  255. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  256. const { mode } = useTheme();
  257. const { t } = useTranslation();
  258. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  259. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  260. return (
  261. <span
  262. 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"
  263. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  264. title={side === 'L' ? t('common.left') : t('common.right')}
  265. >
  266. {side}
  267. </span>
  268. );
  269. }
  270. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  271. // deliberately a different colour, because it means something different: this
  272. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  273. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  274. const { mode } = useTheme();
  275. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  276. return (
  277. <span
  278. 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"
  279. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  280. title={title}
  281. >
  282. {FTS_INLET_SIDE[inlet]}
  283. </span>
  284. );
  285. }
  286. /**
  287. * Which side indicator, if any, belongs on an AMS card header.
  288. *
  289. * Three sources, in descending authority:
  290. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  291. * through the switch, so the inlet is the only meaningful label.
  292. * 2. A real extruder id from ams_extruder_map.
  293. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  294. * never reported a map. This one is only a guess, and it is suppressed
  295. * when a switch is installed: with an FTS every unit reports extruder
  296. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  297. * nothing but their unit numbers.
  298. */
  299. function amsSideBadge(
  300. amsId: number,
  301. amsExtruderMap: Record<string, number>,
  302. amsSwitchInlet: Record<string, 'A' | 'B'>,
  303. ftsInstalled: boolean
  304. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  305. const inlet = amsSwitchInlet[String(amsId)];
  306. if (inlet) return { kind: 'inlet', inlet };
  307. const mapped = amsExtruderMap[String(amsId)];
  308. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  309. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  310. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  311. return null;
  312. }
  313. // Expand nozzle type codes to material names
  314. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  315. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  316. function nozzleTypeName(type: string, t: (key: string) => string): string {
  317. if (!type) return '';
  318. // Full text names (from main nozzle info)
  319. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  320. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  321. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  322. // 4-char codes (e.g. "HS01"): last 2 digits = material
  323. if (type.length >= 4) {
  324. const material = type.slice(2, 4);
  325. if (material === '00') return t('printers.nozzleStainlessSteel');
  326. if (material === '01') return t('printers.nozzleHardenedSteel');
  327. if (material === '05') return t('printers.nozzleTungstenCarbide');
  328. }
  329. // 2-digit numeric codes
  330. if (type === '00') return t('printers.nozzleStainlessSteel');
  331. if (type === '01') return t('printers.nozzleHardenedSteel');
  332. if (type === '05') return t('printers.nozzleTungstenCarbide');
  333. // 2-char alpha codes: H prefix = hardened steel
  334. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  335. return type;
  336. }
  337. // Parse flow type from nozzle type code
  338. // HH = high flow, HS = standard/normal
  339. function nozzleFlowName(type: string, t: (key: string) => string): string {
  340. if (!type) return '';
  341. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  342. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  343. return '';
  344. }
  345. // Per-slot hover card for nozzle rack
  346. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  347. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  348. slot: import('../api/client').NozzleRackSlot;
  349. index: number;
  350. activeStatus?: boolean;
  351. filamentName?: string;
  352. children: React.ReactNode;
  353. }) {
  354. const { t } = useTranslation();
  355. const [isVisible, setIsVisible] = useState(false);
  356. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  357. const triggerRef = useRef<HTMLDivElement>(null);
  358. const cardRef = useRef<HTMLDivElement>(null);
  359. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  360. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  361. const isMounted = slot.stat === 1;
  362. useEffect(() => {
  363. if (isVisible && triggerRef.current && cardRef.current) {
  364. const triggerRect = triggerRef.current.getBoundingClientRect();
  365. const cardHeight = cardRef.current.offsetHeight;
  366. const headerHeight = 56;
  367. const spaceAbove = triggerRect.top - headerHeight;
  368. const spaceBelow = window.innerHeight - triggerRect.bottom;
  369. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  370. setPosition('bottom');
  371. } else {
  372. setPosition('top');
  373. }
  374. }
  375. }, [isVisible]);
  376. const handleMouseEnter = () => {
  377. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  378. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  379. };
  380. const handleMouseLeave = () => {
  381. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  382. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  383. };
  384. useEffect(() => {
  385. return () => {
  386. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  387. };
  388. }, []);
  389. const filamentCss = parseFilamentColor(slot.filament_color);
  390. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  391. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  392. return (
  393. <div
  394. ref={triggerRef}
  395. className="relative"
  396. onMouseEnter={handleMouseEnter}
  397. onMouseLeave={handleMouseLeave}
  398. >
  399. {children}
  400. {isVisible && (
  401. <div
  402. ref={cardRef}
  403. className={`
  404. absolute left-1/2 -translate-x-1/2 z-50
  405. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  406. animate-in fade-in-0 zoom-in-95 duration-150
  407. `}
  408. style={{ maxWidth: 'calc(100vw - 24px)' }}
  409. >
  410. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  411. {isEmpty ? (
  412. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  413. Slot {index + 1} — Empty
  414. </div>
  415. ) : (
  416. <div className="p-2.5 space-y-1.5">
  417. {/* Diameter */}
  418. <div className="flex items-center justify-between">
  419. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  420. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  421. </div>
  422. {/* Type */}
  423. {typeFull && (
  424. <div className="flex items-center justify-between">
  425. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  426. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  427. </div>
  428. )}
  429. {/* Flow (hide if empty) */}
  430. {flowFull && (
  431. <div className="flex items-center justify-between">
  432. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  433. <span className="text-xs text-white font-semibold">{flowFull}</span>
  434. </div>
  435. )}
  436. {/* Status badge */}
  437. <div className="flex items-center justify-between">
  438. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  439. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  440. activeStatus || isMounted
  441. ? 'bg-green-900/50 text-green-400'
  442. : 'bg-bambu-dark-tertiary text-bambu-gray'
  443. }`}>
  444. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  445. </span>
  446. </div>
  447. {/* Wear (hide if null) */}
  448. {slot.wear != null && (
  449. <div className="flex items-center justify-between">
  450. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  451. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  452. </div>
  453. )}
  454. {/* Max Temp (hide if 0) */}
  455. {slot.max_temp > 0 && (
  456. <div className="flex items-center justify-between">
  457. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  458. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  459. </div>
  460. )}
  461. {/* Serial (hide if empty) */}
  462. {slot.serial_number && (
  463. <div className="flex items-center justify-between">
  464. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  465. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  466. </div>
  467. )}
  468. {/* Filament: material type + color swatch (hide if no color) */}
  469. {(filamentCss || slot.filament_type) && (
  470. <div className="flex items-center justify-between">
  471. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  472. <div className="flex items-center gap-1">
  473. {filamentCss && (
  474. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  475. )}
  476. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  477. </div>
  478. </div>
  479. )}
  480. </div>
  481. )}
  482. </div>
  483. {/* Arrow pointer */}
  484. <div
  485. className={`
  486. absolute left-1/2 -translate-x-1/2 w-0 h-0
  487. border-l-[6px] border-l-transparent
  488. border-r-[6px] border-r-transparent
  489. ${position === 'top'
  490. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  491. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  492. `}
  493. />
  494. </div>
  495. )}
  496. </div>
  497. );
  498. }
  499. // Dual-nozzle hover card showing L and R nozzle details side by side
  500. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  501. leftSlot?: import('../api/client').NozzleRackSlot;
  502. rightSlot?: import('../api/client').NozzleRackSlot;
  503. activeNozzle: 'L' | 'R';
  504. filamentInfo?: Record<string, { name: string; k: number | null }>;
  505. children: React.ReactNode;
  506. }) {
  507. const { t } = useTranslation();
  508. const [isVisible, setIsVisible] = useState(false);
  509. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  510. const triggerRef = useRef<HTMLDivElement>(null);
  511. const cardRef = useRef<HTMLDivElement>(null);
  512. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  513. useEffect(() => {
  514. if (isVisible && triggerRef.current && cardRef.current) {
  515. const triggerRect = triggerRef.current.getBoundingClientRect();
  516. const cardHeight = cardRef.current.offsetHeight;
  517. const headerHeight = 56;
  518. const spaceAbove = triggerRect.top - headerHeight;
  519. const spaceBelow = window.innerHeight - triggerRect.bottom;
  520. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  521. setPosition('bottom');
  522. } else {
  523. setPosition('top');
  524. }
  525. }
  526. }, [isVisible]);
  527. const handleMouseEnter = () => {
  528. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  529. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  530. };
  531. const handleMouseLeave = () => {
  532. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  533. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  534. };
  535. useEffect(() => {
  536. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  537. }, []);
  538. if (!leftSlot && !rightSlot) return <>{children}</>;
  539. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  540. const isActive = activeNozzle === side;
  541. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  542. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  543. const filamentCss = parseFilamentColor(slot.filament_color);
  544. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  545. return (
  546. <div className="flex-1 space-y-1.5">
  547. <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'}`}>
  548. {side === 'L' ? t('common.left') : t('common.right')}
  549. </div>
  550. {slot.nozzle_diameter && (
  551. <div className="flex items-center justify-between">
  552. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  553. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  554. </div>
  555. )}
  556. {typeFull && (
  557. <div className="flex items-center justify-between">
  558. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  559. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  560. </div>
  561. )}
  562. {flowFull && (
  563. <div className="flex items-center justify-between">
  564. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  565. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  566. </div>
  567. )}
  568. <div className="flex items-center justify-between">
  569. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  570. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  571. isActive
  572. ? 'bg-green-900/50 text-green-400'
  573. : 'bg-bambu-dark-tertiary text-bambu-gray'
  574. }`}>
  575. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  576. </span>
  577. </div>
  578. {slot.wear != null && (
  579. <div className="flex items-center justify-between">
  580. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  581. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  582. </div>
  583. )}
  584. {/* Serial and max temp only available on the right (removable) nozzle */}
  585. {side === 'R' && slot.max_temp > 0 && (
  586. <div className="flex items-center justify-between">
  587. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  588. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  589. </div>
  590. )}
  591. {side === 'R' && slot.serial_number && (
  592. <div className="flex items-center justify-between">
  593. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  594. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  595. </div>
  596. )}
  597. {(filamentCss || slot.filament_type || slot.filament_id) && (
  598. <div className="flex items-center justify-between">
  599. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  600. <div className="flex items-center gap-1">
  601. {filamentCss && (
  602. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  603. )}
  604. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  605. {filamentName || slot.filament_type || slot.filament_id || ''}
  606. </span>
  607. </div>
  608. </div>
  609. )}
  610. </div>
  611. );
  612. };
  613. return (
  614. <div
  615. ref={triggerRef}
  616. className="relative flex-1"
  617. onMouseEnter={handleMouseEnter}
  618. onMouseLeave={handleMouseLeave}
  619. >
  620. {children}
  621. {isVisible && (
  622. <div
  623. ref={cardRef}
  624. className={`
  625. absolute left-1/2 -translate-x-1/2 z-50
  626. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  627. animate-in fade-in-0 zoom-in-95 duration-150
  628. `}
  629. style={{ maxWidth: 'calc(100vw - 24px)' }}
  630. >
  631. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  632. <div className="p-2.5 flex gap-3">
  633. {leftSlot && renderColumn(leftSlot, 'L')}
  634. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  635. {rightSlot && renderColumn(rightSlot, 'R')}
  636. </div>
  637. </div>
  638. {/* Arrow pointer */}
  639. <div
  640. className={`
  641. absolute left-1/2 -translate-x-1/2 w-0 h-0
  642. border-l-[6px] border-l-transparent
  643. border-r-[6px] border-r-transparent
  644. ${position === 'top'
  645. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  646. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  647. `}
  648. />
  649. </div>
  650. )}
  651. </div>
  652. );
  653. }
  654. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  655. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  656. const { t } = useTranslation();
  657. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  658. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  659. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  660. // base — computing it from min(present IDs) shifts everything left when slot 16
  661. // is the one currently mounted (#943).
  662. const rackNozzles = slots.filter(s => s.id >= 2);
  663. const RACK_SIZE = 6;
  664. const RACK_BASE_ID = 16;
  665. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  666. { length: RACK_SIZE },
  667. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  668. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  669. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  670. },
  671. );
  672. return (
  673. // Sized to its contents rather than growing: the six chips are a fixed
  674. // width at any one card size, so extra width would be dead space taken
  675. // from the temperature cards beside it — which are flex-1 with a 0 basis
  676. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  677. // stays enabled so the card still gives way on a narrow printer card
  678. // instead of overflowing.
  679. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  680. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  681. <div className="flex gap-[3px] justify-center">
  682. {rackSlots.map((slot, i) => {
  683. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  684. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  685. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  686. return (
  687. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  688. <div className="flex flex-col items-center gap-0.5">
  689. <div
  690. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  691. isEmpty
  692. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  693. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  694. }`}
  695. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  696. >
  697. <span
  698. data-rack-diameter
  699. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  700. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  701. >
  702. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  703. </span>
  704. </div>
  705. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  706. acted on without counting chips. Sits below the chip rather
  707. than inside it: the chip is barely wider than its own
  708. diameter text and already carries that over a
  709. filament-coloured background. */}
  710. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  711. {i + 1}
  712. </span>
  713. </div>
  714. </NozzleSlotHoverCard>
  715. );
  716. })}
  717. </div>
  718. </div>
  719. );
  720. }
  721. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  722. function WaterDropEmpty({ className }: { className?: string }) {
  723. return (
  724. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  725. <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"/>
  726. </svg>
  727. );
  728. }
  729. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  730. function WaterDropHalf({ className }: { className?: string }) {
  731. return (
  732. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  733. <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"/>
  734. <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"/>
  735. </svg>
  736. );
  737. }
  738. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  739. function WaterDropFull({ className }: { className?: string }) {
  740. return (
  741. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  742. <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"/>
  743. <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"/>
  744. </svg>
  745. );
  746. }
  747. // Thermometer SVG - empty outline
  748. function ThermometerEmpty({ className }: { className?: string }) {
  749. return (
  750. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  751. <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"/>
  752. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  753. </svg>
  754. );
  755. }
  756. // Thermometer SVG - half filled (gold - same as humidity fair)
  757. function ThermometerHalf({ className }: { className?: string }) {
  758. return (
  759. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  760. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  761. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  762. <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"/>
  763. </svg>
  764. );
  765. }
  766. // Thermometer SVG - fully filled (red - same as humidity bad)
  767. function ThermometerFull({ className }: { className?: string }) {
  768. return (
  769. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  770. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  771. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  772. <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"/>
  773. </svg>
  774. );
  775. }
  776. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  777. // Added for visual parity with the thermometer icons on the dual-nozzle card
  778. // that previously had no icon at all (#1115, design by @m4rtini2).
  779. function NozzleIcon({ className }: { className?: string }) {
  780. return (
  781. <svg
  782. className={className}
  783. viewBox="0 0 24 24"
  784. fill="none"
  785. xmlns="http://www.w3.org/2000/svg"
  786. stroke="currentColor"
  787. strokeWidth="1.5"
  788. strokeLinecap="round"
  789. strokeLinejoin="round"
  790. >
  791. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  792. <rect x="6" y="11.5" width="12.1" height="3.7" />
  793. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  794. </svg>
  795. );
  796. }
  797. // Heater thermometer icon - filled when heating, outline when off
  798. interface HeaterThermometerProps {
  799. className?: string;
  800. color: string; // The color class (e.g., "text-orange-400")
  801. isHeating: boolean;
  802. }
  803. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  804. // Extract the actual color from Tailwind class for SVG fill
  805. const colorMap: Record<string, string> = {
  806. 'text-orange-400': '#fb923c',
  807. 'text-blue-400': '#60a5fa',
  808. 'text-green-400': '#4ade80',
  809. };
  810. const fillColor = colorMap[color] || '#888';
  811. // Glow style when heating
  812. const glowStyle = isHeating ? {
  813. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  814. } : {};
  815. if (isHeating) {
  816. // Filled thermometer with glow - heater is ON
  817. return (
  818. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  819. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  820. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  821. <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"/>
  822. </svg>
  823. );
  824. }
  825. // Empty thermometer - heater is OFF
  826. return (
  827. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  828. <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"/>
  829. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  830. </svg>
  831. );
  832. }
  833. // AMS Filament Backup tri-state indicator + toggle.
  834. // state=true → ON, click to disable
  835. // state=false → OFF, click opens modal
  836. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  837. interface AmsBackupBadgeProps {
  838. state: boolean | null;
  839. onClick: () => void;
  840. }
  841. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  842. const { t } = useTranslation();
  843. const known = state !== null;
  844. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  845. let title: string;
  846. if (state === true) {
  847. className += known
  848. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  849. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  850. title = t('printers.amsBackup.titleOn');
  851. } else if (state === false) {
  852. className += known
  853. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  854. : 'bg-bambu-dark text-bambu-gray cursor-default';
  855. title = t('printers.amsBackup.titleOff');
  856. } else {
  857. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  858. title = t('printers.amsBackup.titleUnknown');
  859. }
  860. return (
  861. <button
  862. type="button"
  863. disabled={!known}
  864. onClick={() => known && onClick()}
  865. className={className}
  866. title={title}
  867. aria-label={title}
  868. >
  869. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  870. </button>
  871. );
  872. }
  873. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  874. // like AmsBackupBadge so the two sit together in the section header, but
  875. // pinned to the right-hand end of the rule: this is a view preference for the
  876. // row, not a property of the printer.
  877. interface ExternalSpoolToggleProps {
  878. hidden: boolean;
  879. onClick: () => void;
  880. }
  881. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  882. const { t } = useTranslation();
  883. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  884. return (
  885. <button
  886. type="button"
  887. onClick={onClick}
  888. aria-pressed={hidden}
  889. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  890. hidden
  891. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  892. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  893. }`}
  894. title={title}
  895. aria-label={title}
  896. >
  897. {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)]" />}
  898. </button>
  899. );
  900. }
  901. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  902. // Reference: https://github.com/theicedmango/bambu-humidity
  903. interface HumidityIndicatorProps {
  904. humidity: number | string;
  905. goodThreshold?: number; // <= this is green
  906. fairThreshold?: number; // <= this is orange, > is red
  907. onClick?: () => void;
  908. compact?: boolean; // Smaller version for grid layout
  909. }
  910. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  911. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  912. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  913. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  914. // Status thresholds (configurable via settings)
  915. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  916. let textColor: string;
  917. let statusText: string;
  918. if (isNaN(humidityValue)) {
  919. textColor = '#C3C2C1';
  920. statusText = 'Unknown';
  921. } else if (humidityValue <= good) {
  922. textColor = '#22a352'; // Green - Good
  923. statusText = 'Good';
  924. } else if (humidityValue <= fair) {
  925. textColor = '#d4a017'; // Gold - Fair
  926. statusText = 'Fair';
  927. } else {
  928. textColor = '#c62828'; // Red - Bad
  929. statusText = 'Bad';
  930. }
  931. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  932. let DropComponent: React.FC<{ className?: string }>;
  933. if (isNaN(humidityValue)) {
  934. DropComponent = WaterDropEmpty;
  935. } else if (humidityValue <= good) {
  936. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  937. } else if (humidityValue <= fair) {
  938. DropComponent = WaterDropHalf; // Fair - half filled
  939. } else {
  940. DropComponent = WaterDropFull; // Bad - full (too humid)
  941. }
  942. return (
  943. <button
  944. type="button"
  945. onClick={onClick}
  946. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  947. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  948. >
  949. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  950. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  951. </button>
  952. );
  953. }
  954. // Temperature indicator with dynamic icon and coloring
  955. interface TemperatureIndicatorProps {
  956. temp: number;
  957. goodThreshold?: number; // <= this is blue
  958. fairThreshold?: number; // <= this is orange, > is red
  959. onClick?: () => void;
  960. compact?: boolean; // Smaller version for grid layout
  961. }
  962. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  963. // Ensure thresholds are numbers
  964. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  965. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  966. let textColor: string;
  967. let statusText: string;
  968. let ThermoComponent: React.FC<{ className?: string }>;
  969. if (temp <= good) {
  970. textColor = '#22a352'; // Green - good (same as humidity)
  971. statusText = 'Good';
  972. ThermoComponent = ThermometerEmpty;
  973. } else if (temp <= fair) {
  974. textColor = '#d4a017'; // Gold - fair (same as humidity)
  975. statusText = 'Fair';
  976. ThermoComponent = ThermometerHalf;
  977. } else {
  978. textColor = '#c62828'; // Red - bad (same as humidity)
  979. statusText = 'Bad';
  980. ThermoComponent = ThermometerFull;
  981. }
  982. return (
  983. <button
  984. type="button"
  985. onClick={onClick}
  986. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  987. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  988. >
  989. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  990. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  991. </button>
  992. );
  993. }
  994. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  995. *
  996. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  997. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  998. * every empty-by-bitmask slot lands here regardless of firmware payload
  999. * shape.
  1000. *
  1001. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  1002. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  1003. * the user cleared with "Reset Slot" where a physical spool may still be
  1004. * loaded but unassigned.
  1005. *
  1006. * Returns null when the slot is loaded (tray_type is present).
  1007. */
  1008. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  1009. if (tray?.tray_type) return null;
  1010. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  1011. // spool the firmware can't identify is physically present (exists === true)
  1012. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  1013. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  1014. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  1015. if (tray?.exists === true) return 'reset';
  1016. if (tray?.exists === false) return 'physical';
  1017. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  1018. }
  1019. // How long to wait for an AMS to report a live drying cycle after the printer
  1020. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  1021. // within a couple of seconds; 30s covers the slowest observed push cadence
  1022. // without leaving the user waiting on a verdict.
  1023. const DRY_START_CONFIRM_MS = 30_000;
  1024. export function CoverImage({
  1025. url,
  1026. printName,
  1027. className = 'w-20 h-20',
  1028. radiusClass = 'rounded-lg',
  1029. }: {
  1030. url: string | null;
  1031. printName?: string;
  1032. className?: string;
  1033. radiusClass?: string;
  1034. }) {
  1035. const { t } = useTranslation();
  1036. const [loaded, setLoaded] = useState(false);
  1037. const [error, setError] = useState(false);
  1038. const [showOverlay, setShowOverlay] = useState(false);
  1039. const imgRef = useRef<HTMLImageElement>(null);
  1040. // Cache-bust the image URL when the print name changes so the browser
  1041. // fetches the new cover instead of serving the stale cached image.
  1042. const cacheBustedUrl = useMemo(() => {
  1043. if (!url) return null;
  1044. const sep = url.includes('?') ? '&' : '?';
  1045. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1046. }, [url, printName]);
  1047. // Re-evaluate load state when the image URL changes, and ask the element
  1048. // whether it is already showing something rather than assuming it is not.
  1049. //
  1050. // `onLoad` used to be the only thing that could set `loaded`, and this
  1051. // effect reset it to false unconditionally. That is right when the URL
  1052. // really changes, but it also runs on mount — and the two are not the same
  1053. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1054. // constant for the duration of a print, so navigating away from the
  1055. // printers page and back re-mounts with a byte-identical src that the
  1056. // browser serves from its in-memory cache. The `load` event for a cache hit
  1057. // and React's passive-effect flush are both plain tasks with no ordering
  1058. // between them, so when `load` won, this effect ran afterwards and undid
  1059. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1060. // sat there until a full reload. Nothing recovered it, because the URL
  1061. // never changes again during the print and so this effect never re-runs.
  1062. //
  1063. // Being a race, it reproduced every time for #2826's reporter and not at
  1064. // all here, which is also why the network panel showed no request: there
  1065. // was no request to show.
  1066. //
  1067. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1068. // which of the two ran first. It is also correct for the case the reporter
  1069. // proposed (a `load` that fires before React's handler is live), so the
  1070. // fix stands whichever mechanism is really at work.
  1071. useEffect(() => {
  1072. setError(false);
  1073. const el = imgRef.current;
  1074. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1075. }, [cacheBustedUrl]);
  1076. return (
  1077. <>
  1078. <div
  1079. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1080. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1081. >
  1082. {cacheBustedUrl && !error ? (
  1083. <>
  1084. <img
  1085. ref={imgRef}
  1086. src={cacheBustedUrl}
  1087. alt={t('printers.printPreview')}
  1088. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1089. onLoad={() => setLoaded(true)}
  1090. onError={() => setError(true)}
  1091. />
  1092. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1093. </>
  1094. ) : (
  1095. <Box className="w-8 h-8 text-bambu-gray" />
  1096. )}
  1097. </div>
  1098. {/* Cover Image Overlay */}
  1099. {showOverlay && cacheBustedUrl && (
  1100. <div
  1101. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1102. onClick={() => setShowOverlay(false)}
  1103. >
  1104. <div className="relative max-w-2xl max-h-full">
  1105. <img
  1106. src={cacheBustedUrl}
  1107. alt={t('printers.printPreview')}
  1108. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1109. />
  1110. {printName && (
  1111. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1112. )}
  1113. </div>
  1114. </div>
  1115. )}
  1116. </>
  1117. );
  1118. }
  1119. interface PrinterMaintenanceInfo {
  1120. due_count: number;
  1121. warning_count: number;
  1122. total_print_hours: number;
  1123. }
  1124. // Status summary bar component - uses queryClient to read cached statuses
  1125. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1126. const { t } = useTranslation();
  1127. const queryClient = useQueryClient();
  1128. // Subscribe to query cache changes to re-render when status updates
  1129. // Throttled to prevent rapid re-renders from causing tab crashes
  1130. const [cacheTick, setCacheTick] = useState(0);
  1131. useEffect(() => {
  1132. let pending = false;
  1133. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1134. if (!pending) {
  1135. pending = true;
  1136. requestAnimationFrame(() => {
  1137. setCacheTick(t => t + 1);
  1138. pending = false;
  1139. });
  1140. }
  1141. });
  1142. return () => unsubscribe();
  1143. }, [queryClient]);
  1144. const { counts, nextFinish } = useMemo(() => {
  1145. let printing = 0;
  1146. let paused = 0;
  1147. let finished = 0;
  1148. let idle = 0;
  1149. let offline = 0;
  1150. let loading = 0;
  1151. let error = 0;
  1152. let nextPrinterName: string | null = null;
  1153. let nextRemainingMin: number | null = null;
  1154. let nextProgress: number = 0;
  1155. printers?.forEach((printer) => {
  1156. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1157. if (status === undefined) {
  1158. // Status not yet loaded - don't count as offline yet
  1159. loading++;
  1160. } else if (!status.connected) {
  1161. offline++;
  1162. } else {
  1163. // Count printers with active HMS errors as problems
  1164. const knownHmsCount =
  1165. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1166. if (knownHmsCount > 0) {
  1167. error++;
  1168. }
  1169. switch (status.state) {
  1170. case 'RUNNING':
  1171. printing++;
  1172. if (status.remaining_time != null && status.remaining_time > 0) {
  1173. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1174. nextRemainingMin = status.remaining_time;
  1175. nextPrinterName = printer.name;
  1176. nextProgress = status.progress || 0;
  1177. }
  1178. }
  1179. break;
  1180. case 'PAUSE':
  1181. paused++;
  1182. break;
  1183. case 'FINISH':
  1184. finished++;
  1185. break;
  1186. case 'FAILED':
  1187. // FAILED is the printer's terminal gcode_state after a print stops —
  1188. // including user cancellations, where there's no actual fault. Only
  1189. // count it as a "problem" when an HMS error is also active; otherwise
  1190. // it's just a print that ended unsuccessfully and the plate needs
  1191. // clearing (same as FINISH from the operator's perspective).
  1192. if (knownHmsCount > 0) {
  1193. // Already counted above
  1194. } else {
  1195. finished++;
  1196. }
  1197. break;
  1198. default:
  1199. idle++;
  1200. break;
  1201. }
  1202. }
  1203. });
  1204. return {
  1205. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1206. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1207. };
  1208. // eslint-disable-next-line react-hooks/exhaustive-deps
  1209. }, [printers, queryClient, cacheTick]);
  1210. if (!printers?.length) return null;
  1211. const badges: { count: number; dot: string; label: string }[] = [
  1212. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1213. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1214. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1215. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1216. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1217. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1218. ];
  1219. return (
  1220. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1221. {badges.map(({ count, dot, label }) => count > 0 && (
  1222. <div key={label} className="flex items-center gap-1.5">
  1223. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1224. <span className="text-bambu-gray">
  1225. <span className="text-white font-medium">{count}</span> {label}
  1226. </span>
  1227. </div>
  1228. ))}
  1229. {nextFinish && (
  1230. <>
  1231. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1232. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1233. <div className="flex items-center gap-2">
  1234. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1235. <span className="text-white font-medium">{nextFinish.name}</span>
  1236. </div>
  1237. <div className="flex items-center gap-2 w-full sm:w-auto">
  1238. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1239. <div
  1240. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1241. style={{ width: `${nextFinish.progress}%` }}
  1242. />
  1243. </div>
  1244. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1245. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1246. </div>
  1247. </div>
  1248. </>
  1249. )}
  1250. </div>
  1251. );
  1252. }
  1253. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1254. type ViewMode = 'expanded' | 'compact';
  1255. type ToolbarDropdownOption<T extends string> = {
  1256. value: T;
  1257. label: string;
  1258. };
  1259. function ToolbarDropdown<T extends string>({
  1260. value,
  1261. options,
  1262. onChange,
  1263. fullWidth = false,
  1264. }: {
  1265. value: T;
  1266. options: ToolbarDropdownOption<T>[];
  1267. onChange: (value: T) => void;
  1268. fullWidth?: boolean;
  1269. }) {
  1270. const [isOpen, setIsOpen] = useState(false);
  1271. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1272. return (
  1273. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1274. <button
  1275. type="button"
  1276. onClick={() => setIsOpen(open => !open)}
  1277. 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'}`}
  1278. >
  1279. <span className="truncate">{selectedOption?.label}</span>
  1280. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1281. </button>
  1282. {isOpen && (
  1283. <>
  1284. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1285. <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">
  1286. {options.map(option => (
  1287. <button
  1288. key={option.value}
  1289. type="button"
  1290. onClick={() => {
  1291. onChange(option.value);
  1292. setIsOpen(false);
  1293. }}
  1294. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1295. option.value === value ? 'text-bambu-green' : 'text-white'
  1296. }`}
  1297. >
  1298. {option.label}
  1299. </button>
  1300. ))}
  1301. </div>
  1302. </>
  1303. )}
  1304. </div>
  1305. );
  1306. }
  1307. function ToolbarMenu({
  1308. label,
  1309. icon,
  1310. children,
  1311. }: {
  1312. label: string;
  1313. icon: React.ReactNode;
  1314. children: React.ReactNode;
  1315. }) {
  1316. const [isOpen, setIsOpen] = useState(false);
  1317. return (
  1318. <div className="relative">
  1319. <button
  1320. type="button"
  1321. onClick={() => setIsOpen(open => !open)}
  1322. 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"
  1323. aria-label={label}
  1324. title={label}
  1325. >
  1326. {icon}
  1327. </button>
  1328. {isOpen && (
  1329. <>
  1330. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1331. <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">
  1332. {children}
  1333. </div>
  1334. </>
  1335. )}
  1336. </div>
  1337. );
  1338. }
  1339. function IndicatorControlPopover({
  1340. title,
  1341. options = [],
  1342. unit,
  1343. customMin,
  1344. customMax,
  1345. customStep = 1,
  1346. widthClass = 'w-[240px]',
  1347. popoverWidth = 240,
  1348. popoverHeight = 280,
  1349. isPending,
  1350. onClose,
  1351. onSubmit,
  1352. children,
  1353. }: {
  1354. title: string;
  1355. options?: Array<{ label: string; value: number }>;
  1356. unit?: string;
  1357. customMin?: number;
  1358. customMax?: number;
  1359. customStep?: number;
  1360. widthClass?: string;
  1361. popoverWidth?: number;
  1362. popoverHeight?: number;
  1363. isPending?: boolean;
  1364. onClose: () => void;
  1365. onSubmit?: (value: number) => void;
  1366. children?: React.ReactNode;
  1367. }) {
  1368. const anchorRef = useRef<HTMLSpanElement>(null);
  1369. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1370. const [customValue, setCustomValue] = useState('');
  1371. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1372. // can position via fixed coords. Portaling to document.body escapes
  1373. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1374. // own contexts and would otherwise cover the popover even at z-[60].
  1375. useLayoutEffect(() => {
  1376. const trigger = anchorRef.current?.parentElement;
  1377. if (!trigger) return;
  1378. const measure = () => {
  1379. const rect = trigger.getBoundingClientRect();
  1380. setCoords(computePopoverPosition({
  1381. triggerRect: rect,
  1382. popoverWidth,
  1383. estimatedHeight: popoverHeight,
  1384. horizontalAlign: 'center',
  1385. }));
  1386. };
  1387. measure();
  1388. window.addEventListener('resize', measure);
  1389. window.addEventListener('scroll', measure, true);
  1390. return () => {
  1391. window.removeEventListener('resize', measure);
  1392. window.removeEventListener('scroll', measure, true);
  1393. };
  1394. }, [popoverWidth, popoverHeight]);
  1395. const showCustomInput = unit !== undefined;
  1396. const submitCustom = () => {
  1397. const value = Number(customValue);
  1398. if (!Number.isFinite(value)) return;
  1399. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1400. onSubmit?.(Math.round(bounded));
  1401. };
  1402. return (
  1403. <>
  1404. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1405. {createPortal(
  1406. <>
  1407. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1408. <div
  1409. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1410. style={{
  1411. top: coords?.top ?? -9999,
  1412. left: coords?.left ?? -9999,
  1413. visibility: coords ? 'visible' : 'hidden',
  1414. }}
  1415. onClick={e => e.stopPropagation()}
  1416. >
  1417. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1418. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1419. {options.length > 0 && (
  1420. <div className="px-3 py-2.5">
  1421. <div className="grid grid-cols-2 gap-1.5">
  1422. {options.map(option => (
  1423. <button
  1424. key={`${option.label}-${option.value}`}
  1425. type="button"
  1426. disabled={isPending}
  1427. onClick={() => onSubmit?.(option.value)}
  1428. 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"
  1429. >
  1430. {option.label}
  1431. </button>
  1432. ))}
  1433. </div>
  1434. </div>
  1435. )}
  1436. {children}
  1437. {showCustomInput && (
  1438. <>
  1439. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1440. <form
  1441. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1442. onSubmit={(e) => {
  1443. e.preventDefault();
  1444. submitCustom();
  1445. }}
  1446. >
  1447. <input
  1448. type="number"
  1449. min={customMin}
  1450. max={customMax}
  1451. step={customStep}
  1452. value={customValue}
  1453. onChange={e => setCustomValue(e.target.value)}
  1454. placeholder="Custom"
  1455. 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"
  1456. />
  1457. <button
  1458. type="submit"
  1459. disabled={isPending || customValue.trim() === ''}
  1460. 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"
  1461. >
  1462. Set
  1463. </button>
  1464. </form>
  1465. </>
  1466. )}
  1467. </div>
  1468. </>,
  1469. document.body
  1470. )}
  1471. </>
  1472. );
  1473. }
  1474. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1475. function NozzleTemperatureControlBox({
  1476. label,
  1477. current,
  1478. target,
  1479. isActive,
  1480. isPending,
  1481. onSubmit,
  1482. options = NOZZLE_TEMPERATURE_OPTIONS,
  1483. }: {
  1484. label: string;
  1485. current?: number;
  1486. target?: number;
  1487. isActive: boolean;
  1488. isPending?: boolean;
  1489. onSubmit: (value: number) => void;
  1490. options?: Array<{ label: string; value: number }>;
  1491. }) {
  1492. const [customValue, setCustomValue] = useState('');
  1493. const submitCustom = () => {
  1494. const value = Number(customValue);
  1495. if (!Number.isFinite(value)) return;
  1496. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1497. };
  1498. return (
  1499. <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'}`}>
  1500. <div className="mb-1.5 flex items-center justify-between gap-2">
  1501. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1502. <span className="text-[10px] text-bambu-gray">
  1503. {Math.round(current ?? 0)}°C
  1504. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1505. </span>
  1506. </div>
  1507. <div className="grid grid-cols-2 gap-1">
  1508. {options.map(option => (
  1509. <button
  1510. key={`${label}-${option.value}`}
  1511. type="button"
  1512. disabled={isPending}
  1513. onClick={() => onSubmit(option.value)}
  1514. 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"
  1515. >
  1516. {option.label}
  1517. </button>
  1518. ))}
  1519. </div>
  1520. <form
  1521. className="mt-1.5 flex gap-1"
  1522. onSubmit={(e) => {
  1523. e.preventDefault();
  1524. submitCustom();
  1525. }}
  1526. >
  1527. <input
  1528. type="number"
  1529. min={0}
  1530. max={320}
  1531. step={1}
  1532. value={customValue}
  1533. onChange={e => setCustomValue(e.target.value)}
  1534. placeholder="Custom"
  1535. 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"
  1536. />
  1537. <button
  1538. type="submit"
  1539. disabled={isPending || customValue.trim() === ''}
  1540. 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"
  1541. >
  1542. Set
  1543. </button>
  1544. </form>
  1545. </div>
  1546. );
  1547. }
  1548. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1549. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1550. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1551. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1552. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1553. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1554. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1555. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1556. };
  1557. /** Classify a printer into one of the UI status buckets. */
  1558. function classifyPrinterStatus(
  1559. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1560. ): PrinterState {
  1561. if (!status?.connected) return 'offline';
  1562. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1563. if (hmsErrors.length > 0) return 'error';
  1564. switch (status.state) {
  1565. case 'RUNNING': return 'printing';
  1566. case 'PAUSE': return 'paused';
  1567. case 'FINISH': return 'finished';
  1568. // FAILED without an active HMS error is the printer's terminal state after
  1569. // any unsuccessful end — including user-cancellations. Treat the same as
  1570. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1571. // HMS code is actually attached (handled by the early-return above).
  1572. case 'FAILED': return 'finished';
  1573. default: return 'idle';
  1574. }
  1575. }
  1576. /**
  1577. * Get human-readable status display text for a printer.
  1578. * Uses stg_cur_name for detailed calibration/preparation stages,
  1579. * otherwise formats the gcode_state nicely.
  1580. */
  1581. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1582. // If we have a specific stage name (calibration, heating, etc.), use it
  1583. if (stg_cur_name) {
  1584. return stg_cur_name;
  1585. }
  1586. // Format the gcode_state nicely
  1587. switch (state) {
  1588. case 'RUNNING':
  1589. return 'Printing';
  1590. case 'PAUSE':
  1591. return 'Paused';
  1592. case 'FINISH':
  1593. return 'Finished';
  1594. case 'FAILED':
  1595. return 'Failed';
  1596. case 'IDLE':
  1597. return 'Idle';
  1598. default:
  1599. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1600. }
  1601. }
  1602. // Bambu models that ship with an enclosure chamber fan (firmware field
  1603. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1604. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1605. // widget is hidden in fanItems instead of rendered greyed-out.
  1606. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1607. 'X1C',
  1608. 'X1',
  1609. 'X1E',
  1610. 'X2D',
  1611. 'P1S',
  1612. 'P2S',
  1613. 'H2D',
  1614. 'H2D Pro',
  1615. 'H2C',
  1616. 'H2S',
  1617. ]);
  1618. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1619. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1620. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1621. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1622. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1623. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1624. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1625. 'P2S',
  1626. 'X2D',
  1627. ]);
  1628. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1629. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1630. // • User-defined friendly name (editable, protected by printers:update)
  1631. // • AMS serial number
  1632. // • AMS firmware version
  1633. export function AmsNameHoverCard({
  1634. ams,
  1635. printerId,
  1636. label,
  1637. amsLabels,
  1638. canEdit,
  1639. onSaved,
  1640. children,
  1641. }: {
  1642. ams: import('../api/client').AMSUnit;
  1643. printerId: number;
  1644. label: string; // auto-generated label, e.g. "AMS-A"
  1645. amsLabels?: Record<number, string>;
  1646. canEdit: boolean;
  1647. onSaved: () => void;
  1648. children: React.ReactNode;
  1649. }) {
  1650. const { t } = useTranslation();
  1651. const [isVisible, setIsVisible] = useState(false);
  1652. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1653. const [editValue, setEditValue] = useState('');
  1654. const [isSaving, setIsSaving] = useState(false);
  1655. const [saveError, setSaveError] = useState<string | null>(null);
  1656. const [isInputFocused, setIsInputFocused] = useState(false);
  1657. const triggerRef = useRef<HTMLDivElement>(null);
  1658. const cardRef = useRef<HTMLDivElement>(null);
  1659. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1660. useEffect(() => {
  1661. if (isVisible) {
  1662. setEditValue(amsLabels?.[ams.id] ?? '');
  1663. setSaveError(null);
  1664. requestAnimationFrame(() => {
  1665. if (triggerRef.current && cardRef.current) {
  1666. const rect = triggerRef.current.getBoundingClientRect();
  1667. const spaceAbove = rect.top - 56;
  1668. const spaceBelow = window.innerHeight - rect.bottom;
  1669. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1670. }
  1671. });
  1672. }
  1673. }, [isVisible, amsLabels, ams.id]);
  1674. const handleMouseEnter = () => {
  1675. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1676. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1677. };
  1678. const handleMouseLeave = () => {
  1679. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1680. if (!isInputFocused) {
  1681. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1682. }
  1683. };
  1684. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1685. const handleSave = async () => {
  1686. if (!canEdit) return;
  1687. setIsSaving(true);
  1688. setSaveError(null);
  1689. try {
  1690. const trimmed = editValue.trim();
  1691. if (trimmed) {
  1692. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1693. } else {
  1694. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1695. }
  1696. onSaved();
  1697. setIsVisible(false);
  1698. } catch (err) {
  1699. setSaveError(err instanceof Error ? err.message : String(err));
  1700. } finally {
  1701. setIsSaving(false);
  1702. }
  1703. };
  1704. const handleClear = async () => {
  1705. if (!canEdit) return;
  1706. setIsSaving(true);
  1707. setSaveError(null);
  1708. try {
  1709. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1710. onSaved();
  1711. setIsVisible(false);
  1712. } catch (err) {
  1713. setSaveError(err instanceof Error ? err.message : String(err));
  1714. } finally {
  1715. setIsSaving(false);
  1716. }
  1717. };
  1718. return (
  1719. <div
  1720. ref={triggerRef}
  1721. className="relative inline-block"
  1722. onMouseEnter={handleMouseEnter}
  1723. onMouseLeave={handleMouseLeave}
  1724. >
  1725. {children}
  1726. {isVisible && (
  1727. <div
  1728. ref={cardRef}
  1729. className={`
  1730. absolute left-0 z-50
  1731. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1732. animate-in fade-in-0 zoom-in-95 duration-150
  1733. `}
  1734. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1735. onMouseEnter={handleMouseEnter}
  1736. onMouseLeave={handleMouseLeave}
  1737. >
  1738. <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">
  1739. {/* AMS auto-label */}
  1740. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1741. {/* Serial number */}
  1742. <div className="flex items-center justify-between gap-2">
  1743. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1744. {t('printers.amsPopup.serialNumber')}
  1745. </span>
  1746. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1747. </div>
  1748. {/* Firmware version */}
  1749. <div className="flex items-center justify-between gap-2">
  1750. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1751. {t('printers.amsPopup.firmwareVersion')}
  1752. </span>
  1753. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1754. </div>
  1755. {/* Friendly name editor */}
  1756. <div className="space-y-1">
  1757. <div className="flex items-center gap-2">
  1758. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1759. {t('printers.amsPopup.friendlyName')}
  1760. </span>
  1761. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1762. </div>
  1763. <input
  1764. type="text"
  1765. value={editValue}
  1766. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1767. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1768. onFocus={() => setIsInputFocused(true)}
  1769. onBlur={() => {
  1770. setIsInputFocused(false);
  1771. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1772. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1773. }}
  1774. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1775. disabled={!canEdit}
  1776. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1777. 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"
  1778. maxLength={100}
  1779. />
  1780. {canEdit && (
  1781. <div className="space-y-1">
  1782. {saveError && (
  1783. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1784. )}
  1785. <div className="flex gap-1 justify-end">
  1786. <button
  1787. onClick={handleSave}
  1788. disabled={isSaving}
  1789. 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"
  1790. >
  1791. {t('printers.amsPopup.save')}
  1792. </button>
  1793. {amsLabels?.[ams.id] && (
  1794. <button
  1795. onClick={handleClear}
  1796. disabled={isSaving}
  1797. 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"
  1798. >
  1799. {t('printers.amsPopup.clear')}
  1800. </button>
  1801. )}
  1802. </div>
  1803. </div>
  1804. )}
  1805. </div>
  1806. </div>
  1807. </div>
  1808. )}
  1809. </div>
  1810. );
  1811. }
  1812. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1813. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1814. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1815. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1816. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1817. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1818. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1819. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1820. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1821. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1822. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1823. };
  1824. // How much the printer card's body type and icons grow at each card size
  1825. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1826. // 1.0 and an existing install looks identical until the user picks L or XL --
  1827. // the same control the request asked to have this follow.
  1828. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1829. // The scaled sizes, handed to the card subtree as custom properties. Every
  1830. // converted class names its old fixed value as the fallback, so anything that
  1831. // renders outside a card root -- the portalled temperature popover -- keeps
  1832. // exactly the size it has today.
  1833. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1834. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1835. // Rounded to a tenth so the values stay readable in devtools.
  1836. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1837. return {
  1838. '--pc-t8': px(8),
  1839. '--pc-t9': px(9),
  1840. '--pc-t10': px(10),
  1841. '--pc-t11': px(11),
  1842. '--pc-i2': px(8),
  1843. '--pc-i25': px(10),
  1844. '--pc-i3': px(12),
  1845. '--pc-i35': px(14),
  1846. '--pc-i4': px(16),
  1847. '--pc-i5': px(20),
  1848. '--pc-i7': px(28),
  1849. } as React.CSSProperties;
  1850. }
  1851. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1852. const { t } = useTranslation();
  1853. const queryClient = useQueryClient();
  1854. const { showToast } = useToast();
  1855. // One fleet-wide query shared by every card, not one per card: the list is
  1856. // nearly always empty and a 20-printer fleet would otherwise make 20
  1857. // requests every 30s. React Query dedupes on the key.
  1858. const { data: scheduled = [] } = useQuery({
  1859. queryKey: SCHEDULED_DRYINGS_KEY,
  1860. queryFn: () => api.listScheduledDryings(),
  1861. refetchInterval: 30_000,
  1862. });
  1863. // The live AMS status reports a starting cycle well before the next poll;
  1864. // refetch so a just-dispatched schedule doesn't linger as pending.
  1865. useEffect(() => {
  1866. if (dryingActive) {
  1867. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1868. }
  1869. }, [dryingActive, queryClient]);
  1870. const cancelMutation = useMutation({
  1871. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1872. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1873. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1874. });
  1875. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1876. // old firmware on a printer that was offline at schedule time), and without
  1877. // this the run just vanishes with only the backend log saying why.
  1878. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1879. if (rows.length === 0) return null;
  1880. return (
  1881. <div className="mt-2 space-y-1">
  1882. {rows.map(s => {
  1883. const failed = s.status === 'failed';
  1884. const reasonKey = waitingReasonKey(s.waiting_reason);
  1885. const failedKey = failedReasonKey(s.error_code);
  1886. return (
  1887. <div
  1888. key={s.id}
  1889. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1890. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1891. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1892. }`}
  1893. >
  1894. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1895. {failed ? (
  1896. t('printers.drying.scheduleFailedReason', {
  1897. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1898. })
  1899. ) : (
  1900. <>
  1901. {s.start_after
  1902. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1903. : t('printers.drying.scheduledAsap')}
  1904. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1905. </>
  1906. )}
  1907. </span>
  1908. <button
  1909. onClick={() => cancelMutation.mutate(s.id)}
  1910. disabled={cancelMutation.isPending}
  1911. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1912. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1913. >
  1914. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1915. </button>
  1916. </div>
  1917. );
  1918. })}
  1919. </div>
  1920. );
  1921. }
  1922. function PrinterCard({
  1923. printer,
  1924. hideIfDisconnected,
  1925. maintenanceInfo,
  1926. viewMode = 'expanded',
  1927. cardSize = 2,
  1928. amsThresholds,
  1929. spoolmanEnabled = false,
  1930. linkedSpools,
  1931. spoolmanUrl,
  1932. spoolmanSyncMode,
  1933. onGetAssignment,
  1934. onUnassignSpool,
  1935. spoolmanSpools,
  1936. spoolmanSlotAssignments,
  1937. spoolmanLoading = false,
  1938. onUnassignSpoolmanSpool,
  1939. timeFormat = 'system',
  1940. cameraViewMode = 'window',
  1941. onOpenEmbeddedCamera,
  1942. onSelectCameraViewMode,
  1943. checkPrinterFirmware = true,
  1944. dryingPresets = DRYING_PRESETS,
  1945. requirePlateClear = false,
  1946. selectionMode = false,
  1947. isSelected = false,
  1948. onToggleSelect,
  1949. onOpenCompactCard,
  1950. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1951. bedTempPresets = BED_TEMP_DEFAULTS,
  1952. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1953. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1954. aiDetectionEnabled = false,
  1955. aiDetection,
  1956. aiLastError = null,
  1957. }: {
  1958. printer: Printer;
  1959. hideIfDisconnected?: boolean;
  1960. maintenanceInfo?: PrinterMaintenanceInfo;
  1961. viewMode?: ViewMode;
  1962. cardSize?: number;
  1963. amsThresholds?: {
  1964. humidityGood: number;
  1965. humidityFair: number;
  1966. tempGood: number;
  1967. tempFair: number;
  1968. };
  1969. spoolmanEnabled?: boolean;
  1970. hasUnlinkedSpools?: boolean;
  1971. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1972. spoolmanUrl?: string | null;
  1973. spoolmanSyncMode?: string | null;
  1974. spoolAssignments?: SpoolAssignment[];
  1975. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1976. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1977. spoolmanSpools?: InventorySpool[];
  1978. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1979. spoolmanLoading?: boolean;
  1980. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1981. timeFormat?: 'system' | '12h' | '24h';
  1982. cameraViewMode?: CameraViewMode;
  1983. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1984. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  1985. checkPrinterFirmware?: boolean;
  1986. dryingPresets?: Record<string, DryingPreset>;
  1987. requirePlateClear?: boolean;
  1988. selectionMode?: boolean;
  1989. isSelected?: boolean;
  1990. onToggleSelect?: (id: number) => void;
  1991. onOpenCompactCard?: (id: number) => void;
  1992. nozzleTempPresets?: readonly [number, number, number];
  1993. bedTempPresets?: readonly [number, number, number];
  1994. chamberTempPresets?: readonly [number, number, number];
  1995. fanSpeedPresets?: readonly [number, number, number];
  1996. aiDetectionEnabled?: boolean;
  1997. aiDetection?: AiDetection;
  1998. aiLastError?: string | null;
  1999. }) {
  2000. const { t } = useTranslation();
  2001. const queryClient = useQueryClient();
  2002. const navigate = useNavigate();
  2003. const { showToast } = useToast();
  2004. const { hasPermission, canModify } = useAuth();
  2005. const [showMenu, setShowMenu] = useState(false);
  2006. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  2007. const [deleteArchives, setDeleteArchives] = useState(true);
  2008. const [showEditModal, setShowEditModal] = useState(false);
  2009. const [showFileManager, setShowFileManager] = useState(false);
  2010. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  2011. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  2012. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  2013. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  2014. const [showHMSModal, setShowHMSModal] = useState(false);
  2015. // #1546: AI failure detection modal — opens from the AI badge.
  2016. const [showAiModal, setShowAiModal] = useState(false);
  2017. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  2018. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  2019. // External spool visibility (#1782) — browser-local, per printer. Read once
  2020. // per card; the toggle that writes it is the only thing that changes it.
  2021. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2022. isExternalSpoolHidden(printer.id),
  2023. );
  2024. const toggleExternalSpool = useCallback(() => {
  2025. setExternalSpoolHidden((prev) => {
  2026. const next = !prev;
  2027. persistExternalSpoolHidden(printer.id, next);
  2028. return next;
  2029. });
  2030. }, [printer.id]);
  2031. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2032. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2033. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2034. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2035. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2036. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2037. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2038. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2039. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2040. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2041. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2042. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2043. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2044. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2045. // AMS drying popover state: which AMS unit has the popover open
  2046. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2047. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2048. const [dryingFilament, setDryingFilament] = useState('PLA');
  2049. const [dryingTemp, setDryingTemp] = useState(50);
  2050. const [dryingDuration, setDryingDuration] = useState(4);
  2051. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2052. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2053. // go through scheduleDryingMutation.
  2054. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2055. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2056. const [dryingStartAt, setDryingStartAt] = useState('');
  2057. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2058. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2059. // Reset every field the popover owns, including the start mode. Leaving the
  2060. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2061. // the next open, by then in the past, and the POST rejected it.
  2062. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2063. const firstTray = ams.tray.find(t => t.tray_type);
  2064. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2065. // Only reachable if a custom preset set dropped PLA itself.
  2066. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2067. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2068. setDryingFilament(filType);
  2069. setDryingTemp(preset[moduleType] || preset.n3f);
  2070. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2071. setDryingRotateTray(false);
  2072. setDryingStartMode('now');
  2073. setDryingDelayMinutes(120);
  2074. setDryingStartAt('');
  2075. setDryingPopoverModuleType(ams.module_type);
  2076. setDryingPopoverAmsId(ams.id);
  2077. setDryingPopoverAnchor(trigger);
  2078. }, [dryingPresets]);
  2079. // Re-measure on resize/scroll so the popover and its arrow track the
  2080. // flame button, like IndicatorControlPopover.
  2081. useLayoutEffect(() => {
  2082. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2083. const measure = () => {
  2084. setDryingPopoverPos(computePopoverPosition({
  2085. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2086. popoverWidth: DRYING_POPOVER_WIDTH,
  2087. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2088. horizontalAlign: 'center',
  2089. }));
  2090. };
  2091. measure();
  2092. window.addEventListener('resize', measure);
  2093. window.addEventListener('scroll', measure, true);
  2094. return () => {
  2095. window.removeEventListener('resize', measure);
  2096. window.removeEventListener('scroll', measure, true);
  2097. };
  2098. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2099. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2100. // Whether the click hitting the backdrop is the one that dismissed the
  2101. // native datetime picker (see the backdrop's onMouseDown).
  2102. const dryingBackdropSkipCloseRef = useRef(false);
  2103. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2104. // an object rather than a bare id so restarting drying on the SAME unit produces
  2105. // a new identity and rearms the timeout below.
  2106. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2107. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2108. const [isDropUploading, setIsDropUploading] = useState(false);
  2109. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2110. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2111. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2112. // inside the card would have to open upward into the card body; anchored to
  2113. // the viewport it escapes the card and the grid's scroll container both.
  2114. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2115. const dragCounterRef = useRef(0);
  2116. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2117. amsId: number;
  2118. amsLabel: string;
  2119. mode: 'humidity' | 'temperature';
  2120. } | null>(null);
  2121. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2122. initialKind: HeaterSensorKind;
  2123. availableKinds: HeaterSensorKind[];
  2124. } | null>(null);
  2125. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2126. tagUid: string;
  2127. trayUuid: string;
  2128. printerId: number;
  2129. amsId: number;
  2130. trayId: number;
  2131. } | null>(null);
  2132. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2133. printerId: number;
  2134. amsId: number;
  2135. trayId: number;
  2136. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2137. } | null>(null);
  2138. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2139. amsId: number;
  2140. trayId: number;
  2141. trayCount: number;
  2142. trayType?: string;
  2143. trayColor?: string;
  2144. traySubBrands?: string;
  2145. trayInfoIdx?: string;
  2146. extruderId?: number;
  2147. caliIdx?: number | null;
  2148. savedPresetId?: string;
  2149. } | null>(null);
  2150. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2151. const [plateCheckResult, setPlateCheckResult] = useState<{
  2152. is_empty: boolean;
  2153. confidence: number;
  2154. difference_percent: number;
  2155. message: string;
  2156. debug_image_url?: string;
  2157. needs_calibration: boolean;
  2158. light_warning?: boolean;
  2159. reference_count?: number;
  2160. max_references?: number;
  2161. roi?: { x: number; y: number; w: number; h: number };
  2162. } | null>(null);
  2163. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2164. const [isCalibrating, setIsCalibrating] = useState(false);
  2165. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2166. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2167. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2168. const { data: status } = useQuery({
  2169. queryKey: ['printerStatus', printer.id],
  2170. queryFn: () => api.getPrinterStatus(printer.id),
  2171. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2172. });
  2173. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2174. const { data: firmwareInfo } = useQuery({
  2175. queryKey: ['firmwareUpdate', printer.id],
  2176. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2177. staleTime: 5 * 60 * 1000,
  2178. refetchInterval: 5 * 60 * 1000,
  2179. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2180. });
  2181. // Collect unique tray_info_idx values for cloud filament info lookup
  2182. const trayInfoIds = useMemo(() => {
  2183. const ids = new Set<string>();
  2184. if (status?.ams) {
  2185. for (const ams of status.ams) {
  2186. for (const tray of ams.tray || []) {
  2187. if (tray.tray_info_idx) {
  2188. ids.add(tray.tray_info_idx);
  2189. }
  2190. }
  2191. }
  2192. }
  2193. for (const vt of status?.vt_tray ?? []) {
  2194. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2195. }
  2196. if (status?.nozzle_rack) {
  2197. for (const slot of status.nozzle_rack) {
  2198. if (slot.filament_id) {
  2199. ids.add(slot.filament_id);
  2200. }
  2201. }
  2202. }
  2203. return Array.from(ids);
  2204. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2205. // Collect loaded filament types for queue widget filtering
  2206. const loadedFilamentTypes = useMemo(() => {
  2207. const types = new Set<string>();
  2208. if (status?.ams) {
  2209. for (const ams of status.ams) {
  2210. for (const tray of ams.tray || []) {
  2211. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2212. }
  2213. }
  2214. }
  2215. for (const vt of status?.vt_tray ?? []) {
  2216. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2217. }
  2218. return types;
  2219. }, [status?.ams, status?.vt_tray]);
  2220. // Collect loaded filament type+color pairs for queue widget override matching
  2221. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2222. const loadedFilaments = useMemo(() => {
  2223. const filaments = new Set<string>();
  2224. if (status?.ams) {
  2225. for (const ams of status.ams) {
  2226. for (const tray of ams.tray || []) {
  2227. if (tray.tray_type && tray.tray_color) {
  2228. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2229. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2230. }
  2231. }
  2232. }
  2233. }
  2234. for (const vt of status?.vt_tray ?? []) {
  2235. if (vt.tray_type && vt.tray_color) {
  2236. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2237. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2238. }
  2239. }
  2240. return filaments;
  2241. }, [status?.ams, status?.vt_tray]);
  2242. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2243. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2244. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2245. const loadedVariants = useMemo(() => {
  2246. const variants = new Set<string>();
  2247. if (status?.ams) {
  2248. for (const ams of status.ams) {
  2249. for (const tray of ams.tray || []) {
  2250. if (tray.tray_type && tray.tray_color) {
  2251. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2252. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2253. }
  2254. }
  2255. }
  2256. }
  2257. for (const vt of status?.vt_tray ?? []) {
  2258. if (vt.tray_type && vt.tray_color) {
  2259. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2260. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2261. }
  2262. }
  2263. return variants;
  2264. }, [status?.ams, status?.vt_tray]);
  2265. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2266. const { data: filamentInfo } = useQuery({
  2267. queryKey: ['filamentInfo', trayInfoIds],
  2268. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2269. enabled: trayInfoIds.length > 0,
  2270. staleTime: 5 * 60 * 1000, // 5 minutes
  2271. });
  2272. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2273. const { data: slotPresets } = useQuery({
  2274. queryKey: ['slotPresets', printer.id],
  2275. queryFn: () => api.getSlotPresets(printer.id),
  2276. staleTime: 2 * 60 * 1000, // 2 minutes
  2277. });
  2278. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2279. // Only queried when there's a running print backed by an archive; shared
  2280. // React Query cache with the Queue / Archives pages keeps it cheap.
  2281. const activeArchiveId =
  2282. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2283. const { data: activeArchivePlates } = useQuery({
  2284. queryKey: ['archive-plates', activeArchiveId],
  2285. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2286. enabled: activeArchiveId != null,
  2287. staleTime: 5 * 60 * 1000,
  2288. });
  2289. const activePlateLabel = (() => {
  2290. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2291. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2292. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2293. })();
  2294. // Fetch user-defined AMS friendly names from the database
  2295. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2296. queryKey: ['amsLabels', printer.id],
  2297. queryFn: () => api.getAmsLabels(printer.id),
  2298. staleTime: 5 * 60 * 1000, // 5 minutes
  2299. });
  2300. // Cache WiFi signal to prevent it disappearing on updates
  2301. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2302. useEffect(() => {
  2303. if (status?.wifi_signal != null) {
  2304. setCachedWifiSignal(status.wifi_signal);
  2305. }
  2306. }, [status?.wifi_signal]);
  2307. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2308. // Cache connected state to prevent flicker when status briefly becomes undefined
  2309. const cachedConnected = useRef<boolean | undefined>(undefined);
  2310. useEffect(() => {
  2311. if (status?.connected !== undefined) {
  2312. cachedConnected.current = status.connected;
  2313. }
  2314. }, [status?.connected]);
  2315. const isConnected = status?.connected ?? cachedConnected.current;
  2316. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2317. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2318. useEffect(() => {
  2319. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2320. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2321. }
  2322. }, [status?.ams_extruder_map]);
  2323. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2324. ? status.ams_extruder_map
  2325. : cachedAmsExtruderMap.current;
  2326. // Same caching for the Filament Track Switch inlet bindings, for the same
  2327. // reason: a partial MQTT frame briefly empties the map and the badges would
  2328. // otherwise blink out.
  2329. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2330. useEffect(() => {
  2331. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2332. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2333. }
  2334. }, [status?.ams_switch_inlet]);
  2335. const ftsInstalled = status?.fila_switch?.installed === true;
  2336. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2337. ? status.ams_switch_inlet
  2338. : cachedAmsSwitchInlet.current;
  2339. // Cache AMS data to prevent it disappearing on idle/offline printers
  2340. const cachedAmsData = useRef<AMSUnit[]>([]);
  2341. useEffect(() => {
  2342. if (status?.ams && status.ams.length > 0) {
  2343. cachedAmsData.current = status.ams;
  2344. }
  2345. }, [status?.ams]);
  2346. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2347. // #2532: the K-profile line only exists on slots the printer has actually
  2348. // calibrated. The AMS units and the external-spool group are flex siblings in
  2349. // one row, so on a card that shows a value anywhere, the slots without one
  2350. // reserve the same height -- otherwise their fill bars sit a line above their
  2351. // neighbours'. A card with no calibrated slot at all is unaffected.
  2352. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2353. || (status?.vt_tray ?? []).some(tray => tray.k);
  2354. // Confirm a drying cycle actually started (#2533). Firmware answers
  2355. // ams_filament_drying with result=success even when it then silently declines,
  2356. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2357. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2358. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2359. // means the printer took the command and dropped it.
  2360. useEffect(() => {
  2361. if (!dryStartWatch) return;
  2362. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2363. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2364. }, [dryStartWatch, amsData]);
  2365. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2366. // otherwise rearm the timeout on every frame, so it would never elapse.
  2367. useEffect(() => {
  2368. if (!dryStartWatch) return;
  2369. const timer = setTimeout(() => {
  2370. setDryStartWatch(null);
  2371. showToast(t('printers.drying.toastNotStarted'), 'error');
  2372. }, DRY_START_CONFIRM_MS);
  2373. return () => clearTimeout(timer);
  2374. }, [dryStartWatch, showToast, t]);
  2375. // Cache tray_now to prevent flickering when undefined values come in
  2376. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2377. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2378. const cachedTrayNow = useRef<number | undefined>(undefined);
  2379. const currentTrayNow = status?.tray_now;
  2380. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2381. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2382. cachedTrayNow.current = currentTrayNow;
  2383. } else if (currentTrayNow === 255) {
  2384. cachedTrayNow.current = undefined;
  2385. }
  2386. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2387. ? currentTrayNow
  2388. : cachedTrayNow.current;
  2389. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2390. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2391. // expectedTray = the slot the firmware now expects filament in
  2392. // previousTray = the slot that ran out
  2393. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2394. // so these are often different — the graphic highlights the expected one.
  2395. const expectedTray = status?.expected_tray ?? null;
  2396. const previousTray = status?.previous_tray ?? null;
  2397. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2398. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2399. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2400. if (globalId === null) return null;
  2401. if (globalId === 254) return t('printers.expectedSlot.external');
  2402. if (globalId >= 128 && globalId <= 135) {
  2403. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2404. }
  2405. const amsId = Math.floor(globalId / 4);
  2406. const slot = globalId % 4;
  2407. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2408. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2409. };
  2410. const runoutGuidance = status?.state === 'PAUSE'
  2411. ? {
  2412. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2413. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2414. }
  2415. : null;
  2416. // Fetch smart plug for this printer
  2417. const { data: smartPlug } = useQuery({
  2418. queryKey: ['smartPlugByPrinter', printer.id],
  2419. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2420. });
  2421. // Fetch script plugs for this printer (for multi-device control)
  2422. const { data: scriptPlugs } = useQuery({
  2423. queryKey: ['scriptPlugsByPrinter', printer.id],
  2424. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2425. });
  2426. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2427. const { data: plugStatus } = useQuery({
  2428. queryKey: ['smartPlugStatus', smartPlug?.id],
  2429. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2430. enabled: !!smartPlug,
  2431. refetchInterval: 10000, // 10 seconds for real-time power display
  2432. });
  2433. // Fetch queue count for this printer
  2434. const { data: queueItems } = useQuery({
  2435. queryKey: ['queue', printer.id, 'pending'],
  2436. queryFn: () => api.getQueue(printer.id, 'pending'),
  2437. });
  2438. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2439. // so the badge only shows on printers that can actually run the queued jobs.
  2440. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2441. const queueCount = useMemo(() => {
  2442. if (!queueItems?.length) return 0;
  2443. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2444. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2445. // Fetch currently printing queue item to show who started it (Issue #206)
  2446. const { data: printingQueueItems } = useQuery({
  2447. queryKey: ['queue', printer.id, 'printing'],
  2448. queryFn: () => api.getQueue(printer.id, 'printing'),
  2449. enabled: status?.state === 'RUNNING',
  2450. });
  2451. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2452. const { data: reprintUser } = useQuery({
  2453. queryKey: ['currentPrintUser', printer.id],
  2454. queryFn: () => api.getCurrentPrintUser(printer.id),
  2455. enabled: status?.state === 'RUNNING',
  2456. });
  2457. // Combine both sources: queue item user takes precedence, then reprint user
  2458. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2459. // Fetch last completed print for this printer
  2460. const { data: lastPrints } = useQuery({
  2461. queryKey: ['archives', printer.id, 'last'],
  2462. queryFn: () => api.getArchives(printer.id, 1, 0),
  2463. enabled: status?.connected && status?.state !== 'RUNNING',
  2464. });
  2465. const lastPrint = lastPrints?.[0];
  2466. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2467. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2468. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2469. // gate is up and the just-finished print asked for a verdict, offer
  2470. // Good/Reject right where the operator releases the plate. Releasing the
  2471. // plate without answering stays possible — the two are orthogonal (though
  2472. // the confirm_default_good_on_plate_clear setting can couple them).
  2473. // Only offered to whoever may record it: the PATCH checks archives:update
  2474. // against the archive's owner, so for anyone else the pair could only fail.
  2475. const pendingConfirmArchive =
  2476. lastPrint &&
  2477. lastPrint.status === 'completed' &&
  2478. lastPrint.confirm_requested &&
  2479. lastPrint.user_verdict == null &&
  2480. canModify('archives', 'update', lastPrint.created_by_id)
  2481. ? lastPrint
  2482. : null;
  2483. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2484. // Auto Power Off the printer is powered down exactly when the operator clears the
  2485. // plate. Hiding the control there left no way to release the gate (#2864).
  2486. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2487. const activePrintName = status?.current_print && isPrintingOrPaused
  2488. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2489. : null;
  2490. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2491. useEffect(() => {
  2492. if (activePrintName) {
  2493. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2494. } else if (!needsPlateClear) {
  2495. setRetainedPrintJob(null);
  2496. }
  2497. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2498. const plateStatus = (() => {
  2499. // Connected-only because the pill's only render site sits inside the live-status
  2500. // panel. For a powered-down printer the plate-clear button itself carries the
  2501. // state — see the standalone slot below the status block (#2864).
  2502. if (!requirePlateClear || !status?.connected) return null;
  2503. if (isPrintingOrPaused) {
  2504. return {
  2505. label: t('printers.plateStatus.inUse'),
  2506. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2507. };
  2508. }
  2509. if (status.awaiting_plate_clear) {
  2510. return {
  2511. label: t('printers.plateStatus.notCleared'),
  2512. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2513. };
  2514. }
  2515. return {
  2516. label: t('printers.plateStatus.cleared'),
  2517. className: 'bg-status-ok/20 text-status-ok',
  2518. };
  2519. })();
  2520. const plateStatusPill = plateStatus ? (
  2521. <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}`}>
  2522. {plateStatus.label}
  2523. </span>
  2524. ) : null;
  2525. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2526. const shouldHide = hideIfDisconnected && isConnected === false;
  2527. const deleteMutation = useMutation({
  2528. mutationFn: (options: { deleteArchives: boolean }) =>
  2529. api.deletePrinter(printer.id, options.deleteArchives),
  2530. onSuccess: () => {
  2531. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2532. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2533. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2534. },
  2535. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2536. });
  2537. const connectMutation = useMutation({
  2538. mutationFn: () => api.connectPrinter(printer.id),
  2539. onSuccess: () => {
  2540. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2541. },
  2542. });
  2543. const forceRefreshMutation = useMutation({
  2544. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2545. onSuccess: () => {
  2546. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2547. showToast(t('printers.forceRefreshSuccess'), 'success');
  2548. },
  2549. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2550. });
  2551. const unlinkSpoolMutation = useMutation({
  2552. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2553. onSuccess: (result) => {
  2554. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2555. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2556. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2557. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2558. },
  2559. onError: (error: Error) => {
  2560. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2561. },
  2562. });
  2563. // AMS drying mutations
  2564. const startDryingMutation = useMutation({
  2565. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2566. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2567. onSuccess: (_data, { amsId }) => {
  2568. setDryingPopoverAmsId(null);
  2569. setDryStartWatch({ amsId });
  2570. // "Command sent", not "drying started" — at this point the printer has only
  2571. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2572. // the cycle is genuinely live; the watcher below covers the case where it
  2573. // never appears.
  2574. showToast(t('printers.drying.toastCommandSent'), 'success');
  2575. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2576. },
  2577. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2578. });
  2579. // Scheduled (delayed / at-time) drying runs (#2638)
  2580. const scheduleDryingMutation = useMutation({
  2581. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2582. api.createScheduledDrying({
  2583. printer_id: printer.id,
  2584. ams_id: params.amsId,
  2585. temp: params.temp,
  2586. duration_hours: params.duration,
  2587. filament: params.filament,
  2588. rotate_tray: params.rotateTray,
  2589. start_after: params.startAfter,
  2590. }),
  2591. onSuccess: () => {
  2592. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2593. setDryingPopoverAmsId(null);
  2594. },
  2595. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2596. });
  2597. const stopDryingMutation = useMutation({
  2598. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2599. onSuccess: () => {
  2600. setDryStartWatch(null);
  2601. showToast(t('printers.drying.toastStopped'), 'success');
  2602. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2603. },
  2604. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2605. });
  2606. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2607. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2608. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2609. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2610. // showing the old backup state until the user reopens it.
  2611. const setAmsBackupMutation = useMutation({
  2612. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2613. onSuccess: (_data, enabled) => {
  2614. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2615. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2616. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2617. },
  2618. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2619. });
  2620. // Smart plug control mutations
  2621. const powerControlMutation = useMutation({
  2622. mutationFn: (action: 'on' | 'off') =>
  2623. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2624. onSuccess: () => {
  2625. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2626. },
  2627. });
  2628. const toggleAutoOffMutation = useMutation({
  2629. mutationFn: (enabled: boolean) =>
  2630. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2631. onSuccess: () => {
  2632. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2633. // Also invalidate the smart-plugs list to keep Settings page in sync
  2634. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2635. },
  2636. });
  2637. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2638. const runScriptMutation = useMutation({
  2639. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2640. onSuccess: () => {
  2641. showToast(t('printers.toast.scriptTriggered'));
  2642. },
  2643. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2644. });
  2645. // Print control mutations
  2646. const stopPrintMutation = useMutation({
  2647. mutationFn: () => api.stopPrint(printer.id),
  2648. onSuccess: () => {
  2649. showToast(t('printers.toast.printStopped'));
  2650. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2651. },
  2652. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2653. });
  2654. const pausePrintMutation = useMutation({
  2655. mutationFn: () => api.pausePrint(printer.id),
  2656. onSuccess: () => {
  2657. showToast(t('printers.toast.printPaused'));
  2658. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2659. },
  2660. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2661. });
  2662. const resumePrintMutation = useMutation({
  2663. mutationFn: () => api.resumePrint(printer.id),
  2664. onSuccess: () => {
  2665. showToast(t('printers.toast.printResumed'));
  2666. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2667. },
  2668. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2669. });
  2670. const clearPlateMutation = useMutation({
  2671. mutationFn: () => api.clearPlate(printer.id),
  2672. onSuccess: () => {
  2673. showToast(t('queue.clearPlateSuccess'));
  2674. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2675. old ? { ...old, awaiting_plate_clear: false } : old
  2676. );
  2677. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2678. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2679. },
  2680. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2681. });
  2682. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2683. // reject goes through the dialog for the optional reason + reprint.
  2684. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2685. // Only "good" is answered on the card. A reject wants a reason and possibly
  2686. // a reprint, so that button opens the dialog instead — and the parameter
  2687. // says as much, rather than accepting a verdict this path cannot send and
  2688. // then reporting it as good.
  2689. const cardVerdictMutation = useMutation({
  2690. mutationFn: (verdict: 'good') =>
  2691. api.updateArchive(pendingConfirmArchive!.id, {
  2692. user_verdict: verdict,
  2693. user_verdict_source: 'printer_card',
  2694. }),
  2695. onSuccess: () => {
  2696. showToast(t('confirmOutcome.savedGood'), 'success');
  2697. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2698. },
  2699. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2700. });
  2701. // Rendered from two places: inside the live-status block for a connected printer,
  2702. // and standalone below it for a powered-down one, whose status block isn't rendered
  2703. // at all (#2864). Shared so the two can't drift apart.
  2704. const expandedClearPlateButton = (
  2705. <>
  2706. {pendingConfirmArchive && (
  2707. <div className="mt-2 flex items-center gap-1.5">
  2708. <span
  2709. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2710. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2711. >
  2712. {t('confirmOutcome.cardPrompt')}
  2713. </span>
  2714. <button
  2715. type="button"
  2716. onClick={() => setShowConfirmOutcome(true)}
  2717. disabled={cardVerdictMutation.isPending}
  2718. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2719. title={t('confirmOutcome.reject')}
  2720. >
  2721. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2722. </button>
  2723. <button
  2724. type="button"
  2725. onClick={() => cardVerdictMutation.mutate('good')}
  2726. disabled={cardVerdictMutation.isPending}
  2727. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2728. title={t('confirmOutcome.good')}
  2729. >
  2730. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2731. </button>
  2732. </div>
  2733. )}
  2734. <button
  2735. type="button"
  2736. onClick={() => clearPlateMutation.mutate()}
  2737. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2738. 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"
  2739. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2740. >
  2741. {clearPlateMutation.isPending ? (
  2742. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2743. ) : (
  2744. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2745. )}
  2746. {t('printers.plateStatus.markCleared')}
  2747. </button>
  2748. {showConfirmOutcome && pendingConfirmArchive && (
  2749. <ConfirmOutcomeDialog
  2750. archiveId={pendingConfirmArchive.id}
  2751. onClose={() => setShowConfirmOutcome(false)}
  2752. />
  2753. )}
  2754. </>
  2755. );
  2756. const nozzleTemperatureMutation = useMutation({
  2757. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2758. api.setNozzleTemperature(printer.id, target, nozzle),
  2759. onSuccess: (result) => {
  2760. setStatusControlMenu(null);
  2761. showToast(result.message);
  2762. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2763. },
  2764. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2765. });
  2766. const bedTemperatureMutation = useMutation({
  2767. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2768. onSuccess: (result) => {
  2769. setStatusControlMenu(null);
  2770. showToast(result.message);
  2771. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2772. },
  2773. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2774. });
  2775. const chamberTemperatureMutation = useMutation({
  2776. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2777. onSuccess: (result) => {
  2778. setStatusControlMenu(null);
  2779. showToast(result.message);
  2780. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2781. },
  2782. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2783. });
  2784. const fanSpeedMutation = useMutation({
  2785. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2786. api.setFanSpeed(printer.id, fan, speed),
  2787. onMutate: async ({ fan, speed }) => {
  2788. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2789. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2790. const fanField = {
  2791. part: 'cooling_fan_speed',
  2792. aux: 'big_fan1_speed',
  2793. aux2: 'left_aux_fan_speed',
  2794. chamber: 'big_fan2_speed',
  2795. }[fan];
  2796. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2797. old ? { ...old, [fanField]: speed } : old
  2798. );
  2799. return { previousStatus };
  2800. },
  2801. onSuccess: (result) => {
  2802. setStatusControlMenu(null);
  2803. showToast(result.message);
  2804. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2805. },
  2806. onError: (error: Error, _variables, context) => {
  2807. if (context?.previousStatus) {
  2808. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2809. }
  2810. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2811. },
  2812. });
  2813. const selectExtruderMutation = useMutation({
  2814. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2815. onMutate: async (extruder) => {
  2816. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2817. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2818. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2819. old ? { ...old, active_extruder: extruder } : old
  2820. );
  2821. return { previousStatus };
  2822. },
  2823. onSuccess: (result) => {
  2824. setStatusControlMenu(null);
  2825. showToast(result.message);
  2826. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2827. },
  2828. onError: (error: Error, _extruder, context) => {
  2829. if (context?.previousStatus) {
  2830. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2831. }
  2832. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2833. },
  2834. });
  2835. // Chamber light mutation with optimistic update
  2836. const chamberLightMutation = useMutation({
  2837. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2838. onMutate: async (on) => {
  2839. // Cancel any outgoing refetches
  2840. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2841. // Snapshot the previous value
  2842. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2843. // Optimistically update
  2844. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2845. ...old,
  2846. chamber_light: on,
  2847. }));
  2848. return { previousStatus };
  2849. },
  2850. onSuccess: (_, on) => {
  2851. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2852. },
  2853. onError: (error: Error, _, context) => {
  2854. // Rollback on error
  2855. if (context?.previousStatus) {
  2856. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2857. }
  2858. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2859. },
  2860. });
  2861. // Print speed mutation with optimistic update
  2862. const printSpeedMutation = useMutation({
  2863. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2864. onMutate: async (mode) => {
  2865. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2866. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2867. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2868. ...old,
  2869. speed_level: mode,
  2870. }));
  2871. return { previousStatus };
  2872. },
  2873. onError: (error: Error, _, context) => {
  2874. if (context?.previousStatus) {
  2875. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2876. }
  2877. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2878. },
  2879. });
  2880. const airductMutation = useMutation({
  2881. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2882. onMutate: async (mode) => {
  2883. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2884. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2885. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2886. ...old,
  2887. airduct_mode: mode === 'cooling' ? 0 : 1,
  2888. }));
  2889. return { previousStatus };
  2890. },
  2891. onError: (error: Error, _, context) => {
  2892. if (context?.previousStatus) {
  2893. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2894. }
  2895. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2896. },
  2897. });
  2898. const bedJogMutation = useMutation({
  2899. mutationFn: ({ distance }: { distance: number }) =>
  2900. api.bedJog(printer.id, distance),
  2901. onError: (error: Error) =>
  2902. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2903. });
  2904. const xyJogMutation = useMutation({
  2905. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2906. api.xyJog(printer.id, x, y),
  2907. onError: (error: Error) =>
  2908. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2909. });
  2910. const extruderJogMutation = useMutation({
  2911. mutationFn: (distance: number) =>
  2912. api.extruderJog(printer.id, distance),
  2913. onError: (error: Error) =>
  2914. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2915. });
  2916. const homeAxesMutation = useMutation({
  2917. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2918. onSuccess: () => {
  2919. showToast(t('printers.bedJog.homingStarted'));
  2920. },
  2921. onError: (error: Error) =>
  2922. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2923. });
  2924. // Plate detection setting mutation
  2925. const plateDetectionMutation = useMutation({
  2926. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2927. onSuccess: () => {
  2928. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2929. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2930. },
  2931. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2932. });
  2933. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2934. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2935. // metrics, and the print picker — so flipping this flag puts the printer
  2936. // out of service across every consumer in one place. Used from the
  2937. // overflow menu and EditPrinterModal.
  2938. const maintenanceMutation = useMutation({
  2939. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2940. onSuccess: (_data, isActive) => {
  2941. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2942. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2943. showToast(
  2944. isActive
  2945. ? t('printers.maintenance.toastExited', { name: printer.name })
  2946. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2947. 'success',
  2948. );
  2949. },
  2950. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2951. });
  2952. // Confirm before entering maintenance on a printing printer (entering mode
  2953. // disconnects MQTT, which stops progress tracking + completion notifications
  2954. // for the in-flight job).
  2955. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2956. const handleEnterMaintenance = () => {
  2957. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2958. setConfirmMaintenanceEnter(true);
  2959. } else {
  2960. maintenanceMutation.mutate(false);
  2961. }
  2962. };
  2963. // Query for printable objects (for skip functionality)
  2964. // Fetch when printing with 2+ objects OR when modal is open
  2965. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2966. const { data: objectsData } = useQuery({
  2967. queryKey: ['printableObjects', printer.id],
  2968. queryFn: () => api.getPrintableObjects(printer.id),
  2969. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2970. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2971. });
  2972. // State for tracking which AMS slot is being refreshed
  2973. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2974. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2975. const seenBusyStateRef = useRef<boolean>(false);
  2976. // Fallback timeout ref
  2977. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2978. // Minimum display time passed
  2979. const minTimePassedRef = useRef<boolean>(false);
  2980. // AMS slot refresh mutation
  2981. const refreshAmsSlotMutation = useMutation({
  2982. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2983. api.refreshAmsSlot(printer.id, amsId, slotId),
  2984. onMutate: ({ amsId, slotId }) => {
  2985. // Clear any existing timeout
  2986. if (refreshTimeoutRef.current) {
  2987. clearTimeout(refreshTimeoutRef.current);
  2988. }
  2989. // Reset state
  2990. seenBusyStateRef.current = false;
  2991. minTimePassedRef.current = false;
  2992. setRefreshingSlot({ amsId, slotId });
  2993. // Minimum display time (2 seconds)
  2994. setTimeout(() => {
  2995. minTimePassedRef.current = true;
  2996. }, 2000);
  2997. // Fallback timeout (30 seconds max)
  2998. refreshTimeoutRef.current = setTimeout(() => {
  2999. setRefreshingSlot(null);
  3000. }, 30000);
  3001. },
  3002. onSuccess: (data) => {
  3003. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  3004. },
  3005. onError: (error: Error) => {
  3006. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  3007. if (refreshTimeoutRef.current) {
  3008. clearTimeout(refreshTimeoutRef.current);
  3009. }
  3010. setRefreshingSlot(null);
  3011. },
  3012. });
  3013. // AMS load/unload mutations (#891)
  3014. const loadAmsTrayMutation = useMutation({
  3015. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  3016. api.loadAmsTray(printer.id, trayId, extruderId),
  3017. onSuccess: (data) => {
  3018. setFeedDirectionRequest(null);
  3019. showToast(data.message || t('printers.toast.loadInitiated'));
  3020. },
  3021. onError: (error: Error) => {
  3022. setFeedDirectionRequest(null);
  3023. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3024. },
  3025. });
  3026. const unloadAmsMutation = useMutation({
  3027. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3028. onSuccess: (data) => {
  3029. showToast(data.message || t('printers.toast.unloadInitiated'));
  3030. },
  3031. onError: (error: Error) => {
  3032. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3033. },
  3034. });
  3035. // Pending "which hotend?" question, non-null only while the dialog is open.
  3036. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3037. // load command has to name one — see FeedDirectionModal.
  3038. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3039. trayId: number;
  3040. amsId: number;
  3041. slotId: number;
  3042. slotLabel: string;
  3043. } | null>(null);
  3044. // Whether a load from this printer has to ask which hotend to feed.
  3045. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3046. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3047. // The external holder needs no question: its two tray ids name the side
  3048. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3049. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3050. // external spool, because it would occupy an extruder channel permanently.
  3051. //
  3052. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3053. // carries does not address an HT unit, so the load is refused whatever the
  3054. // answer. Asking first would only put a dialog in front of the same error.
  3055. const isExternal = amsId === 255;
  3056. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3057. loadAmsTrayMutation.mutate({ trayId });
  3058. return;
  3059. }
  3060. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3061. // front rather than sending a command the firmware will drop. BambuStudio
  3062. // shows the same message and returns without publishing anything.
  3063. if (!status?.fila_switch?.ready) {
  3064. showToast(t('printers.ams.switchNotReady'), 'warning');
  3065. return;
  3066. }
  3067. setFeedDirectionRequest({
  3068. trayId,
  3069. amsId,
  3070. slotId,
  3071. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3072. });
  3073. };
  3074. // Plate references state
  3075. const [plateReferences, setPlateReferences] = useState<{
  3076. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3077. max_references: number;
  3078. } | null>(null);
  3079. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3080. // Fetch plate references
  3081. const fetchPlateReferences = async () => {
  3082. try {
  3083. const data = await api.getPlateReferences(printer.id);
  3084. setPlateReferences(data);
  3085. } catch {
  3086. // Ignore errors - references will show as empty
  3087. }
  3088. };
  3089. // Toggle plate detection enabled/disabled
  3090. const handleTogglePlateDetection = () => {
  3091. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3092. };
  3093. // Open plate detection management modal (for calibration/references)
  3094. const handleOpenPlateManagement = async () => {
  3095. setIsCheckingPlate(true);
  3096. setPlateCheckResult(null);
  3097. // Auto-turn on light if it's off
  3098. const lightWasOff = status?.chamber_light === false;
  3099. setPlateCheckLightWasOff(lightWasOff);
  3100. if (lightWasOff) {
  3101. await api.setChamberLight(printer.id, true);
  3102. // Wait for light to physically turn on and camera to adjust exposure
  3103. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3104. await new Promise(resolve => setTimeout(resolve, 2500));
  3105. }
  3106. try {
  3107. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3108. setPlateCheckResult(result);
  3109. fetchPlateReferences();
  3110. } catch (error) {
  3111. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3112. // Restore light if check failed
  3113. if (lightWasOff) {
  3114. await api.setChamberLight(printer.id, false);
  3115. setPlateCheckLightWasOff(false);
  3116. }
  3117. } finally {
  3118. setIsCheckingPlate(false);
  3119. }
  3120. };
  3121. // Close plate check modal and restore light state
  3122. const closePlateCheckModal = useCallback(async () => {
  3123. setPlateCheckResult(null);
  3124. // Restore light to original state if we turned it on
  3125. if (plateCheckLightWasOff) {
  3126. await api.setChamberLight(printer.id, false);
  3127. setPlateCheckLightWasOff(false);
  3128. }
  3129. }, [plateCheckLightWasOff, printer.id]);
  3130. // Calibrate plate detection handler
  3131. const handleCalibratePlate = async (label?: string) => {
  3132. setIsCalibrating(true);
  3133. try {
  3134. const result = await api.calibratePlateDetection(printer.id, { label });
  3135. if (result.success) {
  3136. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3137. // Refresh references and re-check
  3138. fetchPlateReferences();
  3139. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3140. setPlateCheckResult(checkResult);
  3141. } else {
  3142. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3143. }
  3144. } catch (error) {
  3145. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3146. } finally {
  3147. setIsCalibrating(false);
  3148. }
  3149. };
  3150. // Update reference label
  3151. const handleUpdateRefLabel = async (index: number, label: string) => {
  3152. try {
  3153. await api.updatePlateReferenceLabel(printer.id, index, label);
  3154. setEditingRefLabel(null);
  3155. fetchPlateReferences();
  3156. } catch (error) {
  3157. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3158. }
  3159. };
  3160. // Delete reference
  3161. const handleDeleteRef = async (index: number) => {
  3162. try {
  3163. await api.deletePlateReference(printer.id, index);
  3164. showToast(t('printers.toast.referenceDeleted'), 'success');
  3165. fetchPlateReferences();
  3166. // Re-check to update counts
  3167. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3168. setPlateCheckResult(checkResult);
  3169. } catch (error) {
  3170. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3171. }
  3172. };
  3173. // Save ROI settings
  3174. const handleSaveRoi = async () => {
  3175. if (!editingRoi) return;
  3176. setIsSavingRoi(true);
  3177. try {
  3178. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3179. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3180. setEditingRoi(null);
  3181. // Re-check to see new ROI in action
  3182. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3183. setPlateCheckResult(checkResult);
  3184. } catch (error) {
  3185. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3186. } finally {
  3187. setIsSavingRoi(false);
  3188. }
  3189. };
  3190. // Close plate check modal on Escape key
  3191. useEffect(() => {
  3192. const handleEscape = (e: KeyboardEvent) => {
  3193. if (e.key === 'Escape' && plateCheckResult) {
  3194. closePlateCheckModal();
  3195. }
  3196. };
  3197. window.addEventListener('keydown', handleEscape);
  3198. return () => window.removeEventListener('keydown', handleEscape);
  3199. }, [plateCheckResult, closePlateCheckModal]);
  3200. // Watch ams_status_main to detect when RFID read completes
  3201. // ams_status_main: 0=idle, 2=rfid_identifying
  3202. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3203. useEffect(() => {
  3204. if (!refreshingSlot) return;
  3205. const amsStatus = status?.ams_status_main ?? 0;
  3206. // Track when we see non-idle state (printer is working)
  3207. if (amsStatus !== 0) {
  3208. seenBusyStateRef.current = true;
  3209. // Cancel any deferred clear since we're back to busy
  3210. if (deferredClearRef.current) {
  3211. clearTimeout(deferredClearRef.current);
  3212. deferredClearRef.current = null;
  3213. }
  3214. }
  3215. // When we've seen busy and now idle, clear (with min time check)
  3216. if (seenBusyStateRef.current && amsStatus === 0) {
  3217. if (minTimePassedRef.current) {
  3218. // Min time passed - clear now
  3219. if (refreshTimeoutRef.current) {
  3220. clearTimeout(refreshTimeoutRef.current);
  3221. }
  3222. setRefreshingSlot(null);
  3223. } else {
  3224. // Schedule clear after min time (2 seconds from start)
  3225. if (!deferredClearRef.current) {
  3226. deferredClearRef.current = setTimeout(() => {
  3227. if (refreshTimeoutRef.current) {
  3228. clearTimeout(refreshTimeoutRef.current);
  3229. }
  3230. setRefreshingSlot(null);
  3231. }, 2000);
  3232. }
  3233. }
  3234. }
  3235. return () => {
  3236. if (deferredClearRef.current) {
  3237. clearTimeout(deferredClearRef.current);
  3238. }
  3239. };
  3240. }, [status?.ams_status_main, refreshingSlot]);
  3241. useEffect(() => {
  3242. if (!showMenu) return;
  3243. const handleClickOutside = (event: MouseEvent) => {
  3244. const target = event.target as Node;
  3245. if (!printerActionsMenuRef.current?.contains(target)) {
  3246. setShowMenu(false);
  3247. }
  3248. };
  3249. document.addEventListener('mousedown', handleClickOutside);
  3250. return () => document.removeEventListener('mousedown', handleClickOutside);
  3251. }, [showMenu]);
  3252. if (shouldHide) {
  3253. return null;
  3254. }
  3255. // Size-based styling helpers
  3256. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3257. // width, its thumbnail and the printer name, but every label inside the
  3258. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3259. // S one -- the disparity was worst exactly where someone asking for more
  3260. // room ends up. These custom properties carry the scaled sizes into the
  3261. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3262. // unless they reach for a size that is already asking for more space.
  3263. // Plain computation rather than useMemo: this sits after the card's early
  3264. // returns, where a hook would break the rules-of-hooks ordering, and
  3265. // building ten strings per render costs nothing.
  3266. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3267. const getImageSize = () => {
  3268. switch (cardSize) {
  3269. case 1: return 'w-10 h-10';
  3270. case 2: return 'w-14 h-14';
  3271. case 3: return 'w-16 h-16';
  3272. case 4: return 'w-20 h-20';
  3273. default: return 'w-14 h-14';
  3274. }
  3275. };
  3276. const getTitleSize = () => {
  3277. switch (cardSize) {
  3278. case 1: return 'text-base truncate';
  3279. case 2: return 'text-lg';
  3280. case 3: return 'text-xl';
  3281. case 4: return 'text-2xl';
  3282. default: return 'text-lg';
  3283. }
  3284. };
  3285. const getSpacing = () => {
  3286. switch (cardSize) {
  3287. case 1: return 'mb-2';
  3288. case 2: return 'mb-4';
  3289. case 3: return 'mb-5';
  3290. case 4: return 'mb-6';
  3291. default: return 'mb-4';
  3292. }
  3293. };
  3294. // A dropped file always becomes a queue item, so a printer that is busy,
  3295. // offline or mid-drying is no reason to refuse the drop — it only means the
  3296. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3297. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3298. // what this would have done for them.
  3299. //
  3300. // What remains is what the flow actually performs: upload the file, then
  3301. // create a queue item. It never touches printers:control, which is what this
  3302. // used to check — so someone holding that but neither of these had the file
  3303. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3304. // button below has always checked this pair.
  3305. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3306. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3307. // and the modal's own "will start later" toast cannot disagree.
  3308. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3309. const handleCardDragEnter = (e: React.DragEvent) => {
  3310. e.preventDefault();
  3311. dragCounterRef.current++;
  3312. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3313. };
  3314. const handleCardDragOver = (e: React.DragEvent) => {
  3315. e.preventDefault();
  3316. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3317. };
  3318. const handleCardDragLeave = (e: React.DragEvent) => {
  3319. e.preventDefault();
  3320. dragCounterRef.current--;
  3321. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3322. };
  3323. const handleCardDrop = async (e: React.DragEvent) => {
  3324. e.preventDefault();
  3325. dragCounterRef.current = 0;
  3326. setIsDraggingFile(false);
  3327. if (!canDrop) return;
  3328. const droppedFiles = Array.from(e.dataTransfer.files);
  3329. const file = droppedFiles[0];
  3330. if (!file) return;
  3331. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3332. const lower = file.name.toLowerCase();
  3333. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3334. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3335. return;
  3336. }
  3337. setIsDropUploading(true);
  3338. try {
  3339. const result = await api.uploadLibraryFile(file, null);
  3340. // Check printer compatibility if sliced_for_model is available in metadata
  3341. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3342. const printerModel = mapModelCode(printer.model);
  3343. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3344. await api.deleteLibraryFile(result.id).catch(() => {});
  3345. showToast(
  3346. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3347. 'error'
  3348. );
  3349. return;
  3350. }
  3351. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3352. } catch {
  3353. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3354. } finally {
  3355. setIsDropUploading(false);
  3356. }
  3357. };
  3358. const handleCardClick = (e: React.MouseEvent) => {
  3359. if (viewMode !== 'compact' || selectionMode) return;
  3360. const target = e.target as HTMLElement;
  3361. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3362. onOpenCompactCard?.(printer.id);
  3363. };
  3364. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3365. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3366. // Opening a camera in a given mode, without touching which mode is remembered
  3367. // -- the split button's two halves want the same action but disagree about
  3368. // whether the choice was deliberate enough to keep.
  3369. const openCameraIn = (mode: CameraViewMode) => {
  3370. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3371. onOpenEmbeddedCamera(printer.id, printer.name);
  3372. } else {
  3373. openCameraWindow(printer.id);
  3374. }
  3375. };
  3376. // Picking a mode both opens the camera that way and makes it the mode the
  3377. // plain icon uses from now on. A menu that only changed a preference would
  3378. // leave the user with a second click to do the thing they already asked for.
  3379. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3380. [
  3381. {
  3382. mode: 'window' as const,
  3383. icon: <ExternalLink className="w-4 h-4" />,
  3384. label: t('settings.newWindow'),
  3385. title: t('settings.cameraWindowDescription'),
  3386. },
  3387. {
  3388. mode: 'embedded' as const,
  3389. icon: <PictureInPicture2 className="w-4 h-4" />,
  3390. label: t('settings.embeddedOverlay'),
  3391. title: t('settings.cameraOverlayDescription'),
  3392. },
  3393. ]
  3394. ).map(({ mode, icon, label, title }) => ({
  3395. icon,
  3396. // The remembered mode is marked in the label itself: the icon slot already
  3397. // carries the mode's own icon, and a separate tick column would push both
  3398. // entries out of line with every other card menu.
  3399. label: mode === cameraViewMode ? `${label} ✓` : label,
  3400. title,
  3401. onClick: () => {
  3402. onSelectCameraViewMode?.(mode);
  3403. openCameraIn(mode);
  3404. },
  3405. }));
  3406. const renderAmsSlotActions = ({
  3407. amsId,
  3408. slotId,
  3409. loadTrayId,
  3410. isRefreshing,
  3411. includeRfid = true,
  3412. }: {
  3413. amsId: number;
  3414. slotId: number;
  3415. loadTrayId: number;
  3416. isRefreshing?: boolean;
  3417. includeRfid?: boolean;
  3418. }) => {
  3419. const printerBusy = status?.state === 'RUNNING';
  3420. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3421. // ams*4+slot, so the id this menu carries does not name it to the load and
  3422. // unload endpoints — they reject it. Sending no slot falls back to the
  3423. // printer-wide unload, which is what this menu did for every slot before
  3424. // the per-slot form existed. Load has never worked on an HT slot for the
  3425. // same addressing reason; fixing that is a separate change.
  3426. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3427. return (
  3428. <>
  3429. {includeRfid && (
  3430. <button
  3431. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3432. hasPermission('printers:ams_rfid')
  3433. ? 'text-white hover:bg-bambu-dark-tertiary'
  3434. : 'text-bambu-gray/50 cursor-not-allowed'
  3435. }`}
  3436. onClick={(e) => {
  3437. e.stopPropagation();
  3438. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3439. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3440. }}
  3441. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3442. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3443. >
  3444. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3445. {t('printers.rfid.reread')}
  3446. </button>
  3447. )}
  3448. <button
  3449. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3450. hasPermission('printers:control')
  3451. ? 'text-white hover:bg-bambu-dark-tertiary'
  3452. : 'text-bambu-gray/50 cursor-not-allowed'
  3453. }`}
  3454. onClick={(e) => {
  3455. e.stopPropagation();
  3456. if (printerBusy || !hasPermission('printers:control')) return;
  3457. startAmsLoad(amsId, slotId, loadTrayId);
  3458. }}
  3459. disabled={printerBusy || !hasPermission('printers:control')}
  3460. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3461. >
  3462. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3463. {t('printers.ams.load')}
  3464. </button>
  3465. <button
  3466. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3467. hasPermission('printers:control')
  3468. ? 'text-white hover:bg-bambu-dark-tertiary'
  3469. : 'text-bambu-gray/50 cursor-not-allowed'
  3470. }`}
  3471. onClick={(e) => {
  3472. e.stopPropagation();
  3473. if (printerBusy || !hasPermission('printers:control')) return;
  3474. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3475. }}
  3476. disabled={printerBusy || !hasPermission('printers:control')}
  3477. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3478. >
  3479. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3480. {t('printers.ams.unload')}
  3481. </button>
  3482. </>
  3483. );
  3484. };
  3485. const printerActionsMenu = (
  3486. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3487. <Button
  3488. variant="secondary"
  3489. size="sm"
  3490. onClick={() => setShowMenu(!showMenu)}
  3491. title={t('common.more', 'More')}
  3492. className={footerIconButtonClass}
  3493. >
  3494. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3495. </Button>
  3496. {showMenu && (
  3497. <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">
  3498. <button
  3499. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3500. hasPermission('printers:update')
  3501. ? 'hover:bg-bambu-dark-tertiary'
  3502. : 'opacity-50 cursor-not-allowed'
  3503. }`}
  3504. onClick={() => {
  3505. if (!hasPermission('printers:update')) return;
  3506. setShowEditModal(true);
  3507. setShowMenu(false);
  3508. }}
  3509. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3510. >
  3511. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3512. {t('common.edit')}
  3513. </button>
  3514. <button
  3515. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3516. onClick={() => {
  3517. setShowPrinterInfo(true);
  3518. setShowMenu(false);
  3519. }}
  3520. >
  3521. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3522. {t('printers.printerInformation')}
  3523. </button>
  3524. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3525. <button
  3526. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3527. hasPermission('printers:update')
  3528. ? 'hover:bg-bambu-dark-tertiary'
  3529. : 'opacity-50 cursor-not-allowed'
  3530. }`}
  3531. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3532. onClick={() => {
  3533. if (!hasPermission('printers:update')) return;
  3534. setShowMenu(false);
  3535. if (printer.is_active !== false) {
  3536. handleEnterMaintenance();
  3537. } else {
  3538. maintenanceMutation.mutate(true);
  3539. }
  3540. }}
  3541. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3542. >
  3543. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3544. {printer.is_active !== false
  3545. ? t('printers.maintenance.menuEnter')
  3546. : t('printers.maintenance.menuExit')}
  3547. </button>
  3548. <button
  3549. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3550. onClick={() => {
  3551. connectMutation.mutate();
  3552. setShowMenu(false);
  3553. }}
  3554. >
  3555. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3556. {t('printers.reconnect')}
  3557. </button>
  3558. <button
  3559. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3560. disabled={forceRefreshMutation.isPending}
  3561. onClick={() => {
  3562. forceRefreshMutation.mutate();
  3563. setShowMenu(false);
  3564. }}
  3565. >
  3566. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3567. {t('printers.forceRefresh')}
  3568. </button>
  3569. <button
  3570. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3571. onClick={() => {
  3572. setShowMQTTDebug(true);
  3573. setShowMenu(false);
  3574. }}
  3575. >
  3576. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3577. {t('printers.mqttDebug')}
  3578. </button>
  3579. <button
  3580. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3581. onClick={() => {
  3582. setShowDiagnostic(true);
  3583. setShowMenu(false);
  3584. }}
  3585. >
  3586. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3587. {t('diagnostic.runButton')}
  3588. </button>
  3589. <button
  3590. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3591. hasPermission('printers:delete')
  3592. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3593. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3594. }`}
  3595. onClick={() => {
  3596. if (!hasPermission('printers:delete')) return;
  3597. setShowDeleteConfirm(true);
  3598. setShowMenu(false);
  3599. }}
  3600. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3601. >
  3602. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3603. {t('common.delete')}
  3604. </button>
  3605. </div>
  3606. )}
  3607. </div>
  3608. );
  3609. return (
  3610. <Card
  3611. id={`printer-card-${printer.id}`}
  3612. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3613. style={cardScaleStyle}
  3614. onClick={handleCardClick}
  3615. onDragEnter={handleCardDragEnter}
  3616. onDragOver={handleCardDragOver}
  3617. onDragLeave={handleCardDragLeave}
  3618. onDrop={handleCardDrop}
  3619. >
  3620. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3621. {selectionMode && (
  3622. <div
  3623. className="absolute inset-0 z-20 flex items-start p-2"
  3624. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3625. >
  3626. {isSelected ? (
  3627. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3628. ) : (
  3629. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3630. )}
  3631. </div>
  3632. )}
  3633. {/* Drop zone overlay */}
  3634. {(isDraggingFile || isDropUploading) && (
  3635. <div
  3636. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3637. isDropUploading
  3638. ? 'bg-bambu-green/10 border-bambu-green/50'
  3639. : canDrop
  3640. ? 'bg-bambu-green/10 border-bambu-green'
  3641. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3642. }`}
  3643. >
  3644. <div className="text-center">
  3645. {isDropUploading ? (
  3646. <>
  3647. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3648. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3649. </>
  3650. ) : canDrop ? (
  3651. <>
  3652. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3653. <p className="text-sm font-medium text-bambu-green">
  3654. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3655. </p>
  3656. </>
  3657. ) : (
  3658. <>
  3659. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3660. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3661. {!hasPermission('library:upload')
  3662. ? t('fileManager.noPermissionUpload')
  3663. : t('fileManager.noPermissionAddToQueue')}
  3664. </p>
  3665. </>
  3666. )}
  3667. </div>
  3668. </div>
  3669. )}
  3670. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3671. {/* Header */}
  3672. <div className={getSpacing()}>
  3673. {/* Top row: Image, Name, Menu */}
  3674. <div className="flex items-start justify-between gap-2">
  3675. <div className="flex items-center gap-3 min-w-0 flex-1">
  3676. {/* Printer Model Image */}
  3677. <img
  3678. src={getPrinterImage(printer.model)}
  3679. alt={printer.model || t('common.printer')}
  3680. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3681. />
  3682. <div className="min-w-0 flex-1">
  3683. <div className="flex items-center justify-between gap-2">
  3684. <div className="flex min-w-0 items-center gap-2">
  3685. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3686. {/* Connection indicator dot for compact mode */}
  3687. {viewMode === 'compact' && (() => {
  3688. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3689. const hasSevere = hmsErrors.some(isSevereHMSError);
  3690. const hasWarning = hmsErrors.length > 0;
  3691. const pipColor = !status?.connected
  3692. ? 'bg-status-error'
  3693. : hasSevere
  3694. ? 'bg-status-error'
  3695. : hasWarning
  3696. ? 'bg-status-warning'
  3697. : 'bg-status-ok';
  3698. const pipTitle = !status?.connected
  3699. ? t('printers.connection.offline')
  3700. : hasWarning
  3701. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3702. : t('printers.connection.connected');
  3703. return (
  3704. <div
  3705. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3706. title={pipTitle}
  3707. />
  3708. );
  3709. })()}
  3710. </div>
  3711. {viewMode === 'compact' && showClearPlateButton && (
  3712. <button
  3713. type="button"
  3714. onClick={() => clearPlateMutation.mutate()}
  3715. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3716. aria-label={t('printers.plateStatus.markCleared')}
  3717. 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"
  3718. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3719. >
  3720. {clearPlateMutation.isPending ? (
  3721. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3722. ) : (
  3723. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3724. )}
  3725. </button>
  3726. )}
  3727. </div>
  3728. <p className="text-sm text-bambu-gray">
  3729. {printer.model || 'Unknown Model'}
  3730. {/* Nozzle Info - only in expanded. Every fitted size, not
  3731. just nozzles[0]: the array is indexed by extruder, so on a
  3732. dual-nozzle machine with two sizes fitted showing the
  3733. first entry alone named one hotend and implied it was the
  3734. whole printer. Deduplicated, so the usual matching pair
  3735. still reads as a single "0.4mm". */}
  3736. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3737. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3738. • {installedNozzleDiameters(status).join(' / ')}mm
  3739. </span>
  3740. )}
  3741. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3742. <span className="ml-2 text-bambu-gray">
  3743. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3744. {Math.round(maintenanceInfo.total_print_hours)}h
  3745. </span>
  3746. )}
  3747. </p>
  3748. </div>
  3749. </div>
  3750. </div>
  3751. {/* Badges row - only in expanded mode */}
  3752. {viewMode === 'expanded' && (
  3753. <div className="mt-2">
  3754. <div className="flex flex-wrap items-center gap-2">
  3755. {/* Connection status badge (or Maintenance pill when out of service).
  3756. Defensive: only swap when is_active is EXPLICITLY false. An
  3757. undefined / missing field defaults to "active" so the regular
  3758. pill renders — matches the backend default and prevents test
  3759. fixtures (or stale clients) from accidentally tripping the
  3760. maintenance UI. */}
  3761. {printer.is_active === false ? (
  3762. <span
  3763. 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"
  3764. title={t('printers.maintenance.subtitle')}
  3765. >
  3766. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3767. {t('printers.maintenance.pillLabel')}
  3768. </span>
  3769. ) : (
  3770. <span
  3771. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3772. status?.connected
  3773. ? 'bg-status-ok/20 text-status-ok'
  3774. : 'bg-status-error/20 text-status-error'
  3775. }`}
  3776. >
  3777. {status?.connected ? (
  3778. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3779. ) : (
  3780. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3781. )}
  3782. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3783. </span>
  3784. )}
  3785. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3786. {printer.is_active !== false && !status?.connected && (
  3787. <button
  3788. onClick={() => setShowDiagnostic(true)}
  3789. 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"
  3790. title={t('diagnostic.runButton')}
  3791. >
  3792. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3793. {t('diagnostic.runButton')}
  3794. </button>
  3795. )}
  3796. {/* Network connection indicator */}
  3797. {status?.connected && status?.wired_network && (
  3798. <span
  3799. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3800. title={t('printers.connection.ethernet', 'Ethernet')}
  3801. >
  3802. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3803. {t('printers.connection.ethernet', 'Ethernet')}
  3804. </span>
  3805. )}
  3806. {/* WiFi signal indicator */}
  3807. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3808. <span
  3809. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3810. wifiSignal >= -50
  3811. ? 'bg-status-ok/20 text-status-ok'
  3812. : wifiSignal >= -60
  3813. ? 'bg-status-ok/20 text-status-ok'
  3814. : wifiSignal >= -70
  3815. ? 'bg-status-warning/20 text-status-warning'
  3816. : wifiSignal >= -80
  3817. ? 'bg-orange-500/20 text-orange-600'
  3818. : 'bg-status-error/20 text-status-error'
  3819. }`}
  3820. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3821. >
  3822. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3823. {wifiSignal}dBm
  3824. </span>
  3825. )}
  3826. {/* HMS Status Indicator */}
  3827. {status?.connected && (() => {
  3828. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3829. return (
  3830. <button
  3831. onClick={() => setShowHMSModal(true)}
  3832. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3833. knownErrors.length > 0
  3834. ? knownErrors.some(isSevereHMSError)
  3835. ? 'bg-status-error/20 text-status-error'
  3836. : 'bg-status-warning/20 text-status-warning'
  3837. : 'bg-status-ok/20 text-status-ok'
  3838. }`}
  3839. title={t('printers.clickToViewHmsErrors')}
  3840. >
  3841. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3842. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3843. </button>
  3844. );
  3845. })()}
  3846. {/* AI failure detection badge (#1546) — always shown while detection
  3847. is enabled for this printer, like the other health badges. Gray
  3848. "Idle" outside a monitored print, class-colored during one. */}
  3849. {aiDetectionEnabled && (() => {
  3850. const cls = aiDetectionClass(aiDetection);
  3851. const colorClass =
  3852. cls === 'failure'
  3853. ? 'bg-status-error/20 text-status-error'
  3854. : cls === 'warning'
  3855. ? 'bg-status-warning/20 text-status-warning'
  3856. : cls === 'safe'
  3857. ? 'bg-status-ok/20 text-status-ok'
  3858. : cls === 'error'
  3859. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3860. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3861. // 'error' and 'unknown' have no score to quote — saying
  3862. // "Safe (0.000)" for a print nothing is looking at is the
  3863. // whole of #2952.
  3864. const title =
  3865. cls === 'error'
  3866. ? t('printers.aiDetection.tooltipError', {
  3867. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3868. })
  3869. : cls === 'unknown'
  3870. ? t('printers.aiDetection.tooltipUnknown')
  3871. : aiDetection
  3872. ? t('printers.aiDetection.tooltip', {
  3873. status: t(`printers.aiDetection.${cls}`),
  3874. score: aiDetection.score.toFixed(3),
  3875. })
  3876. : t('printers.aiDetection.tooltipIdle');
  3877. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3878. return (
  3879. <button
  3880. onClick={() => setShowAiModal(true)}
  3881. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3882. title={title}
  3883. >
  3884. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3885. {t(`printers.aiDetection.${cls}`)}
  3886. </button>
  3887. );
  3888. })()}
  3889. {/* Maintenance Status Indicator */}
  3890. {maintenanceInfo && (
  3891. <button
  3892. onClick={() => navigate('/maintenance')}
  3893. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3894. maintenanceInfo.due_count > 0
  3895. ? 'bg-status-error/20 text-status-error'
  3896. : maintenanceInfo.warning_count > 0
  3897. ? 'bg-status-warning/20 text-status-warning'
  3898. : 'bg-status-ok/20 text-status-ok'
  3899. }`}
  3900. title={
  3901. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3902. ? `${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`
  3903. : t('printers.maintenanceUpToDate')
  3904. }
  3905. >
  3906. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3907. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3908. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3909. : 'OK'}
  3910. </button>
  3911. )}
  3912. {/* Queue Count Badge */}
  3913. {queueCount > 0 && (
  3914. <button
  3915. onClick={() => navigate('/queue')}
  3916. 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"
  3917. title={t('printers.queue.inQueue', { count: queueCount })}
  3918. >
  3919. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3920. {queueCount}
  3921. </button>
  3922. )}
  3923. {/* Firmware Version Badge */}
  3924. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3925. <button
  3926. onClick={() => setShowFirmwareModal(true)}
  3927. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3928. firmwareInfo.update_available
  3929. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3930. : 'bg-status-ok/20 text-status-ok'
  3931. }`}
  3932. title={
  3933. firmwareInfo.update_available
  3934. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3935. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3936. }
  3937. >
  3938. {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)]" />}
  3939. {firmwareInfo.current_version}
  3940. </button>
  3941. ) : status?.firmware_version ? (
  3942. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3943. {status.firmware_version}
  3944. </span>
  3945. ) : null}
  3946. {/* Enclosure Door Badge — models with an actual door sensor.
  3947. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3948. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3949. <span
  3950. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3951. status.door_open
  3952. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3953. : 'bg-status-ok/20 text-status-ok'
  3954. }`}
  3955. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3956. >
  3957. {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)]" />}
  3958. </span>
  3959. )}
  3960. </div>
  3961. </div>
  3962. )}
  3963. </div>
  3964. {/* Delete Confirmation */}
  3965. {showDeleteConfirm && (
  3966. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3967. <Card className="w-full max-w-md mx-4">
  3968. <CardContent>
  3969. <div className="flex items-start gap-3 mb-4">
  3970. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3971. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3972. </div>
  3973. <div>
  3974. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3975. <p className="text-sm text-bambu-gray mt-1">
  3976. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3977. </p>
  3978. </div>
  3979. </div>
  3980. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3981. <label className="flex items-start gap-3 cursor-pointer">
  3982. <input
  3983. type="checkbox"
  3984. checked={deleteArchives}
  3985. onChange={(e) => setDeleteArchives(e.target.checked)}
  3986. 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"
  3987. />
  3988. <div>
  3989. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3990. <p className="text-xs text-bambu-gray mt-0.5">
  3991. {deleteArchives
  3992. ? t('printers.confirm.deleteArchivesNote')
  3993. : t('printers.confirm.keepArchivesNote')}
  3994. </p>
  3995. </div>
  3996. </label>
  3997. </div>
  3998. <div className="flex justify-end gap-2">
  3999. <Button
  4000. variant="secondary"
  4001. onClick={() => {
  4002. setShowDeleteConfirm(false);
  4003. setDeleteArchives(true);
  4004. }}
  4005. >
  4006. {t('common.cancel')}
  4007. </Button>
  4008. <Button
  4009. variant="danger"
  4010. onClick={() => {
  4011. deleteMutation.mutate({ deleteArchives });
  4012. setShowDeleteConfirm(false);
  4013. setDeleteArchives(true);
  4014. }}
  4015. >
  4016. Delete
  4017. </Button>
  4018. </div>
  4019. </CardContent>
  4020. </Card>
  4021. </div>
  4022. )}
  4023. {/* Status — see the equivalent defensive `=== false` check on the
  4024. header pill above for why this is not `!printer.is_active`. */}
  4025. {printer.is_active === false ? (
  4026. // Maintenance mode (#1476) — replaces the cover/progress container
  4027. // so the card keeps the same height. Renders for both compact and
  4028. // expanded view modes so the printer stays visible but plainly
  4029. // out-of-service.
  4030. <>
  4031. {viewMode === 'compact' ? (
  4032. <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">
  4033. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4034. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4035. {t('printers.maintenance.pillLabel')}
  4036. </span>
  4037. </div>
  4038. ) : (
  4039. <>
  4040. <div className="flex items-center gap-2 mb-2">
  4041. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4042. {t('printers.status.title', 'Status')}
  4043. </span>
  4044. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4045. </div>
  4046. <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">
  4047. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4048. <div className="flex-1 min-w-0">
  4049. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4050. {t('printers.maintenance.title')}
  4051. </p>
  4052. <p className="text-xs text-bambu-gray mt-0.5">
  4053. {t('printers.maintenance.subtitle')}
  4054. </p>
  4055. </div>
  4056. <Button
  4057. variant="secondary"
  4058. size="sm"
  4059. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4060. onClick={() => maintenanceMutation.mutate(true)}
  4061. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4062. >
  4063. {t('printers.maintenance.exitButton')}
  4064. </Button>
  4065. </div>
  4066. </>
  4067. )}
  4068. </>
  4069. ) : status?.connected && (
  4070. <>
  4071. {/* Compact: Simple status bar */}
  4072. {viewMode === 'compact' ? (
  4073. (() => {
  4074. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4075. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4076. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4077. ? Math.max(0, Math.min(100, status.progress || 0))
  4078. : showClearPlateButton
  4079. ? 100
  4080. : hasProblem
  4081. ? 100
  4082. : 0;
  4083. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4084. const compactProgressClass = hasProblem
  4085. ? 'bg-status-error'
  4086. : status.state === 'PAUSE'
  4087. ? 'bg-status-warning'
  4088. : 'bg-bambu-green';
  4089. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4090. const hasCompactLayers =
  4091. isActiveCompactPrint &&
  4092. status.layer_num != null &&
  4093. status.total_layers != null &&
  4094. status.total_layers > 0;
  4095. return (
  4096. <>
  4097. <div className="relative mt-2 flex items-center gap-2">
  4098. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4099. <div
  4100. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4101. style={{ width: `${compactProgress}%` }}
  4102. />
  4103. </div>
  4104. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4105. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4106. </span>
  4107. </div>
  4108. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4109. enough to answer "which printer finishes first", which is what a
  4110. wall-mounted fleet view is for. One line of the metrics the
  4111. expanded card already renders, using the same formatters and the
  4112. same ETA styling so S and M read alike. The row keeps its height
  4113. when idle so cards don't shift as prints start and stop. */}
  4114. <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">
  4115. {hasCompactEta && (
  4116. <>
  4117. <span className="flex shrink-0 items-center gap-1">
  4118. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4119. {formatDuration(status.remaining_time! * 60)}
  4120. </span>
  4121. <span
  4122. className="shrink-0 font-medium text-bambu-green"
  4123. title={t('printers.estimatedCompletion')}
  4124. >
  4125. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4126. </span>
  4127. </>
  4128. )}
  4129. {hasCompactLayers && (
  4130. <span className="flex min-w-0 items-center gap-1 truncate">
  4131. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4132. {status.layer_num}/{status.total_layers}
  4133. </span>
  4134. )}
  4135. </div>
  4136. </>
  4137. );
  4138. })()
  4139. ) : (
  4140. /* Expanded: Full status section */
  4141. <>
  4142. <div className="flex items-center gap-2 mb-2">
  4143. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4144. {t('printers.status.title', 'Status')}
  4145. </span>
  4146. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4147. </div>
  4148. {/* Current Print or Idle Placeholder */}
  4149. {(() => {
  4150. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4151. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4152. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4153. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4154. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4155. // A running print always has at least one object, so a count of
  4156. // zero means "not loaded", not "nothing to skip" — after a
  4157. // restart mid-print the list is empty until something rebuilds
  4158. // it. Treating that as nothing-to-skip disabled the only
  4159. // control that opens the modal, and the modal's own fetch is
  4160. // what rebuilds the list, so the print could never get it back.
  4161. // Exactly one object is the real nothing-to-skip case.
  4162. const objectCount = status.printable_objects_count ?? 0;
  4163. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4164. return (
  4165. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4166. <button
  4167. onClick={() => setShowSkipObjectsModal(true)}
  4168. disabled={!canSkipObjects}
  4169. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4170. canSkipObjects
  4171. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4172. : 'text-bambu-gray/30 cursor-not-allowed'
  4173. }`}
  4174. title={
  4175. !hasPermission('printers:control')
  4176. ? t('printers.permission.noControl')
  4177. : !isActivePrint
  4178. ? t('printers.skipObjects.onlyWhilePrinting')
  4179. : objectCount === 1
  4180. ? t('printers.skipObjects.requiresMultiple')
  4181. : t('printers.skipObjects.tooltip')
  4182. }
  4183. >
  4184. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4185. {objectsData && objectsData.skipped_count > 0 && (
  4186. <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">
  4187. {objectsData.skipped_count}
  4188. </span>
  4189. )}
  4190. </button>
  4191. <div className="flex items-stretch gap-2">
  4192. <CoverImage
  4193. url={coverUrl}
  4194. printName={printName || undefined}
  4195. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4196. />
  4197. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4198. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4199. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4200. {plateStatusPill}
  4201. </div>
  4202. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4203. {printName || t('printers.noActiveJob', 'No active job')}
  4204. </p>
  4205. <div className="flex h-3 items-center gap-2 text-sm">
  4206. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4207. <div
  4208. 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`}
  4209. style={{ width: `${progress}%` }}
  4210. />
  4211. </div>
  4212. <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>
  4213. </div>
  4214. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4215. {isActivePrint ? (
  4216. <>
  4217. {status.remaining_time != null && status.remaining_time > 0 && (
  4218. <>
  4219. <span className="flex items-center gap-1">
  4220. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4221. {formatDuration(status.remaining_time * 60)}
  4222. </span>
  4223. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4224. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4225. </span>
  4226. </>
  4227. )}
  4228. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4229. <span className="flex items-center gap-1">
  4230. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4231. {status.layer_num}/{status.total_layers}
  4232. </span>
  4233. )}
  4234. {currentPrintUser && (
  4235. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4236. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4237. {currentPrintUser}
  4238. </span>
  4239. )}
  4240. </>
  4241. ) : lastPrint ? (
  4242. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4243. Last: {lastPrint.print_name || lastPrint.filename}
  4244. {lastPrint.completed_at && (
  4245. <span className="ml-1 text-bambu-gray/60">
  4246. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4247. </span>
  4248. )}
  4249. </p>
  4250. ) : (
  4251. <span>{t('printers.readyToPrint')}</span>
  4252. )}
  4253. </div>
  4254. </div>
  4255. </div>
  4256. <PrinterQueueWidget
  4257. printerId={printer.id}
  4258. printerModel={printer.model}
  4259. loadedFilamentTypes={loadedFilamentTypes}
  4260. loadedFilaments={loadedFilaments}
  4261. loadedVariants={loadedVariants}
  4262. variant="panelExtension"
  4263. />
  4264. </div>
  4265. );
  4266. })()}
  4267. </>
  4268. )}
  4269. {/* Temperatures */}
  4270. {status.temperatures && viewMode === 'expanded' && (() => {
  4271. // Use actual heater states from MQTT stream
  4272. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4273. const bedHeating = status.temperatures.bed_heating || false;
  4274. const chamberHeating = status.temperatures.chamber_heating || false;
  4275. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4276. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4277. const kinds: HeaterSensorKind[] = ['nozzle'];
  4278. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4279. kinds.push('bed');
  4280. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4281. return kinds;
  4282. })();
  4283. // active_extruder: 0=right, 1=left
  4284. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4285. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4286. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4287. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4288. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4289. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4290. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4291. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4292. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4293. 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 ${
  4294. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4295. }`;
  4296. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4297. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4298. // the widget there is at best dead UI and at worst suggests a
  4299. // control that does nothing. Mirrors the enclosure-door badge
  4300. // gate above.
  4301. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4302. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4303. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4304. // show it only when the printer actually reports it (airduct part id 3,
  4305. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4306. // have a built-in chamber fan that's always present, so they keep the
  4307. // existing model-list gate and the "Chamber Fan" label.
  4308. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4309. const chamberFanLabel = isExhaustModel
  4310. ? t('printers.fans.exhaust')
  4311. : t('printers.fans.chamber');
  4312. // Composed rather than either/or so both lists stay live for
  4313. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4314. // where that fan is an add-on kit — actually report it. Written
  4315. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4316. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4317. // which reads as if removing them were safe.
  4318. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4319. const fanItems: {
  4320. key: string;
  4321. label: string;
  4322. value: number;
  4323. Icon: typeof Fan;
  4324. activeClass: string;
  4325. }[] = [
  4326. {
  4327. key: 'part',
  4328. label: t('printers.fans.partCooling'),
  4329. value: status.cooling_fan_speed ?? 0,
  4330. Icon: Fan,
  4331. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4332. },
  4333. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4334. // Only reported (non-null) when the firmware lists airduct part
  4335. // id 10, i.e. when the fan is physically installed. Placed
  4336. // before the right-hand auxiliary fan so the two aux badges read
  4337. // left-to-right in the same order as the physical hardware.
  4338. ...(status.left_aux_fan_speed != null
  4339. ? [
  4340. {
  4341. key: 'aux2',
  4342. label: t('printers.fans.leftAuxiliary'),
  4343. value: status.left_aux_fan_speed,
  4344. Icon: Wind,
  4345. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4346. },
  4347. ]
  4348. : []),
  4349. {
  4350. key: 'aux',
  4351. label: t('printers.fans.auxiliary'),
  4352. value: status.big_fan1_speed ?? 0,
  4353. Icon: Wind,
  4354. activeClass: 'text-blue-600 dark:text-blue-400',
  4355. },
  4356. ...(showChamberFan
  4357. ? [
  4358. {
  4359. key: 'chamber',
  4360. label: chamberFanLabel,
  4361. value: status.big_fan2_speed ?? 0,
  4362. Icon: AirVent,
  4363. activeClass: 'text-green-600 dark:text-green-400',
  4364. },
  4365. ]
  4366. : []),
  4367. ];
  4368. return (
  4369. <>
  4370. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4371. {/* Nozzle temp - combined for dual nozzle */}
  4372. <div
  4373. className={statusControlClass}
  4374. title={statusControlTitle}
  4375. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4376. >
  4377. <button
  4378. type="button"
  4379. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4380. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4381. onClick={(e) => {
  4382. e.stopPropagation();
  4383. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4384. }}
  4385. >
  4386. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4387. </button>
  4388. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4389. {status.temperatures.nozzle_2 !== undefined ? (
  4390. <>
  4391. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4392. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4393. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4394. </p>
  4395. </>
  4396. ) : singleNozzleSlot ? (
  4397. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4398. <div className="cursor-default">
  4399. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4400. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4401. {Math.round(status.temperatures.nozzle || 0)}°C
  4402. </p>
  4403. </div>
  4404. </NozzleSlotHoverCard>
  4405. ) : (
  4406. <>
  4407. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4408. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4409. {Math.round(status.temperatures.nozzle || 0)}°C
  4410. </p>
  4411. </>
  4412. )}
  4413. {statusControlMenu === 'nozzle-temp' && (
  4414. isDualNozzle ? (
  4415. <IndicatorControlPopover
  4416. title="Set Nozzle Temperatures"
  4417. widthClass="w-[300px]"
  4418. popoverWidth={300}
  4419. popoverHeight={260}
  4420. isPending={nozzleTemperatureMutation.isPending}
  4421. onClose={() => setStatusControlMenu(null)}
  4422. >
  4423. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4424. <NozzleTemperatureControlBox
  4425. label="Left Temp"
  4426. current={status.temperatures.nozzle}
  4427. target={status.temperatures.nozzle_target}
  4428. isActive={activeNozzle === 'L'}
  4429. isPending={nozzleTemperatureMutation.isPending}
  4430. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4431. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4432. />
  4433. <NozzleTemperatureControlBox
  4434. label="Right Temp"
  4435. current={status.temperatures.nozzle_2}
  4436. target={status.temperatures.nozzle_2_target}
  4437. isActive={activeNozzle === 'R'}
  4438. isPending={nozzleTemperatureMutation.isPending}
  4439. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4440. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4441. />
  4442. </div>
  4443. </IndicatorControlPopover>
  4444. ) : (
  4445. <IndicatorControlPopover
  4446. title="Set Nozzle Temperature"
  4447. unit="°C"
  4448. customMin={0}
  4449. customMax={320}
  4450. isPending={nozzleTemperatureMutation.isPending}
  4451. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4452. onClose={() => setStatusControlMenu(null)}
  4453. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4454. />
  4455. )
  4456. )}
  4457. </div>
  4458. <div
  4459. className={statusControlClass}
  4460. title={statusControlTitle}
  4461. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4462. >
  4463. <button
  4464. type="button"
  4465. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4466. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4467. onClick={(e) => {
  4468. e.stopPropagation();
  4469. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4470. }}
  4471. >
  4472. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4473. </button>
  4474. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4475. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4476. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4477. {Math.round(status.temperatures.bed || 0)}°C
  4478. </p>
  4479. {statusControlMenu === 'bed-temp' && (
  4480. <IndicatorControlPopover
  4481. title="Set Bed Temperature"
  4482. unit="°C"
  4483. customMin={0}
  4484. customMax={140}
  4485. isPending={bedTemperatureMutation.isPending}
  4486. options={buildPresetOptions(bedTempPresets, 'C')}
  4487. onClose={() => setStatusControlMenu(null)}
  4488. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4489. />
  4490. )}
  4491. </div>
  4492. {status.temperatures.chamber !== undefined && (() => {
  4493. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4494. // but can't act on M141, so we keep the card read-only there.
  4495. const hasChamberHeater = status.supports_chamber_heater === true;
  4496. return (
  4497. <div
  4498. className={hasChamberHeater
  4499. ? statusControlClass
  4500. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4501. title={hasChamberHeater ? statusControlTitle : undefined}
  4502. onClick={hasChamberHeater
  4503. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4504. : undefined}
  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: 'chamber', 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-green-400" isHeating={chamberHeating} />
  4518. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4519. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4520. {Math.round(status.temperatures.chamber || 0)}°C
  4521. </p>
  4522. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4523. <IndicatorControlPopover
  4524. title="Set Chamber Temperature"
  4525. unit="°C"
  4526. customMin={0}
  4527. customMax={MAX_CHAMBER_TEMP_C}
  4528. isPending={chamberTemperatureMutation.isPending}
  4529. options={buildPresetOptions(chamberTempPresets, 'C')}
  4530. onClose={() => setStatusControlMenu(null)}
  4531. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4532. />
  4533. )}
  4534. </div>
  4535. );
  4536. })()}
  4537. {/* Active nozzle indicator for dual-nozzle printers */}
  4538. {isDualNozzle && (
  4539. <DualNozzleHoverCard
  4540. leftSlot={leftNozzleSlot}
  4541. rightSlot={rightNozzleSlot}
  4542. activeNozzle={activeNozzle}
  4543. filamentInfo={filamentInfo}
  4544. >
  4545. <div
  4546. 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 ${
  4547. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4548. }`}
  4549. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4550. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4551. >
  4552. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4553. <div className="flex items-center gap-2">
  4554. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4555. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4556. </span>
  4557. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4558. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4559. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4560. </span>
  4561. </div>
  4562. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4563. {statusControlMenu === 'nozzle-select' && (
  4564. <IndicatorControlPopover
  4565. title="Set Nozzle Selection"
  4566. widthClass="w-[300px]"
  4567. popoverWidth={300}
  4568. popoverHeight={140}
  4569. isPending={selectExtruderMutation.isPending}
  4570. options={[
  4571. { label: 'Left', value: 1 },
  4572. { label: 'Right', value: 0 },
  4573. ]}
  4574. onClose={() => setStatusControlMenu(null)}
  4575. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4576. />
  4577. )}
  4578. </div>
  4579. </DualNozzleHoverCard>
  4580. )}
  4581. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4582. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4583. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4584. )}
  4585. </div>
  4586. <div className="mt-2 flex items-center gap-1.5">
  4587. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4588. const active = value > 0;
  4589. return (
  4590. <div
  4591. key={key}
  4592. 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 ${
  4593. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4594. }`}
  4595. title={canUseStatusControls ? label : statusControlTitle}
  4596. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4597. >
  4598. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4599. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4600. {value}%
  4601. </span>
  4602. {statusControlMenu === `fan-${key}` && (
  4603. <IndicatorControlPopover
  4604. title={`Set ${label} Speed`}
  4605. unit="%"
  4606. customMin={0}
  4607. customMax={100}
  4608. isPending={fanSpeedMutation.isPending}
  4609. options={buildPresetOptions(fanSpeedPresets, '%')}
  4610. onClose={() => setStatusControlMenu(null)}
  4611. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4612. />
  4613. )}
  4614. </div>
  4615. );
  4616. })}
  4617. </div>
  4618. </>
  4619. );
  4620. })()}
  4621. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4622. {/* Controls */}
  4623. {viewMode === 'expanded' && (() => {
  4624. // Determine print state for control buttons
  4625. const isRunning = status.state === 'RUNNING';
  4626. const isPaused = status.state === 'PAUSE';
  4627. const isPrinting = isRunning || isPaused;
  4628. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4629. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4630. 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';
  4631. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4632. return (
  4633. <div className="mt-3">
  4634. {/* Section Header */}
  4635. <div className="flex items-center gap-2 mb-2">
  4636. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4637. {t('printers.controls')}
  4638. </span>
  4639. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4640. </div>
  4641. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4642. {/* Left: Secondary controls */}
  4643. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4644. <button
  4645. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4646. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4647. className={`${iconControlClass} ${
  4648. status.chamber_light
  4649. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4650. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4651. }`}
  4652. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4653. >
  4654. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4655. </button>
  4656. {/* Airduct Mode (P2S / X2D / H2*) */}
  4657. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4658. const isHeating = status.airduct_mode === 1;
  4659. const Icon = isHeating ? Flame : Snowflake;
  4660. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4661. 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';
  4662. return (
  4663. <div className="relative">
  4664. <button
  4665. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4666. disabled={!hasPermission('printers:control')}
  4667. className={`${iconControlClass} ${bg}`}
  4668. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4669. >
  4670. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4671. </button>
  4672. {showAirductMenu === printer.id && (
  4673. <>
  4674. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4675. <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]">
  4676. {([
  4677. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4678. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4679. ] as const).map(({ mode, label, modeId }) => (
  4680. <button
  4681. key={mode}
  4682. onClick={() => {
  4683. airductMutation.mutate(mode);
  4684. setShowAirductMenu(null);
  4685. }}
  4686. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4687. status.airduct_mode === modeId
  4688. ? 'text-bambu-green bg-bambu-green/10'
  4689. : 'text-white hover:bg-bambu-dark-tertiary'
  4690. }`}
  4691. >
  4692. {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)]" />}
  4693. {label}
  4694. </button>
  4695. ))}
  4696. </div>
  4697. </>
  4698. )}
  4699. </div>
  4700. );
  4701. })()}
  4702. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4703. {(() => {
  4704. const canControl = hasPermission('printers:control');
  4705. const disabled = isPrinting || !canControl;
  4706. 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';
  4707. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4708. // nozzle-bed gap that means the same thing on every printer, so the
  4709. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4710. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4711. // plate toward the nozzle and closes it.
  4712. const zMovesToolhead = isBedSlinger(printer.model);
  4713. const requestZJog = (arrow: 'up' | 'down') => {
  4714. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4715. // No not-homed gate here, and no endstop bypass to gate either:
  4716. // since #2579 the jog is a bare move that never touches M211. That
  4717. // does not make it clamped — the firmware ignores soft endstops on
  4718. // MQTT G-code entirely, which is what the banner above warns about.
  4719. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4720. };
  4721. const requestXyJog = (x: number, y: number) => {
  4722. xyJogMutation.mutate({ x, y });
  4723. };
  4724. const requestExtruderJog = (distance: number) => {
  4725. extruderJogMutation.mutate(distance);
  4726. };
  4727. return (
  4728. <div className="relative">
  4729. <button
  4730. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4731. disabled={disabled}
  4732. className={`${iconControlClass} ${
  4733. disabled
  4734. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4735. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4736. }`}
  4737. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4738. >
  4739. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4740. </button>
  4741. {showBedJogMenu === printer.id && (
  4742. <>
  4743. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4744. <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">
  4745. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4746. {t('printers.bedJog.title')}
  4747. </div>
  4748. <div className="h-px bg-bambu-dark-tertiary" />
  4749. {/* #2579: Bambu firmware does not enforce soft endstops on
  4750. G-code sent over MQTT, so manual moves can drive past the
  4751. travel limits and cause a collision. Not fixable from our
  4752. side — warn prominently. */}
  4753. <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">
  4754. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4755. <span>{t('printers.bedJog.limitWarning')}</span>
  4756. </div>
  4757. <div className="h-px bg-bambu-dark-tertiary" />
  4758. <div className="flex justify-center px-3 py-2.5">
  4759. <div className="flex items-center justify-center gap-3">
  4760. <div className="grid grid-cols-3 gap-1">
  4761. <div />
  4762. <button
  4763. onClick={() => requestXyJog(0, bedJogStep)}
  4764. disabled={xyJogMutation.isPending}
  4765. className={jogButtonClass}
  4766. aria-label="Move Y forward"
  4767. >
  4768. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4769. </button>
  4770. <div />
  4771. <button
  4772. onClick={() => requestXyJog(-bedJogStep, 0)}
  4773. disabled={xyJogMutation.isPending}
  4774. className={jogButtonClass}
  4775. aria-label="Move X left"
  4776. >
  4777. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4778. </button>
  4779. <button
  4780. onClick={() => {
  4781. setShowBedJogMenu(null);
  4782. homeAxesMutation.mutate('all');
  4783. }}
  4784. disabled={homeAxesMutation.isPending}
  4785. className={jogButtonClass}
  4786. aria-label={t('printers.bedJog.homeZ')}
  4787. >
  4788. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4789. </button>
  4790. <button
  4791. onClick={() => requestXyJog(bedJogStep, 0)}
  4792. disabled={xyJogMutation.isPending}
  4793. className={jogButtonClass}
  4794. aria-label="Move X right"
  4795. >
  4796. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4797. </button>
  4798. <div />
  4799. <button
  4800. onClick={() => requestXyJog(0, -bedJogStep)}
  4801. disabled={xyJogMutation.isPending}
  4802. className={jogButtonClass}
  4803. aria-label="Move Y back"
  4804. >
  4805. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4806. </button>
  4807. <div />
  4808. </div>
  4809. <div className="flex flex-col items-center gap-1">
  4810. <button
  4811. onClick={() => requestZJog('up')}
  4812. disabled={bedJogMutation.isPending}
  4813. className={jogButtonClass}
  4814. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4815. >
  4816. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4817. </button>
  4818. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4819. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4820. </div>
  4821. <button
  4822. onClick={() => requestZJog('down')}
  4823. disabled={bedJogMutation.isPending}
  4824. className={jogButtonClass}
  4825. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4826. >
  4827. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4828. </button>
  4829. </div>
  4830. <div className="flex flex-col items-center gap-1">
  4831. <button
  4832. onClick={() => requestExtruderJog(-bedJogStep)}
  4833. disabled={extruderJogMutation.isPending}
  4834. className={jogButtonClass}
  4835. aria-label="Retract filament"
  4836. >
  4837. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4838. </button>
  4839. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4840. <span className="text-sm font-semibold leading-none">E</span>
  4841. </div>
  4842. <button
  4843. onClick={() => requestExtruderJog(bedJogStep)}
  4844. disabled={extruderJogMutation.isPending}
  4845. className={jogButtonClass}
  4846. aria-label="Extrude filament"
  4847. >
  4848. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4849. </button>
  4850. </div>
  4851. </div>
  4852. </div>
  4853. <div className="h-px bg-bambu-dark-tertiary" />
  4854. <div className="px-3 pt-2.5 pb-3">
  4855. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4856. {t('printers.bedJog.step')}
  4857. </div>
  4858. <div className="flex gap-1">
  4859. {[1, 10, 50].map((step) => (
  4860. <button
  4861. key={step}
  4862. onClick={() => setBedJogStep(step)}
  4863. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4864. bedJogStep === step
  4865. ? 'bg-bambu-green/20 text-bambu-green'
  4866. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4867. }`}
  4868. >
  4869. {step}
  4870. </button>
  4871. ))}
  4872. </div>
  4873. </div>
  4874. </div>
  4875. </>
  4876. )}
  4877. </div>
  4878. );
  4879. })()}
  4880. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4881. <button
  4882. onClick={handleTogglePlateDetection}
  4883. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4884. className={`${iconControlClass} rounded-r-none ${
  4885. printer.plate_detection_enabled
  4886. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4887. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4888. }`}
  4889. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4890. >
  4891. {plateDetectionMutation.isPending ? (
  4892. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4893. ) : (
  4894. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4895. )}
  4896. </button>
  4897. <button
  4898. onClick={handleOpenPlateManagement}
  4899. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4900. 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 ${
  4901. printer.plate_detection_enabled
  4902. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4903. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4904. }`}
  4905. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4906. >
  4907. {isCheckingPlate ? (
  4908. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4909. ) : (
  4910. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4911. )}
  4912. </button>
  4913. </div>
  4914. {/* Print Speed */}
  4915. {(() => (
  4916. <div className="relative">
  4917. <button
  4918. data-testid="speed-control"
  4919. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4920. disabled={!isPrinting || !hasPermission('printers:control')}
  4921. className={`${iconControlClass} ${
  4922. isPrinting
  4923. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4924. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4925. }`}
  4926. title={isPrinting ? t('printers.speed.title') : undefined}
  4927. >
  4928. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4929. </button>
  4930. {showSpeedMenu === printer.id && (
  4931. <>
  4932. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4933. <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]">
  4934. {([
  4935. { mode: 1, label: t('printers.speed.silent') },
  4936. { mode: 2, label: t('printers.speed.standard') },
  4937. { mode: 3, label: t('printers.speed.sport') },
  4938. { mode: 4, label: t('printers.speed.ludicrous') },
  4939. ] as const).map(({ mode, label }) => (
  4940. <button
  4941. key={mode}
  4942. onClick={() => {
  4943. printSpeedMutation.mutate(mode);
  4944. setShowSpeedMenu(null);
  4945. }}
  4946. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4947. status.speed_level === mode
  4948. ? 'text-bambu-green bg-bambu-green/10'
  4949. : 'text-white hover:bg-bambu-dark-tertiary'
  4950. }`}
  4951. >
  4952. {label}
  4953. </button>
  4954. ))}
  4955. </div>
  4956. </>
  4957. )}
  4958. </div>
  4959. ))()}
  4960. </div>
  4961. {/* Right: Print Control Buttons */}
  4962. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4963. {/* Pause/Resume button */}
  4964. {(() => {
  4965. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4966. return (
  4967. <button
  4968. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4969. disabled={pauseUnavailable}
  4970. className={`
  4971. ${printControlClass}
  4972. ${pauseUnavailable
  4973. ? unavailablePrintActionClass
  4974. : isPaused
  4975. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4976. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4977. }
  4978. `}
  4979. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4980. >
  4981. {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)]" />}
  4982. {isPaused ? t('printers.resume') : t('printers.pause')}
  4983. </button>
  4984. );
  4985. })()}
  4986. {/* Stop button */}
  4987. {(() => {
  4988. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4989. return (
  4990. <button
  4991. onClick={() => setShowStopConfirm(true)}
  4992. disabled={stopUnavailable}
  4993. className={`
  4994. ${printControlClass}
  4995. ${stopUnavailable
  4996. ? unavailablePrintActionClass
  4997. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4998. }
  4999. `}
  5000. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  5001. >
  5002. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5003. {t('printers.stop')}
  5004. </button>
  5005. );
  5006. })()}
  5007. </div>
  5008. </div>
  5009. </div>
  5010. );
  5011. })()}
  5012. {/* AMS Units - 2-Column Grid Layout */}
  5013. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  5014. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  5015. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  5016. const htAms = amsData.filter(ams => ams.tray.length === 1);
  5017. // The external spool can only be hidden while some AMS remains to
  5018. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  5019. // filament section, so the toggle is not offered there and a stored
  5020. // preference from a printer that later lost its AMS cannot blank the
  5021. // row either — both read through canHideExternalSpool.
  5022. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  5023. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5024. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5025. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5026. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5027. // floating point, and that lands verbatim in the DOM.
  5028. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5029. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5030. // already grow to fill the row, so the 3.5rem is a floor they sit
  5031. // well above in practice -- raising it just costs a unit its place
  5032. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5033. // its line, and flex-grow stretches its single slot across the whole
  5034. // card. The AMS-HT's own width does scale, below, because its
  5035. // readings sit beside the slot rather than under it.
  5036. const slotMinWidth = '3.5rem';
  5037. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5038. // The AMS-HT holds a single spool, and its slot is the only thing
  5039. // on that row able to grow -- so it swallowed every spare pixel and
  5040. // shoved the temperature and humidity hard against the card's edge.
  5041. // Capping it at roughly two ordinary slots keeps the readings clear
  5042. // of the edge; the cap scales because the text inside the slot does.
  5043. const htSlotStyle: React.CSSProperties = {
  5044. minWidth: slotMinWidth,
  5045. maxWidth: scaledRem(7.25),
  5046. };
  5047. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5048. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5049. });
  5050. // #1762 (comment 2): while a print is running/paused, overlay a small
  5051. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5052. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5053. // staged to a printer with mismatched filament: the wrong-slot pill
  5054. // is visible the instant printing starts.
  5055. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5056. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5057. ? status.ams_mapping
  5058. : [];
  5059. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5060. const boundedSlotCount = Math.max(1, slotCount);
  5061. const gapCount = Math.max(0, boundedSlotCount - 1);
  5062. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5063. return {
  5064. flex: `1 1 ${minWidth}`,
  5065. minWidth,
  5066. };
  5067. };
  5068. return (
  5069. <div className="mt-3">
  5070. {/* Section Header */}
  5071. <div className="flex items-center gap-2 mb-2">
  5072. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5073. {t('printers.filaments')}
  5074. </span>
  5075. <AmsBackupBadge
  5076. state={status.ams_filament_backup}
  5077. onClick={() => setAmsBackupModalOpen(true)}
  5078. />
  5079. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5080. {/* Offered only when an AMS is present: on a printer that
  5081. feeds from the external spool alone, hiding it would
  5082. empty the row entirely (#1782). */}
  5083. {canHideExternalSpool && (
  5084. <>
  5085. <ExternalSpoolToggle
  5086. hidden={externalSpoolHidden}
  5087. onClick={toggleExternalSpool}
  5088. />
  5089. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5090. </>
  5091. )}
  5092. </div>
  5093. {/* AMS Content */}
  5094. <div className="flex flex-wrap gap-2">
  5095. {/* Regular AMS units */}
  5096. {regularAms.map((ams) => {
  5097. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5098. return (
  5099. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5100. {/* Header: Label + Stats (no icon) */}
  5101. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5102. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5103. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5104. <AmsNameHoverCard
  5105. ams={ams}
  5106. printerId={printer.id}
  5107. label={getAmsLabel(ams.id, ams.tray.length)}
  5108. amsLabels={amsLabels}
  5109. canEdit={hasPermission('printers:update')}
  5110. onSaved={refetchAmsLabels}
  5111. >
  5112. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5113. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5114. </span>
  5115. </AmsNameHoverCard>
  5116. {sideBadge?.kind === 'inlet' ? (
  5117. <InletBadge
  5118. inlet={sideBadge.inlet}
  5119. title={t('printers.amsSwitchInletTooltip', {
  5120. inlet: sideBadge.inlet,
  5121. side: FTS_INLET_SIDE[sideBadge.inlet],
  5122. })}
  5123. />
  5124. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5125. <NozzleBadge side={sideBadge.side} />
  5126. ) : null}
  5127. </div>
  5128. {(ams.humidity != null || ams.temp != null) && (
  5129. <div className="flex shrink-0 items-center gap-1.5">
  5130. {ams.humidity != null && (
  5131. <HumidityIndicator
  5132. humidity={ams.humidity}
  5133. goodThreshold={amsThresholds?.humidityGood}
  5134. fairThreshold={amsThresholds?.humidityFair}
  5135. onClick={() => setAmsHistoryModal({
  5136. amsId: ams.id,
  5137. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5138. mode: 'humidity',
  5139. })}
  5140. compact
  5141. />
  5142. )}
  5143. {ams.temp != null && (
  5144. <div className="mr-1">
  5145. <TemperatureIndicator
  5146. temp={ams.temp}
  5147. goodThreshold={amsThresholds?.tempGood}
  5148. fairThreshold={amsThresholds?.tempFair}
  5149. onClick={() => setAmsHistoryModal({
  5150. amsId: ams.id,
  5151. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5152. mode: 'temperature',
  5153. })}
  5154. compact
  5155. />
  5156. </div>
  5157. )}
  5158. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5159. Screen-only models (P1 series) keep the control but can't
  5160. be commanded: it stays disabled and says why (#2533). */}
  5161. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5162. <button
  5163. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5164. onClick={(e) => {
  5165. if (ams.dry_time > 0) {
  5166. stopDryingMutation.mutate(ams.id);
  5167. } else if (dryingPopoverAmsId === ams.id) {
  5168. setDryingPopoverAmsId(null);
  5169. } else {
  5170. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5171. }
  5172. }}
  5173. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5174. ams.dry_time > 0
  5175. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5176. : status.drying_screen_only || ams.dry_sf_reason?.length
  5177. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5178. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5179. }`}
  5180. 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')}
  5181. >
  5182. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5183. </button>
  5184. )}
  5185. </div>
  5186. )}
  5187. </div>
  5188. {/* Drying status bar. A dry_time whose countdown is not
  5189. ticking, with no active drying phase (a parked command —
  5190. e.g. an H2D mid-print already powering other drying — or
  5191. a paused cycle), is shown as "not running", not as an
  5192. active cycle: the amber badge claiming a running dry
  5193. that the AMS never began is how this was found. */}
  5194. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5195. <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')}>
  5196. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5197. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5198. {ams.dry_filament && (
  5199. <span className="text-slate-500/90 dark:text-slate-400/80">
  5200. {ams.dry_target_temp != null
  5201. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5202. : ams.dry_filament}
  5203. </span>
  5204. )}
  5205. {!status.drying_screen_only && (
  5206. <button
  5207. onClick={() => stopDryingMutation.mutate(ams.id)}
  5208. disabled={stopDryingMutation.isPending}
  5209. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5210. title={t('printers.drying.stop')}
  5211. >
  5212. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5213. </button>
  5214. )}
  5215. </div>
  5216. )}
  5217. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5218. <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)]">
  5219. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5220. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5221. {/* The temperature is only ever known from the target we
  5222. cached when sending the command — the filament can also
  5223. be read off a uniformly loaded unit, so it can outlive
  5224. the temperature (#2759). */}
  5225. {ams.dry_filament && (
  5226. <span className="text-amber-700/80 dark:text-amber-300/70">
  5227. {ams.dry_target_temp != null
  5228. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5229. : ams.dry_filament}
  5230. </span>
  5231. )}
  5232. <span className="text-amber-700/80 dark:text-amber-300/70">
  5233. {t('printers.drying.timeRemaining', {
  5234. time: ams.dry_time >= 60
  5235. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5236. : `${ams.dry_time}m`
  5237. })}
  5238. </span>
  5239. {/* A cycle on a screen-only model was started at the printer
  5240. and can only be stopped there (#2533). */}
  5241. {!status.drying_screen_only && (
  5242. <button
  5243. onClick={() => stopDryingMutation.mutate(ams.id)}
  5244. disabled={stopDryingMutation.isPending}
  5245. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5246. title={t('printers.drying.stop')}
  5247. >
  5248. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5249. </button>
  5250. )}
  5251. </div>
  5252. )}
  5253. {/* Slots grid: 4 columns - always render 4 slots */}
  5254. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5255. {[0, 1, 2, 3].map((slotIdx) => {
  5256. // Find tray data for this slot (may be undefined if data incomplete)
  5257. // Use array index if available, as tray.id may not always be set
  5258. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5259. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5260. const isEmpty = !tray?.tray_type;
  5261. const emptyKind = getEmptySlotKind(tray);
  5262. // Check if this is the currently loaded tray
  5263. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5264. const globalTrayId = ams.id * 4 + slotIdx;
  5265. const isActive = effectiveTrayNow === globalTrayId;
  5266. // Runout guidance (#2587): the slot the paused print now
  5267. // expects filament in, and the slot that ran out.
  5268. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5269. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5270. // Get cloud preset info if available
  5271. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5272. // Get saved slot preset mapping (for user-configured slots)
  5273. const slotPreset = slotPresets?.[globalTrayId];
  5274. // Only trusted while it still describes what the printer reports in the
  5275. // slot: the row survives a spool swap, and the display chain below puts
  5276. // it ahead of the live filament id (see slotPresetDescribesTray).
  5277. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5278. ? slotPreset?.preset_name
  5279. : undefined;
  5280. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5281. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5282. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5283. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5284. // Slot-assigned-only spool fill (no tag link required)
  5285. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5286. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5287. : undefined;
  5288. const slotSpoolForFill = slotAssignmentForFill
  5289. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5290. : undefined;
  5291. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5292. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5293. : null;
  5294. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5295. const inventoryFill = (() => {
  5296. const sp = inventoryAssignment?.spool;
  5297. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5298. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5299. }
  5300. return null;
  5301. })();
  5302. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5303. // (inventory weight_used may be stale or over-counted — #676)
  5304. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5305. ? null : inventoryFill;
  5306. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5307. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5308. : resolvedInventoryFill !== null ? 'inventory' as const
  5309. : hasFillLevel ? 'ams' as const
  5310. : undefined;
  5311. // Build filament data for hover card
  5312. const filamentData = tray?.tray_type ? {
  5313. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5314. // Spoolman spool name wins over cloud lookup so a slot bound to
  5315. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5316. // Design PLA") instead of whatever the printer's filament_id
  5317. // resolves to in the cloud catalog (often "Generic PLA" for
  5318. // P-prefix local presets). Spoolman's filament.name is just the
  5319. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5320. // the hover card shows "Devil Design PLA Basic" rather than the
  5321. // vendor-less form. Strip the "@<printer>..." suffix that
  5322. // BambuStudio appends to user-preset names.
  5323. 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,
  5324. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5325. colorHex: tray.tray_color || null,
  5326. kFactor: formatKValue(tray.k),
  5327. fillLevel: effectiveFill,
  5328. trayUuid: tray.tray_uuid || null,
  5329. tagUid: tray.tag_uid || null,
  5330. fillSource,
  5331. } : null;
  5332. // Check if this specific slot is being refreshed
  5333. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5334. refreshingSlot?.slotId === slotIdx;
  5335. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5336. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5337. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5338. ? `P${activePrintSlotIdx + 1}`
  5339. : null;
  5340. // Slot visual content (goes inside hover card)
  5341. const slotVisual = (
  5342. <div
  5343. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5344. isExpectedSlot
  5345. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5346. : isRanOutSlot
  5347. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5348. : isActive
  5349. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5350. : ''
  5351. }`}
  5352. >
  5353. {isExpectedSlot && (
  5354. <span
  5355. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5356. title={t('printers.expectedSlot.title')}
  5357. 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"
  5358. >
  5359. ↓
  5360. </span>
  5361. )}
  5362. {activePrintSlotLabel && (
  5363. <span
  5364. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5365. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5366. 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"
  5367. >
  5368. {activePrintSlotLabel}
  5369. </span>
  5370. )}
  5371. {/* Filament color circle with 1-based slot number centered inside */}
  5372. <FilamentSlotCircle
  5373. trayColor={tray?.tray_color}
  5374. trayType={tray?.tray_type}
  5375. isEmpty={isEmpty}
  5376. emptyKind={emptyKind}
  5377. slotNumber={slotIdx + 1}
  5378. />
  5379. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5380. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5381. </div>
  5382. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5383. {/* Fill bar */}
  5384. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5385. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5386. <div
  5387. className="h-full rounded-full transition-all"
  5388. style={{
  5389. width: `${effectiveFill}%`,
  5390. backgroundColor: getFillBarColor(effectiveFill),
  5391. }}
  5392. />
  5393. )}
  5394. </div>
  5395. </div>
  5396. );
  5397. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5398. return (
  5399. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5400. {/* Loading overlay during RFID re-read */}
  5401. {isRefreshing && (
  5402. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5403. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5404. </div>
  5405. )}
  5406. {/* Hover card wraps only the visual content */}
  5407. {filamentData ? (
  5408. <FilamentHoverCard
  5409. data={filamentData}
  5410. actions={renderAmsSlotActions({
  5411. amsId: ams.id,
  5412. slotId: slotIdx,
  5413. loadTrayId: ams.id * 4 + slotIdx,
  5414. isRefreshing,
  5415. })}
  5416. spoolman={{
  5417. enabled: spoolmanEnabled,
  5418. // #1457: slot assignment is the user's most explicit action — it must
  5419. // outrank the tag-link, which can be stale when a non-RFID slot's
  5420. // fallback tag is still attached to a previous spool in Spoolman.
  5421. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5422. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5423. spoolmanUrl,
  5424. syncMode: spoolmanSyncMode,
  5425. // Suppress Link button when slot is already occupied by ANY assignment
  5426. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5427. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5428. // still appearing on slots with a local Devil Design PLA assigned.
  5429. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5430. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5431. setLinkSpoolModal({
  5432. tagUid: filamentData.tagUid || linkTag,
  5433. trayUuid: filamentData.trayUuid || '',
  5434. printerId: printer.id,
  5435. amsId: ams.id,
  5436. trayId: slotIdx,
  5437. });
  5438. } : undefined,
  5439. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5440. }}
  5441. inventory={(() => {
  5442. if (spoolmanEnabled) {
  5443. if (spoolmanLoading) return undefined;
  5444. const slotAssignment = slotAssignmentForFill;
  5445. const spoolmanSpool = slotSpoolForFill;
  5446. return {
  5447. assignedSpool: spoolmanSpool ? {
  5448. id: spoolmanSpool.id,
  5449. material: spoolmanSpool.material,
  5450. subtype: spoolmanSpool.subtype,
  5451. brand: spoolmanSpool.brand ?? null,
  5452. color_name: spoolmanSpool.color_name ?? null,
  5453. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5454. // The spool's own swatch (#2967). Spoolman carries the
  5455. // extra stops but has no effect field at all, so those
  5456. // rolls gradient and never shimmer.
  5457. rgba: spoolmanSpool.rgba ?? null,
  5458. extra_colors: spoolmanSpool.extra_colors ?? null,
  5459. effect_type: spoolmanSpool.effect_type ?? null,
  5460. remainingWeightGrams: spoolmanSpool.label_weight
  5461. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5462. : undefined,
  5463. } : null,
  5464. onAssignSpool: () => setAssignSpoolModal({
  5465. printerId: printer.id,
  5466. amsId: ams.id,
  5467. trayId: slotIdx,
  5468. trayInfo: {
  5469. type: tray?.tray_type || filamentData.profile,
  5470. material: tray?.tray_type ?? undefined,
  5471. profile: filamentData.profile,
  5472. color: filamentData.colorHex || '',
  5473. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5474. },
  5475. }),
  5476. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5477. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5478. };
  5479. }
  5480. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5481. return {
  5482. assignedSpool: assignment?.spool ? {
  5483. id: assignment.spool.id,
  5484. material: assignment.spool.material,
  5485. subtype: assignment.spool.subtype,
  5486. brand: assignment.spool.brand,
  5487. color_name: assignment.spool.color_name,
  5488. // The spool's own swatch (#2967).
  5489. rgba: assignment.spool.rgba ?? null,
  5490. extra_colors: assignment.spool.extra_colors ?? null,
  5491. effect_type: assignment.spool.effect_type ?? null,
  5492. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5493. } : null,
  5494. onAssignSpool: () => setAssignSpoolModal({
  5495. printerId: printer.id,
  5496. amsId: ams.id,
  5497. trayId: slotIdx,
  5498. trayInfo: {
  5499. type: tray?.tray_type || filamentData.profile,
  5500. material: tray?.tray_type ?? undefined,
  5501. profile: filamentData.profile,
  5502. color: filamentData.colorHex || '',
  5503. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5504. },
  5505. }),
  5506. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5507. isAssigned: !!assignment || isBambuLabSpool(tray),
  5508. };
  5509. })()}
  5510. configureSlot={{
  5511. enabled: hasPermission('printers:control'),
  5512. onConfigure: () => setConfigureSlotModal({
  5513. amsId: ams.id,
  5514. trayId: slotIdx,
  5515. trayCount: ams.tray.length,
  5516. trayType: tray?.tray_type || undefined,
  5517. trayColor: tray?.tray_color || undefined,
  5518. traySubBrands: tray?.tray_sub_brands || undefined,
  5519. trayInfoIdx: tray?.tray_info_idx || undefined,
  5520. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5521. caliIdx: tray?.cali_idx,
  5522. savedPresetId: slotPreset?.preset_id,
  5523. }),
  5524. }}
  5525. >
  5526. {slotVisual}
  5527. </FilamentHoverCard>
  5528. ) : (
  5529. <EmptySlotHoverCard
  5530. kind={emptyKind ?? undefined}
  5531. actions={renderAmsSlotActions({
  5532. amsId: ams.id,
  5533. slotId: slotIdx,
  5534. loadTrayId: ams.id * 4 + slotIdx,
  5535. isRefreshing,
  5536. })}
  5537. configureSlot={{
  5538. enabled: hasPermission('printers:control'),
  5539. onConfigure: () => setConfigureSlotModal({
  5540. amsId: ams.id,
  5541. trayId: slotIdx,
  5542. trayCount: ams.tray.length,
  5543. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5544. }),
  5545. }}
  5546. onAssignSpool={() => setAssignSpoolModal({
  5547. printerId: printer.id,
  5548. amsId: ams.id,
  5549. trayId: slotIdx,
  5550. trayInfo: {
  5551. type: '',
  5552. material: undefined,
  5553. profile: '',
  5554. color: '',
  5555. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5556. },
  5557. })}
  5558. >
  5559. {slotVisual}
  5560. </EmptySlotHoverCard>
  5561. )}
  5562. </div>
  5563. );
  5564. })}
  5565. </div>
  5566. </div>
  5567. );
  5568. })}
  5569. {/* HT AMS units */}
  5570. {htAms.map((ams) => {
  5571. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5572. const tray = ams.tray[0];
  5573. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5574. const isEmpty = !tray?.tray_type;
  5575. const emptyKind = getEmptySlotKind(tray);
  5576. // Check if this is the currently loaded tray
  5577. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5578. const isActive = effectiveTrayNow === globalTrayId;
  5579. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5580. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5581. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5582. // Get cloud preset info if available
  5583. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5584. // Get saved slot preset mapping (for user-configured slots)
  5585. const slotPreset = slotPresets?.[globalTrayId];
  5586. // Only trusted while it still describes what the printer reports in the
  5587. // slot: the row survives a spool swap, and the display chain below puts
  5588. // it ahead of the live filament id (see slotPresetDescribesTray).
  5589. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5590. ? slotPreset?.preset_name
  5591. : undefined;
  5592. const htSlotId = tray?.id ?? 0;
  5593. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5594. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5595. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5596. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5597. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5598. const htInventoryFill = (() => {
  5599. const sp = htInventoryAssignment?.spool;
  5600. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5601. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5602. }
  5603. return null;
  5604. })();
  5605. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5606. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5607. ? null : htInventoryFill;
  5608. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5609. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5610. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5611. : undefined;
  5612. const htSlotSpoolForFill = htSlotAssignmentForFill
  5613. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5614. : undefined;
  5615. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5616. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5617. : null;
  5618. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5619. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5620. : htResolvedInventoryFill !== null ? 'inventory' as const
  5621. : hasFillLevel ? 'ams' as const
  5622. : undefined;
  5623. // Build filament data for hover card
  5624. const filamentData = tray?.tray_type ? {
  5625. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5626. 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,
  5627. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5628. colorHex: tray.tray_color || null,
  5629. kFactor: formatKValue(tray.k),
  5630. fillLevel: htEffectiveFill,
  5631. trayUuid: tray.tray_uuid || null,
  5632. tagUid: tray.tag_uid || null,
  5633. fillSource: htFillSource,
  5634. } : null;
  5635. // Check if this specific slot is being refreshed
  5636. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5637. refreshingSlot?.slotId === htSlotId;
  5638. // #1762 (comment 2): active print-slot index for this HT slot.
  5639. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5640. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5641. ? `P${htActivePrintSlotIdx + 1}`
  5642. : null;
  5643. // Slot visual content (goes inside hover card)
  5644. const slotVisual = (
  5645. <div
  5646. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5647. isExpectedSlot
  5648. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5649. : isRanOutSlot
  5650. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5651. : isActive
  5652. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5653. : ''
  5654. }`}
  5655. >
  5656. {isExpectedSlot && (
  5657. <span
  5658. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5659. title={t('printers.expectedSlot.title')}
  5660. 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"
  5661. >
  5662. ↓
  5663. </span>
  5664. )}
  5665. {htActivePrintSlotLabel && (
  5666. <span
  5667. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5668. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5669. 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"
  5670. >
  5671. {htActivePrintSlotLabel}
  5672. </span>
  5673. )}
  5674. {/* Filament color circle with 1-based slot number centered inside */}
  5675. <FilamentSlotCircle
  5676. trayColor={tray?.tray_color}
  5677. trayType={tray?.tray_type}
  5678. isEmpty={isEmpty}
  5679. emptyKind={emptyKind}
  5680. slotNumber={1}
  5681. />
  5682. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5683. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5684. </div>
  5685. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5686. {/* Fill bar */}
  5687. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5688. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5689. <div
  5690. className="h-full rounded-full transition-all"
  5691. style={{
  5692. width: `${htEffectiveFill}%`,
  5693. backgroundColor: getFillBarColor(htEffectiveFill),
  5694. }}
  5695. />
  5696. )}
  5697. </div>
  5698. </div>
  5699. );
  5700. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5701. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5702. // Without this override, the L view squishes HT into a sliver next to the
  5703. // 4-slot AMS neighbors.
  5704. // 11rem holds one slot plus the temperature/humidity
  5705. // column beside it; both grow with the body scale.
  5706. const htCardWidth = scaledRem(11);
  5707. const htCardStyle: React.CSSProperties = {
  5708. flex: `1 1 ${htCardWidth}`,
  5709. minWidth: htCardWidth,
  5710. // An AMS-HT is never wider than a full AMS. Without a
  5711. // ceiling, a unit that wraps onto a line of its own is
  5712. // the only flex item there and grow stretches its single
  5713. // slot across the entire card, leaving the readings
  5714. // stranded at the far edge.
  5715. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5716. };
  5717. return (
  5718. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5719. {/* Row 1: Label + Nozzle + Drying */}
  5720. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5721. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5722. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5723. <AmsNameHoverCard
  5724. ams={ams}
  5725. printerId={printer.id}
  5726. label={getAmsLabel(ams.id, ams.tray.length)}
  5727. amsLabels={amsLabels}
  5728. canEdit={hasPermission('printers:update')}
  5729. onSaved={refetchAmsLabels}
  5730. >
  5731. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5732. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5733. </span>
  5734. </AmsNameHoverCard>
  5735. {sideBadge?.kind === 'inlet' ? (
  5736. <InletBadge
  5737. inlet={sideBadge.inlet}
  5738. title={t('printers.amsSwitchInletTooltip', {
  5739. inlet: sideBadge.inlet,
  5740. side: FTS_INLET_SIDE[sideBadge.inlet],
  5741. })}
  5742. />
  5743. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5744. <NozzleBadge side={sideBadge.side} />
  5745. ) : null}
  5746. </div>
  5747. {/* Drying button for HT AMS */}
  5748. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5749. <div className="relative ml-auto">
  5750. <button
  5751. disabled={status.drying_screen_only}
  5752. onClick={(e) => {
  5753. if (ams.dry_time > 0) {
  5754. stopDryingMutation.mutate(ams.id);
  5755. } else if (dryingPopoverAmsId === ams.id) {
  5756. setDryingPopoverAmsId(null);
  5757. } else {
  5758. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5759. }
  5760. }}
  5761. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5762. ams.dry_time > 0
  5763. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5764. : status.drying_screen_only
  5765. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5766. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5767. }`}
  5768. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5769. >
  5770. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5771. </button>
  5772. </div>
  5773. )}
  5774. </div>
  5775. {/* HT AMS drying status bar. Same not-running split as the
  5776. standard-AMS bar above: a frozen countdown is not a
  5777. running cycle. */}
  5778. {ams.dry_time > 0 && (
  5779. <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}>
  5780. {ams.dry_countdown_stalled
  5781. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5782. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5783. {ams.dry_countdown_stalled && (
  5784. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5785. )}
  5786. {ams.dry_filament && (
  5787. <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`}>
  5788. {ams.dry_target_temp != null
  5789. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5790. : ams.dry_filament}
  5791. </span>
  5792. )}
  5793. {!ams.dry_countdown_stalled && (
  5794. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5795. {ams.dry_time >= 60
  5796. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5797. : `${ams.dry_time}m`}
  5798. </span>
  5799. )}
  5800. {!status.drying_screen_only && (
  5801. <button
  5802. onClick={() => stopDryingMutation.mutate(ams.id)}
  5803. disabled={stopDryingMutation.isPending}
  5804. 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"
  5805. title={t('printers.drying.stop')}
  5806. >
  5807. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5808. </button>
  5809. )}
  5810. </div>
  5811. )}
  5812. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5813. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5814. {/* Slot wrapper with loading overlay */}
  5815. <div className="relative group flex-1" style={htSlotStyle}>
  5816. {/* Loading overlay during RFID re-read */}
  5817. {isHtRefreshing && (
  5818. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5819. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5820. </div>
  5821. )}
  5822. {/* Hover card wraps only the visual content */}
  5823. {filamentData ? (
  5824. <FilamentHoverCard
  5825. data={filamentData}
  5826. actions={renderAmsSlotActions({
  5827. amsId: ams.id,
  5828. slotId: htSlotId,
  5829. loadTrayId: ams.id * 4 + htSlotId,
  5830. isRefreshing: isHtRefreshing,
  5831. })}
  5832. spoolman={{
  5833. enabled: spoolmanEnabled,
  5834. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5835. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5836. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5837. spoolmanUrl,
  5838. syncMode: spoolmanSyncMode,
  5839. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5840. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5841. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5842. setLinkSpoolModal({
  5843. tagUid: filamentData.tagUid || linkTag,
  5844. trayUuid: filamentData.trayUuid || '',
  5845. printerId: printer.id,
  5846. amsId: ams.id,
  5847. trayId: htSlotId,
  5848. });
  5849. } : undefined,
  5850. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5851. }}
  5852. inventory={(() => {
  5853. if (spoolmanEnabled) {
  5854. if (spoolmanLoading) return undefined;
  5855. const slotAssignment = htSlotAssignmentForFill;
  5856. const spoolmanSpool = htSlotSpoolForFill;
  5857. return {
  5858. assignedSpool: spoolmanSpool ? {
  5859. id: spoolmanSpool.id,
  5860. material: spoolmanSpool.material,
  5861. subtype: spoolmanSpool.subtype,
  5862. brand: spoolmanSpool.brand ?? null,
  5863. color_name: spoolmanSpool.color_name ?? null,
  5864. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5865. // The spool's own swatch (#2967). Spoolman carries the
  5866. // extra stops but has no effect field at all, so those
  5867. // rolls gradient and never shimmer.
  5868. rgba: spoolmanSpool.rgba ?? null,
  5869. extra_colors: spoolmanSpool.extra_colors ?? null,
  5870. effect_type: spoolmanSpool.effect_type ?? null,
  5871. remainingWeightGrams: spoolmanSpool.label_weight
  5872. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5873. : undefined,
  5874. } : null,
  5875. onAssignSpool: () => setAssignSpoolModal({
  5876. printerId: printer.id,
  5877. amsId: ams.id,
  5878. trayId: htSlotId,
  5879. trayInfo: {
  5880. type: tray?.tray_type || filamentData.profile,
  5881. material: tray?.tray_type ?? undefined,
  5882. profile: filamentData.profile,
  5883. color: filamentData.colorHex || '',
  5884. location: getAmsLabel(ams.id, ams.tray.length),
  5885. },
  5886. }),
  5887. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5888. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5889. };
  5890. }
  5891. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5892. return {
  5893. assignedSpool: assignment?.spool ? {
  5894. id: assignment.spool.id,
  5895. material: assignment.spool.material,
  5896. subtype: assignment.spool.subtype,
  5897. brand: assignment.spool.brand,
  5898. color_name: assignment.spool.color_name,
  5899. // The spool's own swatch (#2967).
  5900. rgba: assignment.spool.rgba ?? null,
  5901. extra_colors: assignment.spool.extra_colors ?? null,
  5902. effect_type: assignment.spool.effect_type ?? null,
  5903. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5904. } : null,
  5905. onAssignSpool: () => setAssignSpoolModal({
  5906. printerId: printer.id,
  5907. amsId: ams.id,
  5908. trayId: htSlotId,
  5909. trayInfo: {
  5910. type: tray?.tray_type || filamentData.profile,
  5911. material: tray?.tray_type ?? undefined,
  5912. profile: filamentData.profile,
  5913. color: filamentData.colorHex || '',
  5914. location: getAmsLabel(ams.id, ams.tray.length),
  5915. },
  5916. }),
  5917. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5918. isAssigned: !!assignment || isBambuLabSpool(tray),
  5919. };
  5920. })()}
  5921. configureSlot={{
  5922. enabled: hasPermission('printers:control'),
  5923. onConfigure: () => setConfigureSlotModal({
  5924. amsId: ams.id,
  5925. trayId: htSlotId,
  5926. trayCount: ams.tray.length,
  5927. trayType: tray?.tray_type || undefined,
  5928. trayColor: tray?.tray_color || undefined,
  5929. traySubBrands: tray?.tray_sub_brands || undefined,
  5930. trayInfoIdx: tray?.tray_info_idx || undefined,
  5931. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5932. caliIdx: tray?.cali_idx,
  5933. savedPresetId: slotPreset?.preset_id,
  5934. }),
  5935. }}
  5936. >
  5937. {slotVisual}
  5938. </FilamentHoverCard>
  5939. ) : (
  5940. <EmptySlotHoverCard
  5941. kind={emptyKind ?? undefined}
  5942. actions={renderAmsSlotActions({
  5943. amsId: ams.id,
  5944. slotId: htSlotId,
  5945. loadTrayId: ams.id * 4 + htSlotId,
  5946. isRefreshing: isHtRefreshing,
  5947. })}
  5948. configureSlot={{
  5949. enabled: hasPermission('printers:control'),
  5950. onConfigure: () => setConfigureSlotModal({
  5951. amsId: ams.id,
  5952. trayId: htSlotId,
  5953. trayCount: ams.tray.length,
  5954. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5955. }),
  5956. }}
  5957. onAssignSpool={() => setAssignSpoolModal({
  5958. printerId: printer.id,
  5959. amsId: ams.id,
  5960. trayId: htSlotId,
  5961. trayInfo: {
  5962. type: '',
  5963. material: undefined,
  5964. profile: '',
  5965. color: '',
  5966. location: getAmsLabel(ams.id, ams.tray.length),
  5967. },
  5968. })}
  5969. >
  5970. {slotVisual}
  5971. </EmptySlotHoverCard>
  5972. )}
  5973. </div>
  5974. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5975. {(ams.humidity != null || ams.temp != null) && (
  5976. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5977. {ams.temp != null && (
  5978. <TemperatureIndicator
  5979. temp={ams.temp}
  5980. goodThreshold={amsThresholds?.tempGood}
  5981. fairThreshold={amsThresholds?.tempFair}
  5982. onClick={() => setAmsHistoryModal({
  5983. amsId: ams.id,
  5984. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5985. mode: 'temperature',
  5986. })}
  5987. compact
  5988. />
  5989. )}
  5990. {ams.humidity != null && (
  5991. <HumidityIndicator
  5992. humidity={ams.humidity}
  5993. goodThreshold={amsThresholds?.humidityGood}
  5994. fairThreshold={amsThresholds?.humidityFair}
  5995. onClick={() => setAmsHistoryModal({
  5996. amsId: ams.id,
  5997. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5998. mode: 'humidity',
  5999. })}
  6000. compact
  6001. />
  6002. )}
  6003. </div>
  6004. )}
  6005. </div>
  6006. </div>
  6007. );
  6008. })}
  6009. {/* External spool(s) - grouped in one card like regular AMS */}
  6010. {status.vt_tray.length > 0 && showExternalSpool && (
  6011. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  6012. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  6013. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  6014. </div>
  6015. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  6016. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  6017. const extTrayId = extTray.id ?? 254;
  6018. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  6019. // generically — use active_extruder to determine L vs R:
  6020. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  6021. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  6022. ? (extTrayId === 254 && status.active_extruder === 1) ||
  6023. (extTrayId === 255 && status.active_extruder === 0)
  6024. : effectiveTrayNow === extTrayId;
  6025. const slotTrayId = extTrayId - 254; // 0 or 1
  6026. const extLabel = isDualNozzle
  6027. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6028. : '';
  6029. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6030. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6031. // Only trusted while it still describes what the printer reports in the
  6032. // slot: the row survives a spool swap, and the display chain below puts
  6033. // it ahead of the live filament id (see slotPresetDescribesTray).
  6034. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx)
  6035. ? extSlotPreset?.preset_name
  6036. : undefined;
  6037. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6038. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6039. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6040. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6041. const extInventoryFill = (() => {
  6042. const sp = extInventoryAssignment?.spool;
  6043. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6044. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6045. }
  6046. return null;
  6047. })();
  6048. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6049. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6050. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6051. ? null : extInventoryFill;
  6052. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6053. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6054. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6055. : undefined;
  6056. const extSlotSpoolForFill = extSlotAssignmentForFill
  6057. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6058. : undefined;
  6059. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6060. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6061. : null;
  6062. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6063. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6064. : extResolvedInventoryFill !== null ? 'inventory' as const
  6065. : extHasFillLevel ? 'ams' as const
  6066. : undefined;
  6067. const extFilamentData = {
  6068. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6069. 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',
  6070. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6071. colorHex: extTray.tray_color || null,
  6072. kFactor: formatKValue(extTray.k),
  6073. fillLevel: extEffectiveFill,
  6074. trayUuid: extTray.tray_uuid || null,
  6075. tagUid: extTray.tag_uid || null,
  6076. fillSource: extFillSource,
  6077. };
  6078. const isEmpty = !extTray.tray_type;
  6079. const emptyKind = getEmptySlotKind(extTray);
  6080. const extSlotContent = (
  6081. <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' : ''}`}>
  6082. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6083. the separate Ext-L/Ext-R caption that made the row taller than
  6084. regular AMS slots), 1-based slot number on single-nozzle. */}
  6085. <FilamentSlotCircle
  6086. trayColor={extTray.tray_color}
  6087. trayType={extTray.tray_type}
  6088. isEmpty={isEmpty}
  6089. emptyKind={emptyKind}
  6090. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6091. />
  6092. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6093. {extTray.tray_type || t('ams.slotEmpty')}
  6094. </div>
  6095. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6096. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6097. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6098. <div
  6099. className="h-full rounded-full transition-all"
  6100. style={{
  6101. width: `${extEffectiveFill}%`,
  6102. backgroundColor: getFillBarColor(extEffectiveFill),
  6103. }}
  6104. />
  6105. )}
  6106. </div>
  6107. </div>
  6108. );
  6109. return (
  6110. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6111. {!isEmpty ? (
  6112. <FilamentHoverCard
  6113. data={extFilamentData}
  6114. actions={renderAmsSlotActions({
  6115. amsId: 255,
  6116. slotId: slotTrayId,
  6117. loadTrayId: extTrayId,
  6118. includeRfid: false,
  6119. })}
  6120. spoolman={{
  6121. enabled: spoolmanEnabled,
  6122. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6123. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6124. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6125. spoolmanUrl,
  6126. syncMode: spoolmanSyncMode,
  6127. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6128. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6129. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6130. setLinkSpoolModal({
  6131. tagUid: extFilamentData.tagUid || linkTag,
  6132. trayUuid: extFilamentData.trayUuid || '',
  6133. printerId: printer.id,
  6134. amsId: 255,
  6135. trayId: slotTrayId,
  6136. });
  6137. } : undefined,
  6138. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6139. }}
  6140. inventory={(() => {
  6141. if (spoolmanEnabled) {
  6142. if (spoolmanLoading) return undefined;
  6143. const slotAssignment = extSlotAssignmentForFill;
  6144. const spoolmanSpool = extSlotSpoolForFill;
  6145. return {
  6146. assignedSpool: spoolmanSpool ? {
  6147. id: spoolmanSpool.id,
  6148. material: spoolmanSpool.material,
  6149. subtype: spoolmanSpool.subtype,
  6150. brand: spoolmanSpool.brand ?? null,
  6151. color_name: spoolmanSpool.color_name ?? null,
  6152. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6153. // The spool's own swatch (#2967). Spoolman carries the
  6154. // extra stops but has no effect field at all, so those
  6155. // rolls gradient and never shimmer.
  6156. rgba: spoolmanSpool.rgba ?? null,
  6157. extra_colors: spoolmanSpool.extra_colors ?? null,
  6158. effect_type: spoolmanSpool.effect_type ?? null,
  6159. remainingWeightGrams: spoolmanSpool.label_weight
  6160. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6161. : undefined,
  6162. } : null,
  6163. onAssignSpool: () => setAssignSpoolModal({
  6164. printerId: printer.id,
  6165. amsId: 255,
  6166. trayId: slotTrayId,
  6167. trayInfo: {
  6168. type: extTray.tray_type || extFilamentData.profile,
  6169. material: extTray.tray_type ?? undefined,
  6170. profile: extFilamentData.profile,
  6171. color: extFilamentData.colorHex || '',
  6172. location: extLabel || t('printers.external'),
  6173. },
  6174. }),
  6175. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6176. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6177. };
  6178. }
  6179. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6180. return {
  6181. assignedSpool: assignment?.spool ? {
  6182. id: assignment.spool.id,
  6183. material: assignment.spool.material,
  6184. subtype: assignment.spool.subtype,
  6185. brand: assignment.spool.brand,
  6186. color_name: assignment.spool.color_name,
  6187. // The spool's own swatch (#2967).
  6188. rgba: assignment.spool.rgba ?? null,
  6189. extra_colors: assignment.spool.extra_colors ?? null,
  6190. effect_type: assignment.spool.effect_type ?? null,
  6191. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6192. } : null,
  6193. onAssignSpool: () => setAssignSpoolModal({
  6194. printerId: printer.id,
  6195. amsId: 255,
  6196. trayId: slotTrayId,
  6197. trayInfo: {
  6198. type: extTray.tray_type || extFilamentData.profile,
  6199. material: extTray.tray_type ?? undefined,
  6200. profile: extFilamentData.profile,
  6201. color: extFilamentData.colorHex || '',
  6202. location: extLabel || t('printers.external'),
  6203. },
  6204. }),
  6205. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6206. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6207. };
  6208. })()}
  6209. configureSlot={{
  6210. enabled: hasPermission('printers:control'),
  6211. onConfigure: () => setConfigureSlotModal({
  6212. amsId: 255,
  6213. trayId: slotTrayId,
  6214. trayCount: 1,
  6215. trayType: extTray.tray_type || undefined,
  6216. trayColor: extTray.tray_color || undefined,
  6217. traySubBrands: extTray.tray_sub_brands || undefined,
  6218. trayInfoIdx: extTray.tray_info_idx || undefined,
  6219. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6220. caliIdx: extTray.cali_idx,
  6221. savedPresetId: extSlotPreset?.preset_id,
  6222. }),
  6223. }}
  6224. >
  6225. {extSlotContent}
  6226. </FilamentHoverCard>
  6227. ) : (
  6228. <EmptySlotHoverCard
  6229. kind={emptyKind ?? undefined}
  6230. actions={renderAmsSlotActions({
  6231. amsId: 255,
  6232. slotId: slotTrayId,
  6233. loadTrayId: extTrayId,
  6234. includeRfid: false,
  6235. })}
  6236. configureSlot={{
  6237. enabled: hasPermission('printers:control'),
  6238. onConfigure: () => setConfigureSlotModal({
  6239. amsId: 255,
  6240. trayId: slotTrayId,
  6241. trayCount: 1,
  6242. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6243. }),
  6244. }}
  6245. onAssignSpool={() => setAssignSpoolModal({
  6246. printerId: printer.id,
  6247. amsId: 255,
  6248. trayId: slotTrayId,
  6249. trayInfo: {
  6250. type: '',
  6251. material: undefined,
  6252. profile: '',
  6253. color: '',
  6254. location: `External Slot ${slotTrayId + 1}`,
  6255. },
  6256. })}
  6257. >
  6258. {extSlotContent}
  6259. </EmptySlotHoverCard>
  6260. )}
  6261. </div>
  6262. );
  6263. })}
  6264. </div>
  6265. </div>
  6266. )}
  6267. </div>
  6268. </div>
  6269. );
  6270. })()}
  6271. </>
  6272. )}
  6273. {/* Powered-down printer with a dirty plate: the status block above renders
  6274. nothing without a live connection, so the plate-clear control gets its own
  6275. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6276. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6277. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6278. expandedClearPlateButton
  6279. )}
  6280. {/* Bottom block (power row + action bar). Wrapped together so the
  6281. power row hugs the action bar at the card bottom instead of
  6282. floating up when there's less filament content above. */}
  6283. {viewMode === 'expanded' && (
  6284. <div className="mt-auto">
  6285. {smartPlug && (
  6286. <div className="pt-3">
  6287. <div className="flex items-center gap-2 mb-2">
  6288. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6289. {t('printers.power', 'Power')}
  6290. </span>
  6291. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6292. </div>
  6293. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6294. {/* Plug name + current power */}
  6295. <div className="flex items-center gap-2 min-w-0 pl-1">
  6296. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6297. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6298. <span
  6299. 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"
  6300. title={t('smartPlugs.power')}
  6301. >
  6302. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6303. </span>
  6304. </div>
  6305. {/* Spacer */}
  6306. <div className="flex-1" />
  6307. <div className="flex items-center gap-2">
  6308. {/* Auto-off */}
  6309. <button
  6310. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6311. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6312. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6313. 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 ${
  6314. !hasPermission('smart_plugs:control')
  6315. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6316. : smartPlug.auto_off || smartPlug.auto_off_executed
  6317. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6318. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6319. }`}
  6320. >
  6321. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6322. </button>
  6323. <button
  6324. onClick={() => {
  6325. if (plugStatus?.state === 'ON') {
  6326. setShowPowerOffConfirm(true);
  6327. } else {
  6328. setShowPowerOnConfirm(true);
  6329. }
  6330. }}
  6331. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6332. 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 ${
  6333. !hasPermission('smart_plugs:control')
  6334. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6335. : plugStatus?.state === 'ON'
  6336. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6337. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6338. }`}
  6339. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6340. >
  6341. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6342. </button>
  6343. </div>
  6344. </div>
  6345. {/* HA entity buttons row */}
  6346. {scriptPlugs && scriptPlugs.length > 0 && (
  6347. <div className="flex items-center gap-2 mt-2">
  6348. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6349. <span className="text-xs text-bambu-gray">HA:</span>
  6350. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6351. <div className="flex flex-wrap gap-1">
  6352. {scriptPlugs.map(script => {
  6353. const isScript = script.ha_entity_id?.startsWith('script.');
  6354. return (
  6355. <button
  6356. key={script.id}
  6357. onClick={() => {
  6358. if (isScript) {
  6359. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6360. } else {
  6361. setHaToggleConfirm(script);
  6362. }
  6363. }}
  6364. disabled={runScriptMutation.isPending}
  6365. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6366. 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"
  6367. >
  6368. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6369. {script.name}
  6370. </button>
  6371. );
  6372. })}
  6373. </div>
  6374. </div>
  6375. )}
  6376. </div>
  6377. )}
  6378. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6379. a printer can have an enclosure door contact without having a plug,
  6380. and nesting it there would hide the row on exactly those setups. */}
  6381. <PrinterHASensorRow printerId={printer.id} />
  6382. {/* Connection Info & Actions */}
  6383. <div className="pt-4">
  6384. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6385. <div className="flex items-center justify-between gap-2">
  6386. {printerActionsMenu}
  6387. <div className="flex items-center justify-end gap-2 flex-wrap">
  6388. {/* Camera split button: the icon opens whichever view was used
  6389. last, the caret picks between the two and remembers it.
  6390. Replaces the old Settings > General > Camera switch, which
  6391. made choosing between an overlay and a window a trip to
  6392. another page for something you decide per camera. */}
  6393. <div className="flex items-center flex-shrink-0">
  6394. <Button
  6395. variant="secondary"
  6396. size="sm"
  6397. onClick={() => openCameraIn(cameraViewMode)}
  6398. disabled={!status?.connected || !hasPermission('camera:view')}
  6399. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6400. className={`${footerIconButtonClass} !rounded-r-none`}
  6401. >
  6402. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6403. </Button>
  6404. <Button
  6405. variant="secondary"
  6406. size="sm"
  6407. onClick={(e) => {
  6408. // No open/close toggle: the menu's own outside-mousedown
  6409. // handler has already dismissed it by the time this lands.
  6410. const rect = e.currentTarget.getBoundingClientRect();
  6411. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6412. }}
  6413. disabled={!status?.connected || !hasPermission('camera:view')}
  6414. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6415. aria-label={t('settings.cameraViewMode')}
  6416. // Not footerIconButtonClass plus an override: both widths
  6417. // would carry !important and the stylesheet's own order,
  6418. // not this one, would decide which won.
  6419. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6420. >
  6421. <ChevronDown className="w-3 h-3" />
  6422. </Button>
  6423. </div>
  6424. {cameraMenuAnchor && (
  6425. <ContextMenu
  6426. x={cameraMenuAnchor.x}
  6427. y={cameraMenuAnchor.y}
  6428. items={cameraViewModeMenuItems}
  6429. onClose={() => setCameraMenuAnchor(null)}
  6430. />
  6431. )}
  6432. <Button
  6433. variant="secondary"
  6434. size="sm"
  6435. onClick={() => setShowFileManager(true)}
  6436. disabled={!hasPermission('printers:files')}
  6437. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6438. className={footerIconButtonClass}
  6439. >
  6440. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6441. </Button>
  6442. {/* Shown whatever the printer is doing (#2849): this uploads a
  6443. file and queues it, which a busy or offline printer is no
  6444. reason to refuse -- it only means the item waits. Hiding it
  6445. while the drop zone accepted the same file would have left
  6446. the two routes into this flow disagreeing. */}
  6447. <Button
  6448. size="sm"
  6449. onClick={() => setShowUploadForPrint(true)}
  6450. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6451. title={
  6452. !hasPermission('library:upload')
  6453. ? t('fileManager.noPermissionUpload')
  6454. : !hasPermission('queue:create')
  6455. ? t('fileManager.noPermissionAddToQueue')
  6456. : t('common.print')
  6457. }
  6458. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6459. >
  6460. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6461. {t('common.print')}
  6462. </Button>
  6463. </div>
  6464. </div>
  6465. </div>
  6466. </div>
  6467. )}
  6468. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6469. card's horizontal padding instead of running full-bleed into the
  6470. rounded bottom edge. */}
  6471. <ScheduledDryingBanner
  6472. printerId={printer.id}
  6473. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6474. timeFormat={timeFormat}
  6475. />
  6476. </CardContent>
  6477. {/* File Manager Modal */}
  6478. {showFileManager && (
  6479. <FileManagerModal
  6480. printerId={printer.id}
  6481. printerName={printer.name}
  6482. onClose={() => setShowFileManager(false)}
  6483. />
  6484. )}
  6485. {/* Upload for Print Modal */}
  6486. {showUploadForPrint && (
  6487. <FileUploadModal
  6488. folderId={null}
  6489. onClose={() => setShowUploadForPrint(false)}
  6490. onUploadComplete={() => {}}
  6491. autoUpload
  6492. accept=".gcode,.3mf"
  6493. validateFile={(file) => {
  6494. const lower = file.name.toLowerCase();
  6495. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6496. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6497. }
  6498. }}
  6499. onFileUploaded={(uploadedFile) => {
  6500. // Check printer compatibility if sliced_for_model is available in metadata
  6501. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6502. const printerModel = mapModelCode(printer.model);
  6503. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6504. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6505. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6506. }
  6507. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6508. }}
  6509. />
  6510. )}
  6511. {/* Print Modal (after upload) */}
  6512. {printAfterUpload && (
  6513. <PrintModal
  6514. mode="create"
  6515. libraryFileId={printAfterUpload.id}
  6516. archiveName={printAfterUpload.filename}
  6517. initialSelectedPrinterIds={[printer.id]}
  6518. onClose={() => setPrintAfterUpload(null)}
  6519. onSuccess={() => setPrintAfterUpload(null)}
  6520. cleanupLibraryAfterDispatch
  6521. />
  6522. )}
  6523. {/* MQTT Debug Modal */}
  6524. {showMQTTDebug && (
  6525. <MQTTDebugModal
  6526. printerId={printer.id}
  6527. printerName={printer.name}
  6528. onClose={() => setShowMQTTDebug(false)}
  6529. />
  6530. )}
  6531. {showDiagnostic && (
  6532. <ConnectionDiagnosticModal
  6533. printerId={printer.id}
  6534. printerName={printer.name}
  6535. onClose={() => setShowDiagnostic(false)}
  6536. />
  6537. )}
  6538. {showPrinterInfo && (
  6539. <PrinterInfoModal
  6540. printer={printer}
  6541. status={status}
  6542. totalPrintHours={maintenanceInfo?.total_print_hours}
  6543. onClose={closePrinterInfo}
  6544. />
  6545. )}
  6546. {/* Plate Check Result Modal */}
  6547. {plateCheckResult && (
  6548. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6549. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6550. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6551. <div className="flex items-center gap-2">
  6552. {plateCheckResult.needs_calibration ? (
  6553. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6554. ) : plateCheckResult.is_empty ? (
  6555. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6556. ) : (
  6557. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6558. )}
  6559. <h2 className="text-lg font-semibold text-white">
  6560. Build Plate Check
  6561. </h2>
  6562. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6563. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6564. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6565. </span>
  6566. )}
  6567. </div>
  6568. <button
  6569. onClick={() => closePlateCheckModal()}
  6570. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6571. >
  6572. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6573. </button>
  6574. </div>
  6575. <div className="p-4 space-y-4">
  6576. {plateCheckResult.needs_calibration ? (
  6577. <>
  6578. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6579. <p className="font-medium text-blue-700 dark:text-blue-400">
  6580. {t('printers.plateDetection.calibrationRequired')}
  6581. </p>
  6582. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6583. </div>
  6584. <div className="text-sm text-bambu-gray space-y-2">
  6585. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6586. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6587. </div>
  6588. </>
  6589. ) : (
  6590. <>
  6591. <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'}`}>
  6592. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6593. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6594. </p>
  6595. <p className="text-sm text-bambu-gray mt-1">
  6596. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6597. </p>
  6598. </div>
  6599. {plateCheckResult.debug_image_url && (
  6600. <div>
  6601. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6602. <img
  6603. src={plateCheckResult.debug_image_url}
  6604. alt={t('printers.plateDetection.analysisPreview')}
  6605. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6606. />
  6607. <p className="text-xs text-bambu-gray mt-2">
  6608. {t('printers.plateDetection.analysisLegend')}
  6609. </p>
  6610. </div>
  6611. )}
  6612. <p className="text-xs text-bambu-gray">
  6613. {plateCheckResult.message}
  6614. </p>
  6615. </>
  6616. )}
  6617. {/* Saved References Grid */}
  6618. {plateReferences && plateReferences.references.length > 0 && (
  6619. <div className="mt-4">
  6620. <div className="flex items-center gap-2 mb-2">
  6621. <p className="text-sm font-medium text-white shrink-0">
  6622. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6623. </p>
  6624. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6625. </div>
  6626. <div className="grid grid-cols-5 gap-2">
  6627. {plateReferences.references.map((ref) => (
  6628. <div key={ref.index} className="relative group">
  6629. <img
  6630. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6631. alt={ref.label || `Reference ${ref.index + 1}`}
  6632. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6633. />
  6634. {/* Delete button */}
  6635. <button
  6636. onClick={() => handleDeleteRef(ref.index)}
  6637. 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"
  6638. title={t('printers.plateDetection.deleteReference')}
  6639. >
  6640. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6641. </button>
  6642. {/* Label */}
  6643. {editingRefLabel?.index === ref.index ? (
  6644. <input
  6645. type="text"
  6646. value={editingRefLabel.label}
  6647. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6648. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6649. onKeyDown={(e) => {
  6650. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6651. if (e.key === 'Escape') setEditingRefLabel(null);
  6652. }}
  6653. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6654. autoFocus
  6655. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6656. />
  6657. ) : (
  6658. <p
  6659. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6660. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6661. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6662. >
  6663. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6664. </p>
  6665. )}
  6666. {/* Timestamp */}
  6667. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6668. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6669. </p>
  6670. </div>
  6671. ))}
  6672. </div>
  6673. </div>
  6674. )}
  6675. {/* ROI Editor */}
  6676. {!plateCheckResult.needs_calibration && (
  6677. <div className="mt-4">
  6678. <div className="flex items-center justify-between mb-2">
  6679. <div className="flex min-w-0 flex-1 items-center gap-2">
  6680. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6681. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6682. </div>
  6683. {!editingRoi ? (
  6684. <Button
  6685. variant="ghost"
  6686. size="sm"
  6687. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6688. >
  6689. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6690. {t('common.edit')}
  6691. </Button>
  6692. ) : (
  6693. <div className="flex gap-1">
  6694. <Button
  6695. variant="ghost"
  6696. size="sm"
  6697. onClick={() => setEditingRoi(null)}
  6698. disabled={isSavingRoi}
  6699. >
  6700. {t('common.cancel')}
  6701. </Button>
  6702. <Button
  6703. size="sm"
  6704. onClick={handleSaveRoi}
  6705. disabled={isSavingRoi}
  6706. >
  6707. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6708. </Button>
  6709. </div>
  6710. )}
  6711. </div>
  6712. {editingRoi ? (
  6713. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6714. <div className="grid grid-cols-2 gap-3">
  6715. <div>
  6716. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6717. <input
  6718. type="range"
  6719. min="0"
  6720. max="0.9"
  6721. step="0.01"
  6722. value={editingRoi.x}
  6723. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6724. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6725. />
  6726. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6727. </div>
  6728. <div>
  6729. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6730. <input
  6731. type="range"
  6732. min="0"
  6733. max="0.9"
  6734. step="0.01"
  6735. value={editingRoi.y}
  6736. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6737. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6738. />
  6739. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6740. </div>
  6741. <div>
  6742. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6743. <input
  6744. type="range"
  6745. min="0.1"
  6746. max="1"
  6747. step="0.01"
  6748. value={editingRoi.w}
  6749. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6750. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6751. />
  6752. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6753. </div>
  6754. <div>
  6755. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6756. <input
  6757. type="range"
  6758. min="0.1"
  6759. max="1"
  6760. step="0.01"
  6761. value={editingRoi.h}
  6762. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6763. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6764. />
  6765. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6766. </div>
  6767. </div>
  6768. <p className="text-xs text-bambu-gray">
  6769. {t('printers.roi.instruction')}
  6770. </p>
  6771. </div>
  6772. ) : (
  6773. <p className="text-xs text-bambu-gray">
  6774. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6775. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6776. </p>
  6777. )}
  6778. </div>
  6779. )}
  6780. </div>
  6781. <div className="flex justify-end gap-2 p-4">
  6782. {plateCheckResult.needs_calibration ? (
  6783. <>
  6784. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6785. {t('common.cancel')}
  6786. </Button>
  6787. <Button
  6788. onClick={() => handleCalibratePlate()}
  6789. disabled={isCalibrating}
  6790. >
  6791. {isCalibrating ? (
  6792. <>
  6793. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6794. Calibrating...
  6795. </>
  6796. ) : (
  6797. 'Calibrate Empty Plate'
  6798. )}
  6799. </Button>
  6800. </>
  6801. ) : (
  6802. <>
  6803. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6804. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6805. </Button>
  6806. <Button onClick={() => closePlateCheckModal()}>
  6807. Close
  6808. </Button>
  6809. </>
  6810. )}
  6811. </div>
  6812. </div>
  6813. </div>
  6814. )}
  6815. {/* Power On Confirmation */}
  6816. {showPowerOnConfirm && smartPlug && (
  6817. <ConfirmModal
  6818. title={t('printers.confirm.powerOnTitle')}
  6819. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6820. confirmText={t('printers.confirm.powerOnButton')}
  6821. variant="default"
  6822. onConfirm={() => {
  6823. powerControlMutation.mutate('on');
  6824. setShowPowerOnConfirm(false);
  6825. }}
  6826. onCancel={() => setShowPowerOnConfirm(false)}
  6827. />
  6828. )}
  6829. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6830. disconnects MQTT, which stops progress tracking + completion
  6831. notifications for the in-flight job. Idle / FINISH / FAILED states
  6832. skip this dialog and toggle directly. */}
  6833. {confirmMaintenanceEnter && (
  6834. <ConfirmModal
  6835. title={t('printers.maintenance.confirmMidPrintTitle')}
  6836. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6837. confirmText={t('printers.maintenance.menuEnter')}
  6838. variant="danger"
  6839. onConfirm={() => {
  6840. maintenanceMutation.mutate(false);
  6841. setConfirmMaintenanceEnter(false);
  6842. }}
  6843. onCancel={() => setConfirmMaintenanceEnter(false)}
  6844. />
  6845. )}
  6846. {/* Power Off Confirmation */}
  6847. {showPowerOffConfirm && smartPlug && (
  6848. <ConfirmModal
  6849. title={t('printers.confirm.powerOffTitle')}
  6850. message={
  6851. status?.state === 'RUNNING'
  6852. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6853. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6854. }
  6855. confirmText={t('printers.confirm.powerOffButton')}
  6856. variant="danger"
  6857. onConfirm={() => {
  6858. powerControlMutation.mutate('off');
  6859. setShowPowerOffConfirm(false);
  6860. }}
  6861. onCancel={() => setShowPowerOffConfirm(false)}
  6862. />
  6863. )}
  6864. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6865. {haToggleConfirm && (
  6866. <ConfirmModal
  6867. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6868. message={
  6869. status?.state === 'RUNNING'
  6870. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6871. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6872. }
  6873. confirmText={t('printers.confirm.haToggleButton')}
  6874. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6875. onConfirm={() => {
  6876. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6877. setHaToggleConfirm(null);
  6878. }}
  6879. onCancel={() => setHaToggleConfirm(null)}
  6880. />
  6881. )}
  6882. {/* Stop Print Confirmation */}
  6883. {showStopConfirm && (
  6884. <ConfirmModal
  6885. title={t('printers.confirm.stopTitle')}
  6886. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6887. confirmText={t('printers.confirm.stopButton')}
  6888. variant="danger"
  6889. onConfirm={() => {
  6890. stopPrintMutation.mutate();
  6891. setShowStopConfirm(false);
  6892. }}
  6893. onCancel={() => setShowStopConfirm(false)}
  6894. />
  6895. )}
  6896. {/* Pause Print Confirmation */}
  6897. {showPauseConfirm && (
  6898. <ConfirmModal
  6899. title={t('printers.confirm.pauseTitle')}
  6900. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6901. confirmText={t('printers.confirm.pauseButton')}
  6902. variant="default"
  6903. onConfirm={() => {
  6904. pausePrintMutation.mutate();
  6905. setShowPauseConfirm(false);
  6906. }}
  6907. onCancel={() => setShowPauseConfirm(false)}
  6908. />
  6909. )}
  6910. {/* Resume Print Confirmation */}
  6911. {showResumeConfirm && (
  6912. <ConfirmModal
  6913. title={t('printers.confirm.resumeTitle')}
  6914. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6915. confirmText={t('printers.confirm.resumeButton')}
  6916. variant="default"
  6917. onConfirm={() => {
  6918. resumePrintMutation.mutate();
  6919. setShowResumeConfirm(false);
  6920. }}
  6921. onCancel={() => setShowResumeConfirm(false)}
  6922. />
  6923. )}
  6924. {/* Skip Objects Modal */}
  6925. <SkipObjectsModal
  6926. printerId={printer.id}
  6927. isOpen={showSkipObjectsModal}
  6928. onClose={() => setShowSkipObjectsModal(false)}
  6929. />
  6930. {/* HMS Error Modal */}
  6931. {showHMSModal && (
  6932. <HMSErrorModal
  6933. printerName={printer.name}
  6934. errors={status?.hms_errors || []}
  6935. onClose={() => setShowHMSModal(false)}
  6936. printerId={printer.id}
  6937. hasPermission={hasPermission}
  6938. runoutGuidance={runoutGuidance}
  6939. />
  6940. )}
  6941. {/* AI failure detection modal (#1546) */}
  6942. {showAiModal && (
  6943. <AiDetectionModal
  6944. printerName={printer.name}
  6945. detection={aiDetection}
  6946. lastError={aiLastError}
  6947. onClose={() => setShowAiModal(false)}
  6948. />
  6949. )}
  6950. {/* AMS Filament Backup status / control modal (#1762) */}
  6951. {amsBackupModalOpen && status && (
  6952. <AmsBackupModal
  6953. isOpen={amsBackupModalOpen}
  6954. state={status.ams_filament_backup}
  6955. amsUnits={status.ams}
  6956. amsExtruderMap={status.ams_extruder_map}
  6957. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6958. canToggle={hasPermission('printers:control')}
  6959. pending={setAmsBackupMutation.isPending}
  6960. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6961. onClose={() => setAmsBackupModalOpen(false)}
  6962. />
  6963. )}
  6964. {/* AMS History Modal */}
  6965. {amsHistoryModal && (
  6966. <AMSHistoryModal
  6967. isOpen={!!amsHistoryModal}
  6968. onClose={() => setAmsHistoryModal(null)}
  6969. printerId={printer.id}
  6970. printerName={printer.name}
  6971. amsId={amsHistoryModal.amsId}
  6972. amsLabel={amsHistoryModal.amsLabel}
  6973. initialMode={amsHistoryModal.mode}
  6974. thresholds={amsThresholds}
  6975. />
  6976. )}
  6977. {/* Heater History Modal (nozzle / bed / chamber) */}
  6978. {heaterHistoryModal && (
  6979. <HeaterHistoryModal
  6980. isOpen={!!heaterHistoryModal}
  6981. onClose={() => setHeaterHistoryModal(null)}
  6982. printerId={printer.id}
  6983. printerName={printer.name}
  6984. initialKind={heaterHistoryModal.initialKind}
  6985. availableKinds={heaterHistoryModal.availableKinds}
  6986. />
  6987. )}
  6988. {/* Link Spool Modal */}
  6989. {linkSpoolModal && (
  6990. <LinkSpoolModal
  6991. isOpen={!!linkSpoolModal}
  6992. onClose={() => setLinkSpoolModal(null)}
  6993. tagUid={linkSpoolModal.tagUid}
  6994. trayUuid={linkSpoolModal.trayUuid}
  6995. printerId={linkSpoolModal.printerId}
  6996. amsId={linkSpoolModal.amsId}
  6997. trayId={linkSpoolModal.trayId}
  6998. />
  6999. )}
  7000. {/* Assign Spool Modal */}
  7001. {assignSpoolModal && (
  7002. <AssignSpoolModal
  7003. isOpen={!!assignSpoolModal}
  7004. onClose={() => setAssignSpoolModal(null)}
  7005. printerId={assignSpoolModal.printerId}
  7006. amsId={assignSpoolModal.amsId}
  7007. trayId={assignSpoolModal.trayId}
  7008. trayInfo={assignSpoolModal.trayInfo}
  7009. spoolmanEnabled={!!spoolmanEnabled}
  7010. />
  7011. )}
  7012. {/* Configure AMS Slot Modal */}
  7013. {configureSlotModal && (
  7014. <ConfigureAmsSlotModal
  7015. isOpen={!!configureSlotModal}
  7016. onClose={() => setConfigureSlotModal(null)}
  7017. printerId={printer.id}
  7018. slotInfo={configureSlotModal}
  7019. printerModel={mapModelCode(printer.model) || undefined}
  7020. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  7021. onSuccess={() => {
  7022. // Refresh slot presets to show updated profile name
  7023. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7024. // Printer status will update automatically via WebSocket when AMS data changes
  7025. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7026. }}
  7027. />
  7028. )}
  7029. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7030. {feedDirectionRequest && (
  7031. <FeedDirectionModal
  7032. slotLabel={feedDirectionRequest.slotLabel}
  7033. amsId={feedDirectionRequest.amsId}
  7034. slotId={feedDirectionRequest.slotId}
  7035. extruderSlots={status?.extruder_slots ?? {}}
  7036. isLoading={loadAmsTrayMutation.isPending}
  7037. onConfirm={(extruderId) =>
  7038. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7039. }
  7040. onCancel={() => setFeedDirectionRequest(null)}
  7041. />
  7042. )}
  7043. {/* Edit Printer Modal */}
  7044. {showEditModal && (
  7045. <EditPrinterModal
  7046. printer={printer}
  7047. onClose={() => setShowEditModal(false)}
  7048. />
  7049. )}
  7050. {/* Firmware Update Modal */}
  7051. {showFirmwareModal && firmwareInfo && (
  7052. <FirmwareUpdateModal
  7053. printer={printer}
  7054. firmwareInfo={firmwareInfo}
  7055. onClose={() => setShowFirmwareModal(false)}
  7056. />
  7057. )}
  7058. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7059. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7060. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7061. const sliderMin = 35;
  7062. const sliderMax = maxTemp + 10;
  7063. return (
  7064. <>
  7065. {/* Backdrop */}
  7066. <div
  7067. className="fixed inset-0 z-[100]"
  7068. data-testid="drying-popover-backdrop"
  7069. onMouseDown={() => {
  7070. // The click that dismisses the native datetime picker lands
  7071. // here; it must not close the popover. The input is still
  7072. // focused at mousedown, so remember that and swallow the
  7073. // matching click.
  7074. dryingBackdropSkipCloseRef.current =
  7075. dryingAtTimeInputRef.current !== null &&
  7076. document.activeElement === dryingAtTimeInputRef.current;
  7077. }}
  7078. onClick={() => {
  7079. if (dryingBackdropSkipCloseRef.current) {
  7080. dryingBackdropSkipCloseRef.current = false;
  7081. return;
  7082. }
  7083. setDryingPopoverAmsId(null);
  7084. }}
  7085. />
  7086. {/* An 'above' popover is anchored by its bottom edge (CSS
  7087. bottom) so late-appearing content grows it upward, staying on
  7088. screen and glued to the trigger. maxHeight caps to the space
  7089. on the anchored side; when the viewport is too short the body
  7090. scrolls and the footer stays pinned. dvh so iOS Safari's
  7091. bottom toolbar doesn't clip the footer. */}
  7092. <div
  7093. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7094. style={{
  7095. left: dryingPopoverPos.left,
  7096. ...(dryingPopoverPos.placement === 'above'
  7097. ? {
  7098. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7099. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7100. }
  7101. : {
  7102. top: dryingPopoverPos.top,
  7103. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7104. }),
  7105. }}
  7106. onClick={e => e.stopPropagation()}
  7107. >
  7108. {/* Header */}
  7109. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7110. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7111. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7112. </div>
  7113. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7114. {/* Body */}
  7115. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7116. {/* Filament type select */}
  7117. <div>
  7118. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7119. <ToolbarDropdown
  7120. value={dryingFilament}
  7121. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7122. onChange={fil => {
  7123. setDryingFilament(fil);
  7124. const preset = dryingPresets[fil];
  7125. if (preset) {
  7126. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7127. setDryingTemp(preset[key]);
  7128. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7129. }
  7130. }}
  7131. fullWidth
  7132. />
  7133. </div>
  7134. {/* Temperature */}
  7135. <div>
  7136. <div className="flex items-center justify-between mb-1">
  7137. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7138. <div className="flex items-center gap-1">
  7139. <NumberInput
  7140. min={45}
  7141. max={maxTemp}
  7142. value={dryingTemp}
  7143. onChange={setDryingTemp}
  7144. fallback={45}
  7145. 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"
  7146. />
  7147. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7148. </div>
  7149. </div>
  7150. <input
  7151. type="range"
  7152. min={sliderMin}
  7153. max={sliderMax}
  7154. value={dryingTemp}
  7155. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7156. className="w-full h-1 accent-bambu-green cursor-pointer"
  7157. />
  7158. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7159. <span>45°C</span>
  7160. <span>{maxTemp}°C</span>
  7161. </div>
  7162. </div>
  7163. {/* Duration */}
  7164. <div>
  7165. <div className="flex items-center justify-between mb-1">
  7166. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7167. <div className="flex items-center gap-1">
  7168. <NumberInput
  7169. min={1}
  7170. max={24}
  7171. value={dryingDuration}
  7172. onChange={setDryingDuration}
  7173. fallback={1}
  7174. 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"
  7175. />
  7176. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7177. </div>
  7178. </div>
  7179. <input
  7180. type="range"
  7181. min={1}
  7182. max={24}
  7183. value={dryingDuration}
  7184. onChange={e => setDryingDuration(Number(e.target.value))}
  7185. className="w-full h-1 accent-bambu-green cursor-pointer"
  7186. />
  7187. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7188. <span>1h</span>
  7189. <span>24h</span>
  7190. </div>
  7191. </div>
  7192. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7193. filament threaded out into the feed tube. The whole AMS
  7194. rotates as one mechanism (all 4 spools turn together), so a
  7195. single loaded slot locks the entire unit. Bambu per-tray
  7196. `state`: 9 = empty, 10 = spool present but not loaded
  7197. (rotation possible), 11 = loaded into tube (rotation impossible).
  7198. Catches both mid-print (active feed) AND idle-with-threaded-
  7199. filament — the H2D's post-print state leaves filament in the
  7200. tube but tray_now resets to 255, which a tray_now-only check
  7201. would silently miss. */}
  7202. {(() => {
  7203. const targetAms = dryingPopoverAmsId !== null
  7204. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7205. : undefined;
  7206. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7207. tray => tray.state === 11,
  7208. );
  7209. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7210. return (
  7211. <button
  7212. type="button"
  7213. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7214. aria-pressed={rotateChecked}
  7215. disabled={trayLoadedInThisAms}
  7216. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7217. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7218. rotateChecked
  7219. ? 'bg-bambu-green border-bambu-green text-white'
  7220. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7221. }`}
  7222. >
  7223. {t('printers.drying.rotateTray')}
  7224. </button>
  7225. );
  7226. })()}
  7227. {/* Start mode: now / after delay / at time (#2638) */}
  7228. <div>
  7229. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7230. <div className="grid grid-cols-3 gap-1">
  7231. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7232. <button
  7233. key={mode}
  7234. type="button"
  7235. onClick={() => setDryingStartMode(mode)}
  7236. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7237. dryingStartMode === mode
  7238. ? 'bg-bambu-green border-bambu-green text-white'
  7239. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7240. }`}
  7241. >
  7242. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7243. </button>
  7244. ))}
  7245. </div>
  7246. {dryingStartMode === 'delay' && (
  7247. // Inline chips: a dropdown menu would be clipped by
  7248. // the popover's scrollable body.
  7249. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7250. {DRYING_DELAY_OPTIONS.map(min => (
  7251. <button
  7252. key={min}
  7253. type="button"
  7254. aria-pressed={dryingDelayMinutes === min}
  7255. onClick={() => setDryingDelayMinutes(min)}
  7256. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7257. dryingDelayMinutes === min
  7258. ? 'bg-bambu-green border-bambu-green text-white'
  7259. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7260. }`}
  7261. >
  7262. {formatDurationFromHours(min / 60)}
  7263. </button>
  7264. ))}
  7265. </div>
  7266. )}
  7267. {dryingStartMode === 'at_time' && (
  7268. <input
  7269. ref={dryingAtTimeInputRef}
  7270. type="datetime-local"
  7271. data-testid="drying-start-at"
  7272. value={dryingStartAt}
  7273. onChange={e => setDryingStartAt(e.target.value)}
  7274. 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]"
  7275. />
  7276. )}
  7277. </div>
  7278. </div>
  7279. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7280. {/* Footer */}
  7281. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7282. <button
  7283. onClick={() => {
  7284. if (dryingPopoverAmsId !== null) {
  7285. // Clamp rotateTray off when any tray in this AMS is loaded into
  7286. // the tube — the rotate UI is disabled there, but the state may
  7287. // linger as `true` from a previous AMS, or a print may have
  7288. // started while the popover was open. Without this clamp the
  7289. // Start payload would carry rotate_tray=true and firmware would
  7290. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7291. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7292. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7293. tray => tray.state === 11,
  7294. );
  7295. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7296. if (dryingStartMode === 'now') {
  7297. startDryingMutation.mutate({
  7298. amsId: dryingPopoverAmsId,
  7299. temp: dryingTemp,
  7300. duration: dryingDuration,
  7301. filament: dryingFilament,
  7302. rotateTray: rotate,
  7303. });
  7304. } else {
  7305. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7306. if (startAfter) {
  7307. scheduleDryingMutation.mutate({
  7308. amsId: dryingPopoverAmsId,
  7309. temp: dryingTemp,
  7310. duration: dryingDuration,
  7311. filament: dryingFilament,
  7312. rotateTray: rotate,
  7313. startAfter,
  7314. });
  7315. }
  7316. }
  7317. }
  7318. }}
  7319. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7320. data-testid="drying-start-confirm"
  7321. 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"
  7322. >
  7323. {dryingStartMode === 'now'
  7324. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7325. : t('printers.drying.schedule')}
  7326. </button>
  7327. </div>
  7328. </div>
  7329. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7330. since the popover clips its own overflow. */}
  7331. <div
  7332. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7333. style={{
  7334. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7335. top: dryingPopoverPos.anchorY - 5,
  7336. ...(dryingPopoverPos.placement === 'above'
  7337. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7338. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7339. }}
  7340. />
  7341. </>
  7342. );
  7343. })()}
  7344. </Card>
  7345. );
  7346. }
  7347. export function AddPrinterModal({
  7348. onClose,
  7349. onAdd,
  7350. existingSerials,
  7351. }: {
  7352. onClose: () => void;
  7353. onAdd: (data: PrinterCreate) => void;
  7354. existingSerials: string[];
  7355. }) {
  7356. const { t } = useTranslation();
  7357. const [form, setForm] = useState<PrinterCreate>({
  7358. name: '',
  7359. serial_number: '',
  7360. ip_address: '',
  7361. access_code: '',
  7362. model: '',
  7363. location: '',
  7364. auto_archive: true,
  7365. });
  7366. // Discovery state
  7367. const [discovering, setDiscovering] = useState(false);
  7368. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7369. const [discoveryError, setDiscoveryError] = useState('');
  7370. const [hasScanned, setHasScanned] = useState(false);
  7371. const [isDocker, setIsDocker] = useState(false);
  7372. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7373. const [subnet, setSubnet] = useState('');
  7374. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7375. // text input so users can scan a subnet Bambuddy isn't directly on
  7376. // (printer behind a router on a different L3 segment — SSDP multicast
  7377. // won't cross that boundary, only an active unicast scan will). #1564
  7378. const [customSubnet, setCustomSubnet] = useState('');
  7379. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7380. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7381. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7382. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7383. // (not block) when checks fail, so the user doesn't add a printer that
  7384. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7385. // failed result awaiting an explicit "save anyway".
  7386. const [checkingSave, setCheckingSave] = useState(false);
  7387. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7388. // Fetch discovery info on mount + restore the last custom CIDR the user
  7389. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7390. // time they open this modal).
  7391. useEffect(() => {
  7392. discoveryApi.getInfo().then(info => {
  7393. setIsDocker(info.is_docker);
  7394. if (info.subnets.length > 0) {
  7395. setDetectedSubnets(info.subnets);
  7396. setSubnet(info.subnets[0]);
  7397. }
  7398. }).catch(() => {
  7399. // Ignore errors, assume not Docker
  7400. });
  7401. try {
  7402. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7403. if (saved) setCustomSubnet(saved);
  7404. } catch {
  7405. // localStorage unavailable (private mode, quota); recall is opportunistic
  7406. }
  7407. }, []);
  7408. // Filter out already-added printers
  7409. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7410. const handleAddSubmit = async (e: React.FormEvent) => {
  7411. e.preventDefault();
  7412. setCheckingSave(true);
  7413. try {
  7414. const result = await api.diagnoseConnection({
  7415. ip_address: form.ip_address.trim(),
  7416. serial_number: form.serial_number.trim() || undefined,
  7417. access_code: form.access_code || undefined,
  7418. });
  7419. if (result.checks.some((c) => c.status === 'fail')) {
  7420. setSaveWarning(result);
  7421. return;
  7422. }
  7423. } catch {
  7424. // Diagnostic infrastructure failed — never block the save on it.
  7425. } finally {
  7426. setCheckingSave(false);
  7427. }
  7428. onAdd(form);
  7429. };
  7430. const startDiscovery = async () => {
  7431. setDiscoveryError('');
  7432. setDiscovered([]);
  7433. setDiscovering(true);
  7434. setHasScanned(false);
  7435. setScanProgress({ scanned: 0, total: 0 });
  7436. // Native installs fall back to subnet scanning when the user picks
  7437. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7438. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7439. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7440. const wantsSubnetScan = isDocker || useCustomSubnet;
  7441. if (wantsSubnetScan && useCustomSubnet) {
  7442. try {
  7443. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7444. } catch {
  7445. // localStorage write best-effort; user just retypes next time
  7446. }
  7447. }
  7448. try {
  7449. if (wantsSubnetScan) {
  7450. await discoveryApi.startSubnetScan(scanCidr);
  7451. // Poll for scan status and results
  7452. const pollInterval = setInterval(async () => {
  7453. try {
  7454. const status = await discoveryApi.getScanStatus();
  7455. setScanProgress({ scanned: status.scanned, total: status.total });
  7456. const printers = await discoveryApi.getDiscoveredPrinters();
  7457. setDiscovered(printers);
  7458. if (!status.running) {
  7459. clearInterval(pollInterval);
  7460. setDiscovering(false);
  7461. setHasScanned(true);
  7462. }
  7463. } catch (e) {
  7464. console.error('Failed to get scan status:', e);
  7465. }
  7466. }, 500);
  7467. } else {
  7468. // Use SSDP discovery for native installs
  7469. await discoveryApi.startDiscovery(10);
  7470. // Poll for discovered printers every second
  7471. const pollInterval = setInterval(async () => {
  7472. try {
  7473. const printers = await discoveryApi.getDiscoveredPrinters();
  7474. setDiscovered(printers);
  7475. } catch (e) {
  7476. console.error('Failed to get discovered printers:', e);
  7477. }
  7478. }, 1000);
  7479. // Stop after 10 seconds
  7480. setTimeout(async () => {
  7481. clearInterval(pollInterval);
  7482. try {
  7483. await discoveryApi.stopDiscovery();
  7484. } catch {
  7485. // Ignore stop errors
  7486. }
  7487. setDiscovering(false);
  7488. setHasScanned(true);
  7489. // Final fetch
  7490. try {
  7491. const printers = await discoveryApi.getDiscoveredPrinters();
  7492. setDiscovered(printers);
  7493. } catch (e) {
  7494. console.error('Failed to get final discovered printers:', e);
  7495. }
  7496. }, 10000);
  7497. }
  7498. } catch (e) {
  7499. console.error('Failed to start discovery:', e);
  7500. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7501. setDiscovering(false);
  7502. setHasScanned(true);
  7503. }
  7504. };
  7505. // Reuse module-level mapModelCode
  7506. const selectPrinter = (printer: DiscoveredPrinter) => {
  7507. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7508. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7509. setForm({
  7510. ...form,
  7511. name: printer.name || '',
  7512. serial_number: serialNumber,
  7513. ip_address: printer.ip_address,
  7514. model: mapModelCode(printer.model),
  7515. });
  7516. // Clear discovery results after selection
  7517. setDiscovered([]);
  7518. };
  7519. // Cleanup discovery on unmount
  7520. useEffect(() => {
  7521. return () => {
  7522. discoveryApi.stopDiscovery().catch(() => {});
  7523. discoveryApi.stopSubnetScan().catch(() => {});
  7524. };
  7525. }, []);
  7526. // Close on Escape key
  7527. useEffect(() => {
  7528. const handleKeyDown = (e: KeyboardEvent) => {
  7529. if (e.key === 'Escape') onClose();
  7530. };
  7531. window.addEventListener('keydown', handleKeyDown);
  7532. return () => window.removeEventListener('keydown', handleKeyDown);
  7533. }, [onClose]);
  7534. return (
  7535. <>
  7536. <div
  7537. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7538. onClick={onClose}
  7539. >
  7540. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7541. <CardContent>
  7542. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7543. {/* Discovery Section */}
  7544. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7545. {/* Subnet picker — always visible. The dropdown lists detected
  7546. interface subnets and a "Custom..." sentinel that reveals
  7547. a CIDR text input for printers on a different L3 segment
  7548. (router, VLAN, etc.). #1564 */}
  7549. <div className="mb-3">
  7550. <label className="block text-sm text-bambu-gray mb-1">
  7551. {t('printers.discovery.subnetToScan')}
  7552. </label>
  7553. {detectedSubnets.length > 0 ? (
  7554. <select
  7555. 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"
  7556. value={useCustomSubnet ? '__custom__' : subnet}
  7557. onChange={(e) => {
  7558. if (e.target.value === '__custom__') {
  7559. setUseCustomSubnet(true);
  7560. } else {
  7561. setUseCustomSubnet(false);
  7562. setSubnet(e.target.value);
  7563. }
  7564. }}
  7565. disabled={discovering}
  7566. >
  7567. {detectedSubnets.map(s => (
  7568. <option key={s} value={s}>{s}</option>
  7569. ))}
  7570. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7571. </select>
  7572. ) : (
  7573. <input
  7574. type="text"
  7575. 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"
  7576. value={subnet}
  7577. onChange={(e) => setSubnet(e.target.value)}
  7578. placeholder="192.168.1.0/24"
  7579. disabled={discovering}
  7580. />
  7581. )}
  7582. {useCustomSubnet && (
  7583. <input
  7584. type="text"
  7585. aria-label={t('printers.discovery.customSubnetLabel')}
  7586. 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"
  7587. value={customSubnet}
  7588. onChange={(e) => setCustomSubnet(e.target.value)}
  7589. placeholder="10.1.1.0/24"
  7590. disabled={discovering}
  7591. />
  7592. )}
  7593. <p className="mt-1 text-xs text-bambu-gray">
  7594. {isDocker
  7595. ? t('printers.discovery.dockerNote')
  7596. : t('printers.discovery.customSubnetNote')}
  7597. </p>
  7598. </div>
  7599. <Button
  7600. type="button"
  7601. variant="secondary"
  7602. onClick={startDiscovery}
  7603. disabled={discovering}
  7604. className="w-full"
  7605. >
  7606. {discovering ? (
  7607. <>
  7608. <Loader2 className="w-4 h-4 animate-spin" />
  7609. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7610. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7611. : t('printers.discovery.scanning')}
  7612. </>
  7613. ) : (
  7614. <>
  7615. <Search className="w-4 h-4" />
  7616. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7617. </>
  7618. )}
  7619. </Button>
  7620. {discoveryError && (
  7621. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7622. )}
  7623. {newPrinters.length > 0 && (
  7624. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7625. {newPrinters.map((printer) => (
  7626. <div
  7627. key={printer.serial}
  7628. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7629. onClick={() => selectPrinter(printer)}
  7630. >
  7631. <div className="min-w-0 flex-1">
  7632. <p className="font-medium text-white text-sm truncate">
  7633. {printer.name || printer.serial}
  7634. </p>
  7635. <p className="text-xs text-bambu-gray truncate">
  7636. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7637. {printer.serial.startsWith('unknown-') && (
  7638. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7639. )}
  7640. </p>
  7641. </div>
  7642. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7643. </div>
  7644. ))}
  7645. </div>
  7646. )}
  7647. {discovering && (
  7648. <p className="mt-2 text-sm text-bambu-gray text-center">
  7649. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7650. </p>
  7651. )}
  7652. {hasScanned && !discovering && discovered.length === 0 && (
  7653. <p className="mt-2 text-sm text-bambu-gray text-center">
  7654. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7655. </p>
  7656. )}
  7657. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7658. <p className="mt-2 text-sm text-bambu-gray text-center">
  7659. {t('printers.discovery.allConfigured')}
  7660. </p>
  7661. )}
  7662. </div>
  7663. <form onSubmit={handleAddSubmit} className="space-y-4">
  7664. <div>
  7665. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7666. <input
  7667. type="text"
  7668. required
  7669. 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"
  7670. value={form.name}
  7671. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7672. placeholder={t('printers.modal.myPrinter')}
  7673. />
  7674. </div>
  7675. <div>
  7676. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7677. <input
  7678. type="text"
  7679. required
  7680. 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])?)*)"
  7681. 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"
  7682. value={form.ip_address}
  7683. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7684. placeholder="192.168.1.100 or printer.local"
  7685. />
  7686. </div>
  7687. <div>
  7688. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7689. <input
  7690. type="text"
  7691. required
  7692. 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"
  7693. value={form.serial_number}
  7694. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7695. placeholder="01P00A000000000"
  7696. />
  7697. </div>
  7698. <div>
  7699. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7700. <input
  7701. type="password"
  7702. required
  7703. 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"
  7704. value={form.access_code}
  7705. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7706. placeholder={t('printers.modal.fromPrinterSettings')}
  7707. />
  7708. </div>
  7709. <div>
  7710. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7711. <select
  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.model || ''}
  7714. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7715. >
  7716. <option value="">{t('printers.modal.selectModel')}</option>
  7717. <optgroup label="A1 Series">
  7718. <option value="A1">A1</option>
  7719. <option value="A1 Mini">A1 Mini</option>
  7720. </optgroup>
  7721. <optgroup label="A2 Series">
  7722. <option value="A2L">A2L</option>
  7723. </optgroup>
  7724. <optgroup label="H2 Series">
  7725. <option value="H2C">H2C</option>
  7726. <option value="H2D">H2D</option>
  7727. <option value="H2D Pro">H2D Pro</option>
  7728. <option value="H2S">H2S</option>
  7729. </optgroup>
  7730. <optgroup label="P Series">
  7731. <option value="P1P">P1P</option>
  7732. <option value="P1S">P1S</option>
  7733. <option value="P2S">P2S</option>
  7734. </optgroup>
  7735. <optgroup label="X1 Series">
  7736. <option value="X1">X1</option>
  7737. <option value="X1C">X1 Carbon</option>
  7738. <option value="X1E">X1E</option>
  7739. </optgroup>
  7740. <optgroup label="X2 Series">
  7741. <option value="X2D">X2D</option>
  7742. </optgroup>
  7743. </select>
  7744. </div>
  7745. <div>
  7746. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7747. <input
  7748. type="text"
  7749. 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"
  7750. value={form.location || ''}
  7751. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7752. placeholder={t('printers.modal.locationPlaceholder')}
  7753. />
  7754. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7755. </div>
  7756. <div className="flex items-center gap-2">
  7757. <input
  7758. type="checkbox"
  7759. id="auto_archive"
  7760. checked={form.auto_archive}
  7761. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7762. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7763. />
  7764. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7765. {t('printers.modal.autoArchiveLabel')}
  7766. </label>
  7767. </div>
  7768. <button
  7769. type="button"
  7770. onClick={() => setShowDiagnostic(true)}
  7771. disabled={!form.ip_address.trim()}
  7772. 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"
  7773. >
  7774. <Stethoscope className="w-4 h-4" />
  7775. {t('diagnostic.runButton')}
  7776. </button>
  7777. {saveWarning ? (
  7778. <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">
  7779. <div className="flex items-start gap-2">
  7780. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7781. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7782. </div>
  7783. <DiagnosticChecklist result={saveWarning} />
  7784. <div className="flex gap-3">
  7785. <Button
  7786. type="button"
  7787. variant="secondary"
  7788. onClick={() => setSaveWarning(null)}
  7789. className="flex-1"
  7790. >
  7791. {t('printers.addPreflight.back')}
  7792. </Button>
  7793. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7794. {t('printers.addPreflight.saveAnyway')}
  7795. </Button>
  7796. </div>
  7797. </div>
  7798. ) : (
  7799. <div className="flex gap-3 pt-2">
  7800. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7801. {t('common.cancel')}
  7802. </Button>
  7803. <Button type="submit" disabled={checkingSave} className="flex-1">
  7804. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7805. </Button>
  7806. </div>
  7807. )}
  7808. </form>
  7809. </CardContent>
  7810. </Card>
  7811. </div>
  7812. {showDiagnostic && (
  7813. <ConnectionDiagnosticModal
  7814. connection={{
  7815. ip_address: form.ip_address.trim(),
  7816. serial_number: form.serial_number.trim() || undefined,
  7817. access_code: form.access_code || undefined,
  7818. }}
  7819. printerName={form.name || null}
  7820. onClose={() => setShowDiagnostic(false)}
  7821. />
  7822. )}
  7823. </>
  7824. );
  7825. }
  7826. function FirmwareUpdateModal({
  7827. printer,
  7828. firmwareInfo,
  7829. onClose,
  7830. }: {
  7831. printer: Printer;
  7832. firmwareInfo: FirmwareUpdateInfo;
  7833. onClose: () => void;
  7834. }) {
  7835. const { t } = useTranslation();
  7836. const queryClient = useQueryClient();
  7837. const { showToast } = useToast();
  7838. const { hasPermission } = useAuth();
  7839. const canUpdate = hasPermission('firmware:update');
  7840. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7841. const [isUploading, setIsUploading] = useState(false);
  7842. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7843. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7844. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7845. );
  7846. // Prepare check query — runs when a version is selected and user can update
  7847. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7848. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7849. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7850. staleTime: 30000,
  7851. enabled: !!selectedVersion && canUpdate && !isUploading,
  7852. });
  7853. // Start upload mutation
  7854. const uploadMutation = useMutation({
  7855. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7856. onSuccess: () => {
  7857. setIsUploading(true);
  7858. // Start polling for status
  7859. const interval = setInterval(async () => {
  7860. try {
  7861. const status = await firmwareApi.getUploadStatus(printer.id);
  7862. setUploadStatus(status);
  7863. if (status.status === 'complete' || status.status === 'error') {
  7864. clearInterval(interval);
  7865. setPollInterval(null);
  7866. setIsUploading(false);
  7867. if (status.status === 'complete') {
  7868. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7869. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7870. }
  7871. }
  7872. } catch {
  7873. // Ignore errors during polling
  7874. }
  7875. }, 2000);
  7876. setPollInterval(interval);
  7877. },
  7878. onError: (error: Error) => {
  7879. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7880. setIsUploading(false);
  7881. },
  7882. });
  7883. // Cleanup on unmount
  7884. useEffect(() => {
  7885. return () => {
  7886. if (pollInterval) clearInterval(pollInterval);
  7887. };
  7888. }, [pollInterval]);
  7889. const handleStartUpload = () => {
  7890. setUploadStatus(null);
  7891. uploadMutation.mutate();
  7892. };
  7893. return (
  7894. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7895. <Card className="w-full max-w-md mx-4">
  7896. <CardContent>
  7897. <div className="flex items-start gap-3 mb-4">
  7898. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7899. {firmwareInfo.update_available
  7900. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7901. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7902. </div>
  7903. <div className="flex-1">
  7904. <h3 className="text-lg font-semibold text-white">
  7905. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7906. </h3>
  7907. <p className="text-sm text-bambu-gray mt-1">
  7908. {printer.name}
  7909. </p>
  7910. </div>
  7911. </div>
  7912. {/* Version Info */}
  7913. {(() => {
  7914. const selectedEntry = selectedVersion
  7915. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7916. : null;
  7917. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7918. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7919. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7920. return (
  7921. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7922. <div className="flex justify-between items-center text-sm">
  7923. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7924. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7925. {firmwareInfo.current_version || t('common.unknown')}
  7926. </span>
  7927. </div>
  7928. {showSecondLine && (
  7929. <div className="flex justify-between items-center text-sm mt-1">
  7930. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7931. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7932. </div>
  7933. )}
  7934. {displayNotes && (
  7935. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7936. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7937. {t('printers.firmwareModal.releaseNotes')}
  7938. </summary>
  7939. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7940. {displayNotes}
  7941. </div>
  7942. </details>
  7943. )}
  7944. </div>
  7945. );
  7946. })()}
  7947. {/* Available versions list */}
  7948. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7949. <div className="mb-4">
  7950. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7951. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7952. {firmwareInfo.available_versions.map((v) => {
  7953. const isCurrent = firmwareInfo.current_version === v.version;
  7954. const isSelected = selectedVersion === v.version;
  7955. const cmp = firmwareInfo.current_version
  7956. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7957. : 0;
  7958. const relLabel = isCurrent
  7959. ? t('printers.firmwareModal.currentBadge')
  7960. : cmp > 0
  7961. ? t('printers.firmwareModal.newerBadge')
  7962. : t('printers.firmwareModal.olderBadge');
  7963. const relClass = isCurrent
  7964. ? 'text-bambu-gray'
  7965. : cmp > 0
  7966. ? 'text-orange-700 dark:text-orange-400'
  7967. : 'text-blue-700 dark:text-blue-400';
  7968. return (
  7969. <button
  7970. key={v.version}
  7971. type="button"
  7972. disabled={!v.file_available || !canUpdate || isCurrent}
  7973. onClick={() => setSelectedVersion(v.version)}
  7974. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7975. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7976. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7977. >
  7978. <div className="flex items-center gap-2 min-w-0">
  7979. <span className="font-mono text-white">{v.version}</span>
  7980. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7981. </div>
  7982. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7983. isCurrent
  7984. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7985. : v.file_available
  7986. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7987. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7988. }`}>
  7989. {isCurrent
  7990. ? t('printers.firmwareModal.installed')
  7991. : v.file_available
  7992. ? t('printers.firmwareModal.usable')
  7993. : t('printers.firmwareModal.unavailable')}
  7994. </span>
  7995. </button>
  7996. );
  7997. })}
  7998. </div>
  7999. </div>
  8000. )}
  8001. {/* Status / Progress (only when a version is selected) */}
  8002. {!selectedVersion ? null : isPreparing ? (
  8003. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  8004. <Loader2 className="w-4 h-4 animate-spin" />
  8005. {t('printers.firmwareModal.checkingPrereqs')}
  8006. </div>
  8007. ) : prepareInfo && !isUploading && !uploadStatus ? (
  8008. <div className="mb-4">
  8009. {prepareInfo.can_proceed ? (
  8010. <div className="flex items-center gap-2 text-bambu-green text-sm">
  8011. <Box className="w-4 h-4" />
  8012. {t('printers.firmwareModal.sdCardReady')}
  8013. </div>
  8014. ) : (
  8015. <div className="space-y-1">
  8016. {prepareInfo.errors.map((error, i) => (
  8017. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  8018. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  8019. {error}
  8020. </div>
  8021. ))}
  8022. </div>
  8023. )}
  8024. </div>
  8025. ) : null}
  8026. {/* Upload Progress */}
  8027. {(isUploading || uploadStatus) && uploadStatus && (
  8028. <div className="mb-4">
  8029. <div className="flex items-center justify-between text-sm mb-1">
  8030. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8031. <span className="text-white">{uploadStatus.progress}%</span>
  8032. </div>
  8033. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8034. <div
  8035. className={`h-2 rounded-full transition-all ${
  8036. uploadStatus.status === 'error' ? 'bg-status-error' :
  8037. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8038. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8039. style={{ width: `${uploadStatus.progress}%` }}
  8040. />
  8041. </div>
  8042. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8043. {uploadStatus.error && (
  8044. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8045. )}
  8046. </div>
  8047. )}
  8048. {/* Success Message */}
  8049. {uploadStatus?.status === 'complete' && (
  8050. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8051. <p className="text-sm text-bambu-green font-medium mb-2">
  8052. {t('printers.firmwareModal.uploadedSuccess')}
  8053. </p>
  8054. <p className="text-xs text-bambu-gray">
  8055. {t('printers.firmwareModal.applyInstructions')}
  8056. </p>
  8057. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8058. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8059. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8060. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8061. <li>{t('printers.firmwareModal.step4')}</li>
  8062. </ol>
  8063. </div>
  8064. )}
  8065. {/* Buttons */}
  8066. <div className="flex gap-2 justify-end">
  8067. <Button variant="secondary" onClick={onClose}>
  8068. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8069. </Button>
  8070. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8071. <Button
  8072. onClick={handleStartUpload}
  8073. disabled={uploadMutation.isPending}
  8074. >
  8075. {uploadMutation.isPending ? (
  8076. <>
  8077. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8078. {t('printers.firmwareModal.starting')}
  8079. </>
  8080. ) : (
  8081. <>
  8082. <Download className="w-4 h-4 mr-2" />
  8083. {t('printers.firmwareModal.uploadFirmware')}
  8084. </>
  8085. )}
  8086. </Button>
  8087. )}
  8088. </div>
  8089. </CardContent>
  8090. </Card>
  8091. </div>
  8092. );
  8093. }
  8094. function EditPrinterModal({
  8095. printer,
  8096. onClose,
  8097. }: {
  8098. printer: Printer;
  8099. onClose: () => void;
  8100. }) {
  8101. const { t } = useTranslation();
  8102. const queryClient = useQueryClient();
  8103. const { showToast } = useToast();
  8104. const [form, setForm] = useState({
  8105. name: printer.name,
  8106. ip_address: printer.ip_address,
  8107. access_code: '',
  8108. model: printer.model || '',
  8109. location: printer.location || '',
  8110. auto_archive: printer.auto_archive,
  8111. is_active: printer.is_active,
  8112. });
  8113. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8114. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8115. const [checkingSave, setCheckingSave] = useState(false);
  8116. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8117. const updateMutation = useMutation({
  8118. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8119. onSuccess: () => {
  8120. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8121. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8122. onClose();
  8123. },
  8124. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8125. });
  8126. // Close on Escape key
  8127. useEffect(() => {
  8128. const handleKeyDown = (e: KeyboardEvent) => {
  8129. if (e.key === 'Escape') onClose();
  8130. };
  8131. window.addEventListener('keydown', handleKeyDown);
  8132. return () => window.removeEventListener('keydown', handleKeyDown);
  8133. }, [onClose]);
  8134. const doSave = () => {
  8135. const data: Partial<PrinterCreate> = {
  8136. name: form.name,
  8137. ip_address: form.ip_address,
  8138. model: form.model || undefined,
  8139. location: form.location || undefined,
  8140. auto_archive: form.auto_archive,
  8141. is_active: form.is_active,
  8142. };
  8143. // Only include access_code if it was changed
  8144. if (form.access_code) {
  8145. data.access_code = form.access_code;
  8146. }
  8147. updateMutation.mutate(data);
  8148. };
  8149. const handleSubmit = async (e: React.FormEvent) => {
  8150. e.preventDefault();
  8151. setCheckingSave(true);
  8152. try {
  8153. const result = await api.diagnoseConnection({
  8154. ip_address: form.ip_address.trim(),
  8155. serial_number: printer.serial_number,
  8156. access_code: form.access_code || undefined,
  8157. });
  8158. if (result.checks.some((c) => c.status === 'fail')) {
  8159. setSaveWarning(result);
  8160. return;
  8161. }
  8162. } catch {
  8163. // Diagnostic infrastructure failed — never block the save on it.
  8164. } finally {
  8165. setCheckingSave(false);
  8166. }
  8167. doSave();
  8168. };
  8169. return (
  8170. <div
  8171. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8172. onClick={onClose}
  8173. >
  8174. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8175. <CardContent>
  8176. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8177. <form onSubmit={handleSubmit} className="space-y-4">
  8178. <div>
  8179. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8180. <input
  8181. type="text"
  8182. required
  8183. 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"
  8184. value={form.name}
  8185. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8186. placeholder={t('printers.modal.myPrinter')}
  8187. />
  8188. </div>
  8189. <div>
  8190. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8191. <input
  8192. type="text"
  8193. required
  8194. 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])?)*)"
  8195. 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"
  8196. value={form.ip_address}
  8197. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8198. placeholder="192.168.1.100 or printer.local"
  8199. />
  8200. </div>
  8201. <div>
  8202. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8203. <input
  8204. type="text"
  8205. disabled
  8206. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8207. value={printer.serial_number}
  8208. />
  8209. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8210. </div>
  8211. <div>
  8212. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8213. <input
  8214. type="password"
  8215. 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"
  8216. value={form.access_code}
  8217. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8218. placeholder={t('printers.accessCodePlaceholder')}
  8219. />
  8220. </div>
  8221. <div>
  8222. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8223. <select
  8224. 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"
  8225. value={form.model}
  8226. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8227. >
  8228. <option value="">{t('printers.modal.selectModel')}</option>
  8229. <optgroup label="A1 Series">
  8230. <option value="A1">A1</option>
  8231. <option value="A1 Mini">A1 Mini</option>
  8232. </optgroup>
  8233. <optgroup label="A2 Series">
  8234. <option value="A2L">A2L</option>
  8235. </optgroup>
  8236. <optgroup label="H2 Series">
  8237. <option value="H2C">H2C</option>
  8238. <option value="H2D">H2D</option>
  8239. <option value="H2D Pro">H2D Pro</option>
  8240. <option value="H2S">H2S</option>
  8241. </optgroup>
  8242. <optgroup label="P Series">
  8243. <option value="P1P">P1P</option>
  8244. <option value="P1S">P1S</option>
  8245. <option value="P2S">P2S</option>
  8246. </optgroup>
  8247. <optgroup label="X1 Series">
  8248. <option value="X1">X1</option>
  8249. <option value="X1C">X1 Carbon</option>
  8250. <option value="X1E">X1E</option>
  8251. </optgroup>
  8252. <optgroup label="X2 Series">
  8253. <option value="X2D">X2D</option>
  8254. </optgroup>
  8255. </select>
  8256. </div>
  8257. <div>
  8258. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8259. <input
  8260. type="text"
  8261. 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"
  8262. value={form.location}
  8263. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8264. placeholder={t('printers.modal.locationPlaceholder')}
  8265. />
  8266. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8267. </div>
  8268. <div className="flex items-center gap-2">
  8269. <input
  8270. type="checkbox"
  8271. id="edit_auto_archive"
  8272. checked={form.auto_archive}
  8273. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8274. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8275. />
  8276. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8277. {t('printers.modal.autoArchiveLabel')}
  8278. </label>
  8279. </div>
  8280. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8281. is_active because the user-facing concept is "is this printer
  8282. in maintenance" not "is it active". */}
  8283. <div>
  8284. <div className="flex items-center gap-2">
  8285. <input
  8286. type="checkbox"
  8287. id="edit_maintenance_mode"
  8288. checked={!form.is_active}
  8289. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8290. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8291. />
  8292. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8293. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8294. {t('printers.maintenance.editFieldLabel')}
  8295. </label>
  8296. </div>
  8297. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8298. {t('printers.maintenance.editFieldHelp')}
  8299. </p>
  8300. </div>
  8301. {saveWarning ? (
  8302. <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">
  8303. <div className="flex items-start gap-2">
  8304. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8305. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8306. </div>
  8307. <DiagnosticChecklist result={saveWarning} />
  8308. <div className="flex gap-3">
  8309. <Button
  8310. type="button"
  8311. variant="secondary"
  8312. onClick={() => setSaveWarning(null)}
  8313. className="flex-1"
  8314. >
  8315. {t('printers.addPreflight.back')}
  8316. </Button>
  8317. <Button
  8318. type="button"
  8319. onClick={doSave}
  8320. className="flex-1"
  8321. disabled={updateMutation.isPending}
  8322. >
  8323. {t('printers.addPreflight.saveAnyway')}
  8324. </Button>
  8325. </div>
  8326. </div>
  8327. ) : (
  8328. <div className="flex gap-3 pt-4">
  8329. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8330. {t('common.cancel')}
  8331. </Button>
  8332. <Button
  8333. type="submit"
  8334. className="flex-1"
  8335. disabled={updateMutation.isPending || checkingSave}
  8336. >
  8337. {checkingSave
  8338. ? t('printers.addPreflight.checking')
  8339. : updateMutation.isPending
  8340. ? t('common.saving')
  8341. : t('printers.modal.saveChanges')}
  8342. </Button>
  8343. </div>
  8344. )}
  8345. </form>
  8346. </CardContent>
  8347. </Card>
  8348. </div>
  8349. );
  8350. }
  8351. // Component to check if a printer is offline (for power dropdown)
  8352. function usePrinterOfflineStatus(printerId: number) {
  8353. const { data: status } = useQuery({
  8354. queryKey: ['printerStatus', printerId],
  8355. queryFn: () => api.getPrinterStatus(printerId),
  8356. refetchInterval: 30000,
  8357. });
  8358. return !status?.connected;
  8359. }
  8360. // Power dropdown item for an offline printer
  8361. function PowerDropdownItem({
  8362. printer,
  8363. plug,
  8364. onPowerOn,
  8365. isPowering,
  8366. }: {
  8367. printer: Printer;
  8368. plug: { id: number; name: string };
  8369. onPowerOn: (plugId: number) => void;
  8370. isPowering: boolean;
  8371. }) {
  8372. const isOffline = usePrinterOfflineStatus(printer.id);
  8373. // Fetch plug status
  8374. const { data: plugStatus } = useQuery({
  8375. queryKey: ['smartPlugStatus', plug.id],
  8376. queryFn: () => api.getSmartPlugStatus(plug.id),
  8377. refetchInterval: 10000,
  8378. });
  8379. // Only show if printer is offline
  8380. if (!isOffline) {
  8381. return null;
  8382. }
  8383. return (
  8384. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8385. <div className="flex items-center gap-2 min-w-0">
  8386. <span className="text-sm text-white truncate">{printer.name}</span>
  8387. {plugStatus && (
  8388. <span
  8389. className={`text-xs px-1.5 py-0.5 rounded ${
  8390. plugStatus.state === 'ON'
  8391. ? 'bg-bambu-green/20 text-bambu-green'
  8392. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8393. }`}
  8394. >
  8395. {plugStatus.state || '?'}
  8396. </span>
  8397. )}
  8398. </div>
  8399. <button
  8400. onClick={() => onPowerOn(plug.id)}
  8401. disabled={isPowering || plugStatus?.state === 'ON'}
  8402. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8403. plugStatus?.state === 'ON'
  8404. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8405. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8406. }`}
  8407. >
  8408. <Power className="w-3 h-3" />
  8409. {isPowering ? '...' : 'On'}
  8410. </button>
  8411. </div>
  8412. );
  8413. }
  8414. export function PrintersPage() {
  8415. const { t } = useTranslation();
  8416. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8417. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8418. const accentButtonClass = {
  8419. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8420. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8421. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8422. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8423. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8424. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8425. }[activeAccent];
  8426. const [showAddModal, setShowAddModal] = useState(false);
  8427. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8428. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8429. });
  8430. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8431. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8432. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8433. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8434. });
  8435. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8436. return localStorage.getItem('printerSortAsc') !== 'false';
  8437. });
  8438. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8439. const [cardSize, setCardSize] = useState<number>(() => {
  8440. const saved = localStorage.getItem('printerCardSize');
  8441. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8442. });
  8443. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8444. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8445. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8446. });
  8447. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8448. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8449. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8450. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8451. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8452. });
  8453. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8454. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8455. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8456. });
  8457. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8458. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8459. // Defaulting to 'full' because the cards already show this info — users who
  8460. // pick cam-wall view still want to glance the same details without flipping.
  8461. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8462. const saved = localStorage.getItem('camWallStatusMode');
  8463. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8464. });
  8465. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8466. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8467. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8468. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8469. requestAnimationFrame(() => {
  8470. requestAnimationFrame(() => {
  8471. const card = document.getElementById(`printer-card-${printerId}`);
  8472. if (!card) return;
  8473. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8474. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8475. window.scrollTo({
  8476. top: Math.max(0, top),
  8477. behavior: 'smooth',
  8478. });
  8479. });
  8480. });
  8481. }, []);
  8482. const openCompactCard = useCallback((printerId: number) => {
  8483. setCompactDrilldownPrinterId(printerId);
  8484. setCardSize(2);
  8485. localStorage.setItem('printerCardSize', '2');
  8486. scrollPrinterIntoView(printerId);
  8487. }, [scrollPrinterIntoView]);
  8488. const returnToCompactCards = useCallback(() => {
  8489. const printerId = compactDrilldownPrinterId;
  8490. setCompactDrilldownPrinterId(null);
  8491. setCardSize(1);
  8492. localStorage.setItem('printerCardSize', '1');
  8493. if (printerId != null) {
  8494. scrollPrinterIntoView(printerId);
  8495. }
  8496. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8497. const [search, setSearch] = useState('');
  8498. // Both filters persist like every other preference on this page (#2833).
  8499. // `search` deliberately does not: a box that silently refills itself on
  8500. // return is more surprising than a dropdown that remembers.
  8501. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8502. // Validated on read: a value the dropdown no longer offers would filter
  8503. // every printer out, and nothing would explain why.
  8504. const saved = localStorage.getItem('printerStatusFilter');
  8505. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8506. });
  8507. const [locationFilter, setLocationFilter] = useState<string>(
  8508. () => localStorage.getItem('printerLocationFilter') || 'all'
  8509. );
  8510. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8511. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8512. try {
  8513. const saved = localStorage.getItem('printerCollapsedSections');
  8514. return saved ? JSON.parse(saved) : {};
  8515. } catch { return {}; }
  8516. });
  8517. const queryClient = useQueryClient();
  8518. const { showToast } = useToast();
  8519. const { hasPermission } = useAuth();
  8520. // Which way the camera buttons open a stream. Chosen per click from the
  8521. // button's own menu; null until this browser has made a choice, so the
  8522. // stored setting below can act as the default a fresh browser starts from.
  8523. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8524. () => readStoredCameraViewMode()
  8525. );
  8526. // Embedded camera viewer state - supports multiple simultaneous viewers
  8527. // Persisted to localStorage so cameras reopen after navigation
  8528. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8529. const saved = localStorage.getItem('openEmbeddedCameras');
  8530. if (saved) {
  8531. try {
  8532. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8533. return new Map(cameras.map(c => [c.id, c]));
  8534. } catch {
  8535. return new Map();
  8536. }
  8537. }
  8538. return new Map();
  8539. });
  8540. // Persist open cameras to localStorage when they change
  8541. useEffect(() => {
  8542. const cameras = Array.from(embeddedCameraPrinters.values());
  8543. if (cameras.length > 0) {
  8544. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8545. } else {
  8546. localStorage.removeItem('openEmbeddedCameras');
  8547. }
  8548. }, [embeddedCameraPrinters]);
  8549. const { data: printers, isLoading } = useQuery({
  8550. queryKey: ['printers'],
  8551. queryFn: api.getPrinters,
  8552. });
  8553. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8554. // so users with printers:read but no settings:read still get the values needed
  8555. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8556. const { data: settings } = useQuery({
  8557. queryKey: ['ui-preferences'],
  8558. queryFn: api.getUiPreferences,
  8559. });
  8560. // Parse user-configured temperature/fan presets once, with defensive fallback
  8561. // to built-in defaults on parse failure (validators on the backend already
  8562. // reject malformed writes, so this is just forward-compat).
  8563. const effectiveNozzleTempPresets = useMemo(
  8564. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8565. [settings?.nozzle_temp_presets],
  8566. );
  8567. const effectiveBedTempPresets = useMemo(
  8568. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8569. [settings?.bed_temp_presets],
  8570. );
  8571. const effectiveChamberTempPresets = useMemo(
  8572. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8573. [settings?.chamber_temp_presets],
  8574. );
  8575. const effectiveFanSpeedPresets = useMemo(
  8576. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8577. [settings?.fan_speed_presets],
  8578. );
  8579. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8580. const effectiveDryingPresets = useMemo(() => {
  8581. if (settings?.drying_presets) {
  8582. try {
  8583. const userPresets = JSON.parse(settings.drying_presets);
  8584. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8585. return { ...DRYING_PRESETS, ...userPresets };
  8586. }
  8587. } catch { /* ignore parse errors, use defaults */ }
  8588. }
  8589. return DRYING_PRESETS;
  8590. }, [settings?.drying_presets]);
  8591. // The local choice wins over the stored one: someone without settings:update
  8592. // cannot write their pick back, and a preference that silently reverted on
  8593. // the next render would be worse than none at all.
  8594. const cameraViewMode: CameraViewMode =
  8595. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8596. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8597. storeCameraViewMode(mode);
  8598. setChosenCameraViewMode(mode);
  8599. // Best effort, and only a default for other browsers -- the choice is
  8600. // already in effect here. Users below settings:update simply keep theirs
  8601. // locally, which is why the failure is logged rather than surfaced.
  8602. if (hasPermission('settings:update')) {
  8603. api.updateSettings({ camera_view_mode: mode })
  8604. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8605. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8606. }
  8607. }, [hasPermission, queryClient]);
  8608. // Fetch all smart plugs to know which printers have them
  8609. const { data: smartPlugs } = useQuery({
  8610. queryKey: ['smart-plugs'],
  8611. queryFn: api.getSmartPlugs,
  8612. });
  8613. // Fetch maintenance overview for all printers to show badges
  8614. const { data: maintenanceOverview } = useQuery({
  8615. queryKey: ['maintenanceOverview'],
  8616. queryFn: api.getMaintenanceOverview,
  8617. staleTime: 60 * 1000, // 1 minute
  8618. });
  8619. // Live AI failure detection state for the card badges (#1546). Matches the
  8620. // 10s refetch of the Failure Detection settings panel.
  8621. const { data: obicoPrinterStatus } = useQuery({
  8622. queryKey: ['obico-printer-status'],
  8623. queryFn: api.getObicoPrinterStatus,
  8624. refetchInterval: 10000,
  8625. });
  8626. // Badge visibility: detection enabled AND this printer in the monitored set
  8627. // (monitored_printers null = all). Live per-print state is passed separately.
  8628. const isAiMonitored = useCallback(
  8629. (printerId: number) =>
  8630. obicoPrinterStatus?.enabled === true &&
  8631. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8632. [obicoPrinterStatus],
  8633. );
  8634. // Fetch Spoolman status to enable link spool feature
  8635. const { data: spoolmanStatus } = useQuery({
  8636. queryKey: ['spoolman-status'],
  8637. queryFn: api.getSpoolmanStatus,
  8638. staleTime: 60 * 1000, // 1 minute
  8639. });
  8640. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8641. // Fetch Spoolman settings to get sync mode
  8642. const { data: spoolmanSettings } = useQuery({
  8643. queryKey: ['spoolman-settings'],
  8644. queryFn: api.getSpoolmanSettings,
  8645. enabled: !!spoolmanEnabled,
  8646. staleTime: 60 * 1000, // 1 minute
  8647. });
  8648. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8649. // Fetch unlinked spools to know if link button should be enabled
  8650. const { data: unlinkedSpools } = useQuery({
  8651. queryKey: ['unlinked-spools'],
  8652. queryFn: api.getUnlinkedSpools,
  8653. enabled: !!spoolmanEnabled,
  8654. staleTime: 30 * 1000, // 30 seconds
  8655. });
  8656. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8657. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8658. const { data: linkedSpoolsData } = useQuery({
  8659. queryKey: ['linked-spools'],
  8660. queryFn: api.getLinkedSpools,
  8661. enabled: !!spoolmanEnabled,
  8662. staleTime: 30 * 1000, // 30 seconds
  8663. });
  8664. const linkedSpools = linkedSpoolsData?.linked;
  8665. // Fetch spool assignments for inventory feature
  8666. const { data: spoolAssignments } = useQuery({
  8667. queryKey: ['spool-assignments'],
  8668. queryFn: () => api.getAssignments(),
  8669. enabled: hasPermission('inventory:view_assignments'),
  8670. staleTime: 30 * 1000,
  8671. });
  8672. const unassignMutation = useMutation({
  8673. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8674. api.unassignSpool(printerId, amsId, trayId),
  8675. onSuccess: () => {
  8676. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8677. },
  8678. });
  8679. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8680. queryKey: ['spoolman-inventory-spools'],
  8681. queryFn: () => api.getSpoolmanInventorySpools(false),
  8682. enabled: !!spoolmanEnabled,
  8683. staleTime: 30 * 1000,
  8684. });
  8685. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8686. queryKey: ['spoolman-slot-assignments'],
  8687. queryFn: () => api.getSpoolmanSlotAssignments(),
  8688. enabled: !!spoolmanEnabled,
  8689. staleTime: 30 * 1000,
  8690. });
  8691. const unassignSpoolmanMutation = useMutation({
  8692. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8693. onSuccess: () => {
  8694. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8695. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8696. },
  8697. });
  8698. // Helper to find assignment for a specific slot
  8699. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8700. return spoolAssignments?.find(
  8701. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8702. );
  8703. };
  8704. // Create a map of printer_id -> maintenance info for quick lookup
  8705. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8706. (acc, overview) => {
  8707. acc[overview.printer_id] = {
  8708. due_count: overview.due_count,
  8709. warning_count: overview.warning_count,
  8710. total_print_hours: overview.total_print_hours,
  8711. };
  8712. return acc;
  8713. },
  8714. {} as Record<number, PrinterMaintenanceInfo>
  8715. ) || {};
  8716. // Create a map of printer_id -> smart plug
  8717. const smartPlugByPrinter = smartPlugs?.reduce(
  8718. (acc, plug) => {
  8719. if (plug.printer_id) {
  8720. acc[plug.printer_id] = plug;
  8721. }
  8722. return acc;
  8723. },
  8724. {} as Record<number, typeof smartPlugs[0]>
  8725. ) || {};
  8726. const addMutation = useMutation({
  8727. mutationFn: api.createPrinter,
  8728. onSuccess: () => {
  8729. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8730. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8731. setShowAddModal(false);
  8732. },
  8733. onError: (error: Error) => {
  8734. // Localized message when the backend returns a stable error code;
  8735. // the raw message is an English fallback for non-UI clients.
  8736. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8737. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8738. return;
  8739. }
  8740. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8741. },
  8742. });
  8743. const powerOnMutation = useMutation({
  8744. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8745. onSuccess: () => {
  8746. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8747. setPoweringOn(null);
  8748. },
  8749. onError: () => {
  8750. setPoweringOn(null);
  8751. },
  8752. });
  8753. // Bulk selection state
  8754. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8755. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8756. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8757. const [bulkActionPending, setBulkActionPending] = useState(false);
  8758. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8759. const toggleSelect = useCallback((id: number) => {
  8760. setSelectedPrinterIds(prev => {
  8761. const next = new Set(prev);
  8762. if (next.has(id)) next.delete(id);
  8763. else next.add(id);
  8764. return next;
  8765. });
  8766. }, []);
  8767. const clearSelection = useCallback(() => {
  8768. setSelectedPrinterIds(new Set());
  8769. setIsSelectionMode(false);
  8770. }, []);
  8771. // Escape key exits selection mode
  8772. useEffect(() => {
  8773. const handleKeyDown = (e: KeyboardEvent) => {
  8774. if (e.key === 'Escape' && selectionMode) {
  8775. clearSelection();
  8776. }
  8777. };
  8778. window.addEventListener('keydown', handleKeyDown);
  8779. return () => window.removeEventListener('keydown', handleKeyDown);
  8780. }, [selectionMode, clearSelection]);
  8781. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8782. setBulkActionPending(true);
  8783. const ids = Array.from(selectedPrinterIds);
  8784. // Filter to only applicable printers based on cached state
  8785. const applicableIds = ids.filter(id => {
  8786. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8787. // clearPlate is checked before the connection filter: it only releases a
  8788. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8789. // down — every other action here needs to reach the machine (#2864).
  8790. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8791. if (!status?.connected) return false;
  8792. switch (action) {
  8793. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8794. case 'pause': return status.state === 'RUNNING';
  8795. case 'resume': return status.state === 'PAUSE';
  8796. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8797. default: return false;
  8798. }
  8799. });
  8800. if (applicableIds.length === 0) {
  8801. showToast(t('printers.bulk.noneApplicable'), 'error');
  8802. setBulkActionPending(false);
  8803. setBulkConfirmAction(null);
  8804. return;
  8805. }
  8806. const apiCall = {
  8807. stop: api.stopPrint,
  8808. pause: api.pausePrint,
  8809. resume: api.resumePrint,
  8810. clearPlate: api.clearPlate,
  8811. clearHMS: api.clearHMSErrors,
  8812. }[action];
  8813. const results = await Promise.allSettled(
  8814. applicableIds.map(id => apiCall(id))
  8815. );
  8816. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8817. const failed = results.filter(r => r.status === 'rejected').length;
  8818. if (failed === 0) {
  8819. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8820. } else {
  8821. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8822. }
  8823. // Invalidate status queries for affected printers
  8824. applicableIds.forEach(id => {
  8825. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8826. });
  8827. setBulkActionPending(false);
  8828. setBulkConfirmAction(null);
  8829. }, [selectedPrinterIds, queryClient, showToast, t]);
  8830. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8831. // Actions that need confirmation
  8832. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8833. setBulkConfirmAction(action);
  8834. } else {
  8835. executeBulkAction(action);
  8836. }
  8837. }, [executeBulkAction]);
  8838. const toggleHideDisconnected = () => {
  8839. const newValue = !hideDisconnected;
  8840. setHideDisconnected(newValue);
  8841. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8842. };
  8843. const handleSortChange = (newSort: SortOption) => {
  8844. setSortBy(newSort);
  8845. localStorage.setItem('printerSortBy', newSort);
  8846. };
  8847. const handleStatusFilterChange = (value: string) => {
  8848. setStatusFilter(value);
  8849. localStorage.setItem('printerStatusFilter', value);
  8850. };
  8851. const handleLocationFilterChange = (value: string) => {
  8852. setLocationFilter(value);
  8853. localStorage.setItem('printerLocationFilter', value);
  8854. };
  8855. const toggleSortDirection = () => {
  8856. const newAsc = !sortAsc;
  8857. setSortAsc(newAsc);
  8858. localStorage.setItem('printerSortAsc', String(newAsc));
  8859. };
  8860. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8861. const getGridClasses = () => {
  8862. switch (cardSize) {
  8863. 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
  8864. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8865. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8866. case 4: return 'grid-cols-1'; // XL: single column, full width
  8867. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8868. }
  8869. };
  8870. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8871. // Increment version counter whenever a printer status cache entry is updated so
  8872. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8873. useEffect(() => {
  8874. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8875. if (
  8876. event.type === 'updated' &&
  8877. Array.isArray(event.query.queryKey) &&
  8878. event.query.queryKey[0] === 'printerStatus'
  8879. ) {
  8880. setStatusCacheVersion(v => v + 1);
  8881. }
  8882. });
  8883. return unsubscribe;
  8884. }, [queryClient]);
  8885. // Filter printers by search term, status, and location
  8886. const filteredPrinters = useMemo(() => {
  8887. if (!printers) return [];
  8888. let result = printers;
  8889. // Text search
  8890. if (search.trim()) {
  8891. const q = search.trim().toLowerCase();
  8892. result = result.filter(p =>
  8893. p.name.toLowerCase().includes(q) ||
  8894. (p.model || '').toLowerCase().includes(q) ||
  8895. (p.location || '').toLowerCase().includes(q) ||
  8896. (p.serial_number || '').toLowerCase().includes(q)
  8897. );
  8898. }
  8899. // Location filter
  8900. if (locationFilter !== 'all') {
  8901. result = result.filter(p => (p.location || '') === locationFilter);
  8902. }
  8903. // Status filter
  8904. if (statusFilter !== 'all') {
  8905. result = result.filter(p => {
  8906. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8907. if (!status?.connected) return statusFilter === 'offline';
  8908. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8909. switch (statusFilter) {
  8910. case 'printing': return status.state === 'RUNNING';
  8911. case 'paused': return status.state === 'PAUSE';
  8912. case 'finished': return status.state === 'FINISH';
  8913. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8914. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8915. case 'offline': return false; // Connected printers are never offline
  8916. default: return true;
  8917. }
  8918. });
  8919. }
  8920. return result;
  8921. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8922. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8923. // Derive unique locations for the location filter dropdown
  8924. const availableLocations = useMemo(() => {
  8925. if (!printers) return [];
  8926. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8927. }, [printers]);
  8928. // A saved location can outlive what it matched -- renamed, cleared, or the
  8929. // only printer that had it deleted. The dropdown is rendered only while some
  8930. // printer has a location, so a stale one would hide every printer *and* the
  8931. // control to undo it, leaving an empty page and no way back (#2833).
  8932. // Deliberately waits for `printers`: it is undefined while the query is in
  8933. // flight, and acting on the empty list that produces would throw the saved
  8934. // filter away every time the page loads.
  8935. useEffect(() => {
  8936. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8937. setLocationFilter('all');
  8938. localStorage.setItem('printerLocationFilter', 'all');
  8939. }, [printers, availableLocations, locationFilter]);
  8940. // Sort printers based on selected option
  8941. const sortedPrinters = useMemo(() => {
  8942. const sorted = [...filteredPrinters];
  8943. switch (sortBy) {
  8944. case 'name':
  8945. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8946. break;
  8947. case 'model':
  8948. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8949. break;
  8950. case 'location':
  8951. // Sort by location, with ungrouped printers last
  8952. sorted.sort((a, b) => {
  8953. const locA = a.location || '';
  8954. const locB = b.location || '';
  8955. if (!locA && locB) return 1;
  8956. if (locA && !locB) return -1;
  8957. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  8958. });
  8959. break;
  8960. case 'status':
  8961. // Sort by status: HMS errors > printing > idle > offline
  8962. sorted.sort((a, b) => {
  8963. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  8964. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  8965. const getPriority = (s: typeof statusA) => {
  8966. if (!s?.connected) return 3; // offline
  8967. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  8968. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  8969. if (s.state === 'RUNNING') return 1; // printing
  8970. return 2; // idle
  8971. };
  8972. return getPriority(statusA) - getPriority(statusB);
  8973. });
  8974. break;
  8975. case 'eta':
  8976. sorted.sort((a, b) => {
  8977. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8978. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8979. const tier = (s: typeof statusA) => {
  8980. if (!s?.connected) return 3; // offline last
  8981. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8982. if (s.state === 'RUNNING') return 1; // printing without ETA
  8983. return 2; // idle
  8984. };
  8985. const ta = tier(statusA);
  8986. const tb = tier(statusB);
  8987. if (ta !== tb) return ta - tb;
  8988. if (ta === 0) {
  8989. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8990. if (diff !== 0) return diff;
  8991. }
  8992. return a.name.localeCompare(b.name);
  8993. });
  8994. break;
  8995. }
  8996. // Apply ascending/descending
  8997. if (!sortAsc) {
  8998. sorted.reverse();
  8999. }
  9000. return sorted;
  9001. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  9002. const selectAll = useCallback(() => {
  9003. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  9004. setIsSelectionMode(true);
  9005. }, [sortedPrinters]);
  9006. const selectByState = useCallback((state: PrinterState) => {
  9007. setSelectedPrinterIds(prev => {
  9008. const next = new Set(prev);
  9009. sortedPrinters.forEach(p => {
  9010. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  9011. if (classifyPrinterStatus(status) === state) next.add(p.id);
  9012. });
  9013. return next;
  9014. });
  9015. setIsSelectionMode(true);
  9016. }, [sortedPrinters, queryClient]);
  9017. const selectByLocation = useCallback((location: string) => {
  9018. setSelectedPrinterIds(prev => {
  9019. const next = new Set(prev);
  9020. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9021. return next;
  9022. });
  9023. setIsSelectionMode(true);
  9024. }, [sortedPrinters]);
  9025. const selectByModel = useCallback((model: string) => {
  9026. setSelectedPrinterIds(prev => {
  9027. const next = new Set(prev);
  9028. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9029. return next;
  9030. });
  9031. setIsSelectionMode(true);
  9032. }, [sortedPrinters]);
  9033. const toggleSectionCollapse = useCallback((key: string) => {
  9034. setCollapsedSections(prev => {
  9035. const next = { ...prev, [key]: !prev[key] };
  9036. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9037. return next;
  9038. });
  9039. }, []);
  9040. // Group printers when sorted by location, status, or model
  9041. const groupedPrinters = useMemo(() => {
  9042. if (sortBy === 'name' || sortBy === 'eta') return null;
  9043. const groups: Record<string, typeof sortedPrinters> = {};
  9044. if (sortBy === 'location') {
  9045. sortedPrinters.forEach(printer => {
  9046. const location = printer.location || 'Ungrouped';
  9047. if (!groups[location]) groups[location] = [];
  9048. groups[location].push(printer);
  9049. });
  9050. } else if (sortBy === 'model') {
  9051. sortedPrinters.forEach(printer => {
  9052. const model = printer.model || 'Unknown';
  9053. if (!groups[model]) groups[model] = [];
  9054. groups[model].push(printer);
  9055. });
  9056. } else if (sortBy === 'status') {
  9057. sortedPrinters.forEach(printer => {
  9058. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9059. const group = classifyPrinterStatus(status);
  9060. if (!groups[group]) groups[group] = [];
  9061. groups[group].push(printer);
  9062. });
  9063. }
  9064. return groups;
  9065. // 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
  9066. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9067. const toolbarRef = useRef<HTMLDivElement>(null);
  9068. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9069. const expandedToolbarWidthRef = useRef(0);
  9070. const [compactToolbar, setCompactToolbar] = useState(false);
  9071. const measureToolbar = useCallback(() => {
  9072. const toolbar = toolbarRef.current;
  9073. if (!toolbar) return;
  9074. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9075. if (measuredControlsWidth) {
  9076. expandedToolbarWidthRef.current = measuredControlsWidth;
  9077. }
  9078. const searchMinimumWidth = 220;
  9079. const gapWidth = 8;
  9080. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9081. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9082. }, []);
  9083. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9084. useLayoutEffect(() => {
  9085. measureToolbar();
  9086. const toolbar = toolbarRef.current;
  9087. if (!toolbar) return;
  9088. if (typeof ResizeObserver === 'undefined') {
  9089. window.addEventListener('resize', measureToolbar);
  9090. return () => window.removeEventListener('resize', measureToolbar);
  9091. }
  9092. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9093. resizeObserver.observe(toolbar);
  9094. window.addEventListener('resize', measureToolbar);
  9095. return () => {
  9096. resizeObserver.disconnect();
  9097. window.removeEventListener('resize', measureToolbar);
  9098. };
  9099. }, [
  9100. measureToolbar,
  9101. printers?.length,
  9102. availableLocations.length,
  9103. hideDisconnected,
  9104. smartPlugCount,
  9105. ]);
  9106. const renderFilterControls = (inMenu = false) => (
  9107. <>
  9108. {/* Status filter */}
  9109. {printers && printers.length > 0 && (
  9110. <ToolbarDropdown
  9111. value={statusFilter}
  9112. onChange={handleStatusFilterChange}
  9113. fullWidth={inMenu}
  9114. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9115. />
  9116. )}
  9117. {/* Location filter — only shown when at least one printer has a location */}
  9118. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9119. <ToolbarDropdown
  9120. value={locationFilter}
  9121. onChange={handleLocationFilterChange}
  9122. fullWidth={inMenu}
  9123. options={[
  9124. { value: 'all', label: t('printers.filter.allLocations') },
  9125. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9126. ]}
  9127. />
  9128. )}
  9129. <button
  9130. type="button"
  9131. onClick={toggleHideDisconnected}
  9132. aria-pressed={hideDisconnected}
  9133. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9134. hideDisconnected
  9135. ? 'bg-bambu-green border-bambu-green text-white'
  9136. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9137. }`}
  9138. >
  9139. {t('printers.hideOffline')}
  9140. </button>
  9141. </>
  9142. );
  9143. const renderViewControls = (inMenu = false) => (
  9144. <>
  9145. {/* Sort dropdown */}
  9146. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9147. <ToolbarDropdown<SortOption>
  9148. value={sortBy}
  9149. onChange={handleSortChange}
  9150. fullWidth={inMenu}
  9151. options={[
  9152. { value: 'name', label: t('printers.sort.name') },
  9153. { value: 'status', label: t('printers.sort.status') },
  9154. { value: 'model', label: t('printers.sort.model') },
  9155. { value: 'location', label: t('printers.sort.location') },
  9156. { value: 'eta', label: t('printers.sort.eta') },
  9157. ]}
  9158. />
  9159. <button
  9160. onClick={toggleSortDirection}
  9161. 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"
  9162. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9163. >
  9164. {sortAsc ? (
  9165. <ArrowUp className="w-4 h-4 text-white" />
  9166. ) : (
  9167. <ArrowDown className="w-4 h-4 text-white" />
  9168. )}
  9169. </button>
  9170. </div>
  9171. {/* Page view toggle: Cards / Cam Wall */}
  9172. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9173. <button
  9174. type="button"
  9175. onClick={() => {
  9176. setPageView('cards');
  9177. localStorage.setItem('printerPageView', 'cards');
  9178. }}
  9179. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9180. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9181. }`}
  9182. title={t('printers.pageView.cards')}
  9183. aria-pressed={pageView === 'cards'}
  9184. >
  9185. <LayoutGrid className="w-3.5 h-3.5" />
  9186. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9187. </button>
  9188. <button
  9189. type="button"
  9190. onClick={() => {
  9191. setPageView('camwall');
  9192. localStorage.setItem('printerPageView', 'camwall');
  9193. }}
  9194. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9195. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9196. }`}
  9197. title={t('printers.pageView.camWall')}
  9198. aria-pressed={pageView === 'camwall'}
  9199. disabled={!hasPermission('camera:view')}
  9200. >
  9201. <MonitorPlay className="w-3.5 h-3.5" />
  9202. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9203. </button>
  9204. </div>
  9205. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9206. view, and the page a kiosk token points at. Only offered once the wall
  9207. is the active view, so it doesn't compete with the toggle above. */}
  9208. {pageView === 'camwall' && hasPermission('camera:view') && (
  9209. <RouterLink
  9210. to="/camwall"
  9211. 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' : ''}`}
  9212. title={t('printers.pageView.openCamWallPage')}
  9213. >
  9214. <ExternalLink className="w-3.5 h-3.5" />
  9215. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9216. </RouterLink>
  9217. )}
  9218. {/* Card size selector */}
  9219. <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' : ''}`}>
  9220. {cardSizeLabels.map((label, index) => {
  9221. const size = index + 1;
  9222. const isSelected = cardSize === size;
  9223. return (
  9224. <button
  9225. key={label}
  9226. onClick={() => {
  9227. setCompactDrilldownPrinterId(null);
  9228. setCardSize(size);
  9229. localStorage.setItem('printerCardSize', String(size));
  9230. }}
  9231. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9232. index === 0 ? 'rounded-l-lg' : ''
  9233. } ${
  9234. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9235. } ${
  9236. isSelected
  9237. ? 'bg-bambu-green text-white'
  9238. : 'text-white hover:bg-bambu-dark-tertiary'
  9239. }`}
  9240. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  9241. >
  9242. {label}
  9243. </button>
  9244. );
  9245. })}
  9246. </div>
  9247. </>
  9248. );
  9249. const renderActionControls = (inMenu = false) => (
  9250. <>
  9251. {/* Bulk select toggle */}
  9252. <button
  9253. onClick={() => {
  9254. if (selectionMode) clearSelection();
  9255. else setIsSelectionMode(true);
  9256. }}
  9257. 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' : ''} ${
  9258. selectionMode
  9259. ? 'bg-bambu-green border-bambu-green text-white'
  9260. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9261. }`}
  9262. title={t('printers.bulk.select')}
  9263. disabled={!hasPermission('printers:control')}
  9264. >
  9265. <CheckSquare className="w-4 h-4" />
  9266. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9267. </button>
  9268. {/* Power dropdown for offline printers with smart plugs */}
  9269. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9270. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9271. <button
  9272. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9273. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9274. inMenu
  9275. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9276. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9277. }`}
  9278. >
  9279. <span className="flex items-center gap-1.5">
  9280. <Power className="w-4 h-4" />
  9281. {t('printers.powerOn')}
  9282. </span>
  9283. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9284. </button>
  9285. {showPowerDropdown && (
  9286. <>
  9287. {/* Backdrop to close dropdown */}
  9288. <div
  9289. className="fixed inset-0 z-10"
  9290. onClick={() => setShowPowerDropdown(false)}
  9291. />
  9292. <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">
  9293. <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">
  9294. {t('printers.offlinePrintersWithPlugs')}
  9295. </div>
  9296. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9297. <PowerDropdownItem
  9298. key={printer.id}
  9299. printer={printer}
  9300. plug={smartPlugByPrinter[printer.id]}
  9301. onPowerOn={(plugId) => {
  9302. setPoweringOn(plugId);
  9303. powerOnMutation.mutate(plugId);
  9304. }}
  9305. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9306. />
  9307. ))}
  9308. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9309. <div className="px-3 py-2 text-sm text-bambu-gray">
  9310. No printers with smart plugs
  9311. </div>
  9312. )}
  9313. </div>
  9314. </>
  9315. )}
  9316. </div>
  9317. )}
  9318. <Button
  9319. onClick={() => setShowAddModal(true)}
  9320. disabled={!hasPermission('printers:create')}
  9321. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9322. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9323. >
  9324. <Plus className="w-4 h-4" />
  9325. {t('printers.addPrinter')}
  9326. </Button>
  9327. </>
  9328. );
  9329. return (
  9330. <div className="p-4 md:p-8">
  9331. <div className="space-y-3 mb-6">
  9332. <div>
  9333. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9334. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9335. {t('printers.title')}
  9336. </h1>
  9337. <StatusSummaryBar printers={printers} />
  9338. </div>
  9339. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9340. {/* Only show search bar when printers exist */}
  9341. {printers && printers.length > 0 && (
  9342. <div className="relative min-w-0 flex-1">
  9343. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9344. <input
  9345. type="search"
  9346. name="printer-search"
  9347. autoComplete="off"
  9348. data-1p-ignore
  9349. data-lpignore="true"
  9350. value={search}
  9351. onChange={(e) => setSearch(e.target.value)}
  9352. placeholder={t('printers.search')}
  9353. aria-label={t('printers.search')}
  9354. 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"
  9355. />
  9356. {search && (
  9357. <button
  9358. type="button"
  9359. aria-label={t('common.clear')}
  9360. onClick={() => setSearch('')}
  9361. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9362. >
  9363. <X className="w-4 h-4" />
  9364. </button>
  9365. )}
  9366. </div>
  9367. )}
  9368. <div
  9369. ref={expandedToolbarControlsRef}
  9370. aria-hidden={compactToolbar}
  9371. inert={compactToolbar}
  9372. 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`}
  9373. >
  9374. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9375. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9376. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9377. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9378. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9379. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9380. </div>
  9381. {compactToolbar && (
  9382. <div className="ml-auto flex items-center justify-end gap-1">
  9383. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9384. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9385. </ToolbarMenu>
  9386. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9387. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9388. </ToolbarMenu>
  9389. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9390. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9391. </ToolbarMenu>
  9392. </div>
  9393. )}
  9394. </div>
  9395. </div>
  9396. {isLoading ? (
  9397. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9398. ) : printers?.length === 0 ? (
  9399. <Card>
  9400. <CardContent className="text-center py-12">
  9401. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9402. <Button
  9403. onClick={() => setShowAddModal(true)}
  9404. disabled={!hasPermission('printers:create')}
  9405. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9406. >
  9407. <Plus className="w-4 h-4" />
  9408. {t('printers.addPrinter')}
  9409. </Button>
  9410. </CardContent>
  9411. </Card>
  9412. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9413. <Card>
  9414. <CardContent className="text-center py-12">
  9415. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9416. </CardContent>
  9417. </Card>
  9418. ) : pageView === 'camwall' ? (
  9419. <CameraWall
  9420. printers={sortedPrinters}
  9421. maxLive={camWallMaxLive}
  9422. snapshotIntervalSec={camWallSnapshotSec}
  9423. onTileClick={(id, name) => {
  9424. // A wall tile has no room for a split button, so it follows the
  9425. // mode the card buttons last chose.
  9426. if (cameraViewMode === 'embedded') {
  9427. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9428. } else {
  9429. openCameraWindow(id);
  9430. }
  9431. }}
  9432. statusMode={camWallStatusMode}
  9433. onChangeMaxLive={(next) => {
  9434. setCamWallMaxLive(next);
  9435. localStorage.setItem('camWallMaxLive', String(next));
  9436. }}
  9437. onChangeSnapshotIntervalSec={(next) => {
  9438. setCamWallSnapshotSec(next);
  9439. localStorage.setItem('camWallSnapshotSec', String(next));
  9440. }}
  9441. onChangeStatusMode={(next) => {
  9442. setCamWallStatusMode(next);
  9443. localStorage.setItem('camWallStatusMode', next);
  9444. }}
  9445. />
  9446. ) : groupedPrinters ? (
  9447. /* Grouped view (location, status, or model) */
  9448. <div className="space-y-6">
  9449. {(() => {
  9450. const keys = sortBy === 'status'
  9451. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9452. : Object.keys(groupedPrinters);
  9453. // For status grouping, asc/desc flips the fixed priority order
  9454. // (asc = error→offline, desc = offline→error). This matches the
  9455. // sort-toggle behaviour for other groupings.
  9456. return (sortAsc ? keys : [...keys].reverse());
  9457. })().map((groupKey) => {
  9458. const groupPrinters = groupedPrinters[groupKey];
  9459. const collapseKey = `${sortBy}:${groupKey}`;
  9460. const isOpen = !collapsedSections[collapseKey];
  9461. const dot = sortBy === 'status'
  9462. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9463. : 'bg-bambu-green';
  9464. const label = sortBy === 'status'
  9465. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9466. : groupKey;
  9467. return (
  9468. <Collapsible
  9469. key={groupKey}
  9470. open={isOpen}
  9471. onToggle={() => toggleSectionCollapse(collapseKey)}
  9472. summaryClassName="py-1"
  9473. summary={
  9474. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9475. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9476. {label}
  9477. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9478. {selectionMode && (
  9479. <button
  9480. onClick={(e) => {
  9481. e.stopPropagation();
  9482. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9483. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9484. else if (sortBy === 'model') selectByModel(groupKey);
  9485. }}
  9486. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9487. >
  9488. {t('printers.bulk.selectAll')}
  9489. </button>
  9490. )}
  9491. </h2>
  9492. }
  9493. >
  9494. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9495. {groupPrinters.map((printer) => (
  9496. <PrinterCard
  9497. key={printer.id}
  9498. printer={printer}
  9499. hideIfDisconnected={hideDisconnected}
  9500. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9501. viewMode={viewMode}
  9502. cardSize={cardSize}
  9503. amsThresholds={settings ? {
  9504. humidityGood: Number(settings.ams_humidity_good) || 40,
  9505. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9506. tempGood: Number(settings.ams_temp_good) || 28,
  9507. tempFair: Number(settings.ams_temp_fair) || 35,
  9508. } : undefined}
  9509. spoolmanEnabled={spoolmanEnabled}
  9510. hasUnlinkedSpools={hasUnlinkedSpools}
  9511. linkedSpools={linkedSpools}
  9512. spoolmanUrl={spoolmanStatus?.url}
  9513. spoolmanSyncMode={spoolmanSyncMode}
  9514. onGetAssignment={getAssignment}
  9515. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9516. spoolmanSpools={spoolmanSpools}
  9517. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9518. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9519. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9520. timeFormat={settings?.time_format || 'system'}
  9521. cameraViewMode={cameraViewMode}
  9522. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9523. onSelectCameraViewMode={selectCameraViewMode}
  9524. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9525. dryingPresets={effectiveDryingPresets}
  9526. nozzleTempPresets={effectiveNozzleTempPresets}
  9527. bedTempPresets={effectiveBedTempPresets}
  9528. chamberTempPresets={effectiveChamberTempPresets}
  9529. fanSpeedPresets={effectiveFanSpeedPresets}
  9530. requirePlateClear={settings?.require_plate_clear === true}
  9531. selectionMode={selectionMode}
  9532. isSelected={selectedPrinterIds.has(printer.id)}
  9533. onToggleSelect={toggleSelect}
  9534. onOpenCompactCard={openCompactCard}
  9535. aiDetectionEnabled={isAiMonitored(printer.id)}
  9536. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9537. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9538. />
  9539. ))}
  9540. </div>
  9541. </Collapsible>
  9542. );
  9543. })}
  9544. </div>
  9545. ) : (
  9546. /* Regular grid view */
  9547. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9548. {sortedPrinters.map((printer) => (
  9549. <PrinterCard
  9550. key={printer.id}
  9551. printer={printer}
  9552. hideIfDisconnected={hideDisconnected}
  9553. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9554. viewMode={viewMode}
  9555. cardSize={cardSize}
  9556. spoolmanEnabled={spoolmanEnabled}
  9557. hasUnlinkedSpools={hasUnlinkedSpools}
  9558. linkedSpools={linkedSpools}
  9559. spoolmanUrl={spoolmanStatus?.url}
  9560. spoolmanSyncMode={spoolmanSyncMode}
  9561. onGetAssignment={getAssignment}
  9562. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9563. spoolmanSpools={spoolmanSpools}
  9564. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9565. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9566. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9567. amsThresholds={settings ? {
  9568. humidityGood: Number(settings.ams_humidity_good) || 40,
  9569. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9570. tempGood: Number(settings.ams_temp_good) || 28,
  9571. tempFair: Number(settings.ams_temp_fair) || 35,
  9572. } : undefined}
  9573. timeFormat={settings?.time_format || 'system'}
  9574. cameraViewMode={cameraViewMode}
  9575. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9576. onSelectCameraViewMode={selectCameraViewMode}
  9577. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9578. dryingPresets={effectiveDryingPresets}
  9579. nozzleTempPresets={effectiveNozzleTempPresets}
  9580. bedTempPresets={effectiveBedTempPresets}
  9581. chamberTempPresets={effectiveChamberTempPresets}
  9582. fanSpeedPresets={effectiveFanSpeedPresets}
  9583. requirePlateClear={settings?.require_plate_clear === true}
  9584. selectionMode={selectionMode}
  9585. isSelected={selectedPrinterIds.has(printer.id)}
  9586. onToggleSelect={toggleSelect}
  9587. onOpenCompactCard={openCompactCard}
  9588. aiDetectionEnabled={isAiMonitored(printer.id)}
  9589. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9590. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9591. />
  9592. ))}
  9593. </div>
  9594. )}
  9595. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9596. <button
  9597. type="button"
  9598. onClick={returnToCompactCards}
  9599. 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}`}
  9600. title={t('common.back', 'Back')}
  9601. >
  9602. <ArrowLeft className="w-4 h-4" />
  9603. {t('common.back', 'Back')}
  9604. </button>
  9605. )}
  9606. {showAddModal && (
  9607. <AddPrinterModal
  9608. onClose={() => setShowAddModal(false)}
  9609. onAdd={(data) => addMutation.mutate(data)}
  9610. existingSerials={printers?.map(p => p.serial_number) || []}
  9611. />
  9612. )}
  9613. {/* Bulk selection toolbar */}
  9614. {selectionMode && printers && (
  9615. <BulkPrinterToolbar
  9616. selectedIds={selectedPrinterIds}
  9617. printers={printers}
  9618. onClose={clearSelection}
  9619. onSelectAll={selectAll}
  9620. onSelectByLocation={selectByLocation}
  9621. onSelectByState={selectByState}
  9622. onAction={handleBulkAction}
  9623. actionPending={bulkActionPending}
  9624. />
  9625. )}
  9626. {/* Bulk action confirmation modals */}
  9627. {bulkConfirmAction === 'stop' && (
  9628. <ConfirmModal
  9629. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9630. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9631. confirmText={t('printers.bulk.confirm.stopButton')}
  9632. variant="danger"
  9633. isLoading={bulkActionPending}
  9634. onConfirm={() => executeBulkAction('stop')}
  9635. onCancel={() => setBulkConfirmAction(null)}
  9636. />
  9637. )}
  9638. {bulkConfirmAction === 'pause' && (
  9639. <ConfirmModal
  9640. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9641. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9642. confirmText={t('printers.bulk.confirm.pauseButton')}
  9643. isLoading={bulkActionPending}
  9644. onConfirm={() => executeBulkAction('pause')}
  9645. onCancel={() => setBulkConfirmAction(null)}
  9646. />
  9647. )}
  9648. {bulkConfirmAction === 'clearPlate' && (
  9649. <ConfirmModal
  9650. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9651. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9652. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9653. isLoading={bulkActionPending}
  9654. onConfirm={() => executeBulkAction('clearPlate')}
  9655. onCancel={() => setBulkConfirmAction(null)}
  9656. />
  9657. )}
  9658. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9659. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9660. <EmbeddedCameraViewer
  9661. key={camera.id}
  9662. printerId={camera.id}
  9663. printerName={camera.name}
  9664. viewerIndex={index}
  9665. onClose={() => setEmbeddedCameraPrinters(prev => {
  9666. const next = new Map(prev);
  9667. next.delete(camera.id);
  9668. return next;
  9669. })}
  9670. />
  9671. ))}
  9672. </div>
  9673. );
  9674. }