PrintersPage.tsx 493 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { formatPrintName } from '../utils/printName';
  5. import { isBedSlinger } from '../utils/bedSlinger';
  6. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  7. import {
  8. openCameraWindow,
  9. readStoredCameraViewMode,
  10. storeCameraViewMode,
  11. type CameraViewMode,
  12. } from '../utils/camera';
  13. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  14. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  15. import {
  16. isExternalSpoolHidden,
  17. setExternalSpoolHidden as persistExternalSpoolHidden,
  18. } from '../utils/printerCardPrefs';
  19. import {
  20. BED_TEMP_DEFAULTS,
  21. CHAMBER_TEMP_DEFAULTS,
  22. FAN_SPEED_DEFAULTS,
  23. NOZZLE_TEMP_DEFAULTS,
  24. buildPresetOptions,
  25. parsePresetTriple,
  26. } from '../utils/temperatureFanPresets';
  27. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  28. // covers header + filament select + temp slider + duration + rotate-tray
  29. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  30. // earlier); under-estimating leaves the popover clipped off the bottom (the
  31. // original bug at #1447).
  32. const DRYING_POPOVER_WIDTH = 240;
  33. // Height in "now" mode plus the tallest start-mode control; a conservative
  34. // over-estimate just flips the popover above the trigger sooner.
  35. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  36. // Delay presets for the "After delay" drying start mode, in minutes.
  37. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  38. // Every printer card reads the same fleet-wide scheduled-drying list.
  39. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  40. // Why a due run has not started yet: every waiting_reason the scheduler can
  41. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  42. // for ..." with no hint why nothing is happening.
  43. const WAITING_REASON_KEYS: Record<string, string> = {
  44. ams_power_required: 'printers.drying.powerRequired',
  45. ams_retract_filament: 'printers.drying.retractFilament',
  46. ams_blocked: 'printers.drying.cannotDryNow',
  47. ams_not_found: 'printers.drying.waitingAmsNotFound',
  48. printer_offline: 'printers.drying.waitingOffline',
  49. printer_busy: 'printers.drying.waitingPrinterBusy',
  50. already_drying: 'printers.drying.waitingAlreadyDrying',
  51. interrupted: 'printers.drying.waitingInterrupted',
  52. };
  53. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  54. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  55. }
  56. // Which cannot-dry code to name when the firmware reports several at once.
  57. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  58. // button's tooltip and a scheduled row's waiting reason describe one blocked
  59. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  60. // left at the outlet, and both need the user to go and do something. The rest
  61. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  62. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  63. const codes = (reasons ?? []).map(r => Number(r));
  64. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  65. if (codes.includes(3)) return 'printers.drying.retractFilament';
  66. return 'printers.drying.cannotDryNow';
  67. }
  68. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  69. import { useTranslation } from 'react-i18next';
  70. import { useTheme } from '../contexts/ThemeContext';
  71. import { useAuth } from '../contexts/AuthContext';
  72. import {
  73. Plus,
  74. Link,
  75. Unlink,
  76. Signal,
  77. Clock,
  78. MoreVertical,
  79. Trash2,
  80. RefreshCw,
  81. RotateCw,
  82. Box,
  83. HardDrive,
  84. AlertTriangle,
  85. AlertCircle,
  86. Terminal,
  87. Power,
  88. Zap,
  89. Wrench,
  90. ChevronDown,
  91. Eye,
  92. EyeOff,
  93. Filter,
  94. Pencil,
  95. ArrowLeft,
  96. ArrowRight,
  97. ArrowUp,
  98. ArrowDown,
  99. Layers,
  100. Video,
  101. Search,
  102. Loader2,
  103. Square,
  104. Pause,
  105. Play,
  106. X,
  107. Fan,
  108. Wind,
  109. AirVent,
  110. Download,
  111. ScanSearch,
  112. CheckCircle,
  113. CheckSquare,
  114. XCircle,
  115. User,
  116. Home,
  117. Printer as PrinterIcon,
  118. Info,
  119. Cable,
  120. Flame,
  121. Repeat,
  122. Snowflake,
  123. Gauge,
  124. DoorOpen,
  125. DoorClosed,
  126. Move,
  127. LogIn,
  128. LogOut,
  129. MoreHorizontal,
  130. SlidersHorizontal,
  131. Stethoscope,
  132. ScanEye,
  133. LineChart as LineChartIcon,
  134. LayoutGrid,
  135. MonitorPlay,
  136. ExternalLink,
  137. PictureInPicture2,
  138. ThumbsUp,
  139. ThumbsDown,
  140. } from 'lucide-react';
  141. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  142. // Aliased: lucide-react already exports a `Link` icon into this module.
  143. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  144. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  145. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  146. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  147. import { Card, CardContent } from '../components/Card';
  148. import { Button } from '../components/Button';
  149. import { ConfirmModal } from '../components/ConfirmModal';
  150. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  151. import { FileManagerModal } from '../components/FileManagerModal';
  152. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  153. import { CameraWall } from '../components/CameraWall';
  154. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  155. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  156. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  157. import { AiDetectionModal } from '../components/AiDetectionModal';
  158. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  159. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  160. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  161. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  162. import { AmsBackupModal } from '../components/AmsBackupModal';
  163. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  164. import type { HeaterSensorKind } from '../api/client';
  165. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  166. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  167. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  168. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  169. import { useToast } from '../contexts/ToastContext';
  170. import { ChamberLight } from '../components/icons/ChamberLight';
  171. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  172. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  173. import { FileUploadModal } from '../components/FileUploadModal';
  174. import { PrintModal } from '../components/PrintModal';
  175. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  176. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  177. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  178. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  179. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  180. import { Collapsible } from '../components/Collapsible';
  181. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  182. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  183. // The status filter's options, and the only values it may hold. One list so a
  184. // saved filter cannot be validated against a set the dropdown has since moved
  185. // on from (#2833). Labels stay literal so they remain greppable.
  186. const STATUS_FILTER_OPTIONS = [
  187. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  188. { value: 'printing', labelKey: 'printers.status.printing' },
  189. { value: 'paused', labelKey: 'printers.status.paused' },
  190. { value: 'idle', labelKey: 'printers.status.idle' },
  191. { value: 'finished', labelKey: 'printers.status.finished' },
  192. { value: 'error', labelKey: 'printers.status.error' },
  193. { value: 'offline', labelKey: 'printers.status.offline' },
  194. ] as const;
  195. function isKnownStatusFilter(value: string | null): boolean {
  196. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  197. }
  198. export interface SpoolmanSlotAssignmentRow {
  199. printer_id: number;
  200. ams_id: number;
  201. tray_id: number;
  202. spoolman_spool_id: number;
  203. }
  204. // Color names resolve via getColorName() which reads the backend color_catalog
  205. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  206. // Format K value with 3 decimal places, default to 0.020 if null
  207. function formatKValue(k: number | null | undefined): string {
  208. const value = k ?? 0.020;
  209. return value.toFixed(3);
  210. }
  211. // K-profile value shown on the slot card itself (#2532) rather than only inside
  212. // the hover popup, the way BambuStudio shows it per slot.
  213. //
  214. // `k` arrives already gated on the slot being loaded; falsy means the printer
  215. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  216. // missing value, which is captioned inside the hover card but would read as a
  217. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  218. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  219. // reported 0 makes that expression evaluate to the number 0, and React renders
  220. // numbers, putting a bare "0" under the material name.
  221. //
  222. // `reserve` holds the row's height open on the slots without a value whenever
  223. // some other slot on the same card has one, so every fill bar stays on one line.
  224. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  225. const { t } = useTranslation();
  226. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  227. if (!k) {
  228. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  229. }
  230. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  231. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  232. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  233. // family per browser and so measured differently in Safari.
  234. return (
  235. <div className={className} title={t('ams.kFactor')}>
  236. {t('ams.kFactorShort')} {formatKValue(k)}
  237. </div>
  238. );
  239. }
  240. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  241. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  242. const { mode } = useTheme();
  243. const { t } = useTranslation();
  244. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  245. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  246. return (
  247. <span
  248. 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"
  249. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  250. title={side === 'L' ? t('common.left') : t('common.right')}
  251. >
  252. {side}
  253. </span>
  254. );
  255. }
  256. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  257. // deliberately a different colour, because it means something different: this
  258. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  259. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  260. const { mode } = useTheme();
  261. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  262. return (
  263. <span
  264. 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"
  265. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  266. title={title}
  267. >
  268. {FTS_INLET_SIDE[inlet]}
  269. </span>
  270. );
  271. }
  272. /**
  273. * Which side indicator, if any, belongs on an AMS card header.
  274. *
  275. * Three sources, in descending authority:
  276. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  277. * through the switch, so the inlet is the only meaningful label.
  278. * 2. A real extruder id from ams_extruder_map.
  279. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  280. * never reported a map. This one is only a guess, and it is suppressed
  281. * when a switch is installed: with an FTS every unit reports extruder
  282. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  283. * nothing but their unit numbers.
  284. */
  285. function amsSideBadge(
  286. amsId: number,
  287. amsExtruderMap: Record<string, number>,
  288. amsSwitchInlet: Record<string, 'A' | 'B'>,
  289. ftsInstalled: boolean
  290. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  291. const inlet = amsSwitchInlet[String(amsId)];
  292. if (inlet) return { kind: 'inlet', inlet };
  293. const mapped = amsExtruderMap[String(amsId)];
  294. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  295. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  296. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  297. return null;
  298. }
  299. // Expand nozzle type codes to material names
  300. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  301. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  302. function nozzleTypeName(type: string, t: (key: string) => string): string {
  303. if (!type) return '';
  304. // Full text names (from main nozzle info)
  305. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  306. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  307. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  308. // 4-char codes (e.g. "HS01"): last 2 digits = material
  309. if (type.length >= 4) {
  310. const material = type.slice(2, 4);
  311. if (material === '00') return t('printers.nozzleStainlessSteel');
  312. if (material === '01') return t('printers.nozzleHardenedSteel');
  313. if (material === '05') return t('printers.nozzleTungstenCarbide');
  314. }
  315. // 2-digit numeric codes
  316. if (type === '00') return t('printers.nozzleStainlessSteel');
  317. if (type === '01') return t('printers.nozzleHardenedSteel');
  318. if (type === '05') return t('printers.nozzleTungstenCarbide');
  319. // 2-char alpha codes: H prefix = hardened steel
  320. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  321. return type;
  322. }
  323. // Parse flow type from nozzle type code
  324. // HH = high flow, HS = standard/normal
  325. function nozzleFlowName(type: string, t: (key: string) => string): string {
  326. if (!type) return '';
  327. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  328. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  329. return '';
  330. }
  331. // Per-slot hover card for nozzle rack
  332. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  333. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  334. slot: import('../api/client').NozzleRackSlot;
  335. index: number;
  336. activeStatus?: boolean;
  337. filamentName?: string;
  338. children: React.ReactNode;
  339. }) {
  340. const { t } = useTranslation();
  341. const [isVisible, setIsVisible] = useState(false);
  342. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  343. const triggerRef = useRef<HTMLDivElement>(null);
  344. const cardRef = useRef<HTMLDivElement>(null);
  345. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  346. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  347. const isMounted = slot.stat === 1;
  348. useEffect(() => {
  349. if (isVisible && triggerRef.current && cardRef.current) {
  350. const triggerRect = triggerRef.current.getBoundingClientRect();
  351. const cardHeight = cardRef.current.offsetHeight;
  352. const headerHeight = 56;
  353. const spaceAbove = triggerRect.top - headerHeight;
  354. const spaceBelow = window.innerHeight - triggerRect.bottom;
  355. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  356. setPosition('bottom');
  357. } else {
  358. setPosition('top');
  359. }
  360. }
  361. }, [isVisible]);
  362. const handleMouseEnter = () => {
  363. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  364. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  365. };
  366. const handleMouseLeave = () => {
  367. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  368. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  369. };
  370. useEffect(() => {
  371. return () => {
  372. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  373. };
  374. }, []);
  375. const filamentCss = parseFilamentColor(slot.filament_color);
  376. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  377. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  378. return (
  379. <div
  380. ref={triggerRef}
  381. className="relative"
  382. onMouseEnter={handleMouseEnter}
  383. onMouseLeave={handleMouseLeave}
  384. >
  385. {children}
  386. {isVisible && (
  387. <div
  388. ref={cardRef}
  389. className={`
  390. absolute left-1/2 -translate-x-1/2 z-50
  391. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  392. animate-in fade-in-0 zoom-in-95 duration-150
  393. `}
  394. style={{ maxWidth: 'calc(100vw - 24px)' }}
  395. >
  396. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  397. {isEmpty ? (
  398. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  399. Slot {index + 1} — Empty
  400. </div>
  401. ) : (
  402. <div className="p-2.5 space-y-1.5">
  403. {/* Diameter */}
  404. <div className="flex items-center justify-between">
  405. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  406. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  407. </div>
  408. {/* Type */}
  409. {typeFull && (
  410. <div className="flex items-center justify-between">
  411. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  412. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  413. </div>
  414. )}
  415. {/* Flow (hide if empty) */}
  416. {flowFull && (
  417. <div className="flex items-center justify-between">
  418. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  419. <span className="text-xs text-white font-semibold">{flowFull}</span>
  420. </div>
  421. )}
  422. {/* Status badge */}
  423. <div className="flex items-center justify-between">
  424. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  425. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  426. activeStatus || isMounted
  427. ? 'bg-green-900/50 text-green-400'
  428. : 'bg-bambu-dark-tertiary text-bambu-gray'
  429. }`}>
  430. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  431. </span>
  432. </div>
  433. {/* Wear (hide if null) */}
  434. {slot.wear != null && (
  435. <div className="flex items-center justify-between">
  436. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  437. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  438. </div>
  439. )}
  440. {/* Max Temp (hide if 0) */}
  441. {slot.max_temp > 0 && (
  442. <div className="flex items-center justify-between">
  443. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  444. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  445. </div>
  446. )}
  447. {/* Serial (hide if empty) */}
  448. {slot.serial_number && (
  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.nozzleSerial')}</span>
  451. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  452. </div>
  453. )}
  454. {/* Filament: material type + color swatch (hide if no color) */}
  455. {(filamentCss || slot.filament_type) && (
  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.nozzleFilament')}</span>
  458. <div className="flex items-center gap-1">
  459. {filamentCss && (
  460. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  461. )}
  462. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  463. </div>
  464. </div>
  465. )}
  466. </div>
  467. )}
  468. </div>
  469. {/* Arrow pointer */}
  470. <div
  471. className={`
  472. absolute left-1/2 -translate-x-1/2 w-0 h-0
  473. border-l-[6px] border-l-transparent
  474. border-r-[6px] border-r-transparent
  475. ${position === 'top'
  476. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  477. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  478. `}
  479. />
  480. </div>
  481. )}
  482. </div>
  483. );
  484. }
  485. // Dual-nozzle hover card showing L and R nozzle details side by side
  486. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  487. leftSlot?: import('../api/client').NozzleRackSlot;
  488. rightSlot?: import('../api/client').NozzleRackSlot;
  489. activeNozzle: 'L' | 'R';
  490. filamentInfo?: Record<string, { name: string; k: number | null }>;
  491. children: React.ReactNode;
  492. }) {
  493. const { t } = useTranslation();
  494. const [isVisible, setIsVisible] = useState(false);
  495. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  496. const triggerRef = useRef<HTMLDivElement>(null);
  497. const cardRef = useRef<HTMLDivElement>(null);
  498. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  499. useEffect(() => {
  500. if (isVisible && triggerRef.current && cardRef.current) {
  501. const triggerRect = triggerRef.current.getBoundingClientRect();
  502. const cardHeight = cardRef.current.offsetHeight;
  503. const headerHeight = 56;
  504. const spaceAbove = triggerRect.top - headerHeight;
  505. const spaceBelow = window.innerHeight - triggerRect.bottom;
  506. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  507. setPosition('bottom');
  508. } else {
  509. setPosition('top');
  510. }
  511. }
  512. }, [isVisible]);
  513. const handleMouseEnter = () => {
  514. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  515. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  516. };
  517. const handleMouseLeave = () => {
  518. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  519. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  520. };
  521. useEffect(() => {
  522. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  523. }, []);
  524. if (!leftSlot && !rightSlot) return <>{children}</>;
  525. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  526. const isActive = activeNozzle === side;
  527. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  528. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  529. const filamentCss = parseFilamentColor(slot.filament_color);
  530. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  531. return (
  532. <div className="flex-1 space-y-1.5">
  533. <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'}`}>
  534. {side === 'L' ? t('common.left') : t('common.right')}
  535. </div>
  536. {slot.nozzle_diameter && (
  537. <div className="flex items-center justify-between">
  538. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  539. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  540. </div>
  541. )}
  542. {typeFull && (
  543. <div className="flex items-center justify-between">
  544. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  545. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  546. </div>
  547. )}
  548. {flowFull && (
  549. <div className="flex items-center justify-between">
  550. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  551. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  552. </div>
  553. )}
  554. <div className="flex items-center justify-between">
  555. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  556. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  557. isActive
  558. ? 'bg-green-900/50 text-green-400'
  559. : 'bg-bambu-dark-tertiary text-bambu-gray'
  560. }`}>
  561. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  562. </span>
  563. </div>
  564. {slot.wear != null && (
  565. <div className="flex items-center justify-between">
  566. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  567. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  568. </div>
  569. )}
  570. {/* Serial and max temp only available on the right (removable) nozzle */}
  571. {side === 'R' && slot.max_temp > 0 && (
  572. <div className="flex items-center justify-between">
  573. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  574. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  575. </div>
  576. )}
  577. {side === 'R' && slot.serial_number && (
  578. <div className="flex items-center justify-between">
  579. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  580. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  581. </div>
  582. )}
  583. {(filamentCss || slot.filament_type || slot.filament_id) && (
  584. <div className="flex items-center justify-between">
  585. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  586. <div className="flex items-center gap-1">
  587. {filamentCss && (
  588. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  589. )}
  590. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  591. {filamentName || slot.filament_type || slot.filament_id || ''}
  592. </span>
  593. </div>
  594. </div>
  595. )}
  596. </div>
  597. );
  598. };
  599. return (
  600. <div
  601. ref={triggerRef}
  602. className="relative flex-1"
  603. onMouseEnter={handleMouseEnter}
  604. onMouseLeave={handleMouseLeave}
  605. >
  606. {children}
  607. {isVisible && (
  608. <div
  609. ref={cardRef}
  610. className={`
  611. absolute left-1/2 -translate-x-1/2 z-50
  612. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  613. animate-in fade-in-0 zoom-in-95 duration-150
  614. `}
  615. style={{ maxWidth: 'calc(100vw - 24px)' }}
  616. >
  617. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  618. <div className="p-2.5 flex gap-3">
  619. {leftSlot && renderColumn(leftSlot, 'L')}
  620. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  621. {rightSlot && renderColumn(rightSlot, 'R')}
  622. </div>
  623. </div>
  624. {/* Arrow pointer */}
  625. <div
  626. className={`
  627. absolute left-1/2 -translate-x-1/2 w-0 h-0
  628. border-l-[6px] border-l-transparent
  629. border-r-[6px] border-r-transparent
  630. ${position === 'top'
  631. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  632. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  633. `}
  634. />
  635. </div>
  636. )}
  637. </div>
  638. );
  639. }
  640. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  641. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  642. const { t } = useTranslation();
  643. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  644. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  645. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  646. // base — computing it from min(present IDs) shifts everything left when slot 16
  647. // is the one currently mounted (#943).
  648. const rackNozzles = slots.filter(s => s.id >= 2);
  649. const RACK_SIZE = 6;
  650. const RACK_BASE_ID = 16;
  651. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  652. { length: RACK_SIZE },
  653. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  654. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  655. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  656. },
  657. );
  658. return (
  659. // Sized to its contents rather than growing: the six chips are a fixed
  660. // width at any one card size, so extra width would be dead space taken
  661. // from the temperature cards beside it — which are flex-1 with a 0 basis
  662. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  663. // stays enabled so the card still gives way on a narrow printer card
  664. // instead of overflowing.
  665. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  666. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  667. <div className="flex gap-[3px] justify-center">
  668. {rackSlots.map((slot, i) => {
  669. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  670. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  671. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  672. return (
  673. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  674. <div className="flex flex-col items-center gap-0.5">
  675. <div
  676. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  677. isEmpty
  678. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  679. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  680. }`}
  681. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  682. >
  683. <span
  684. data-rack-diameter
  685. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  686. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  687. >
  688. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  689. </span>
  690. </div>
  691. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  692. acted on without counting chips. Sits below the chip rather
  693. than inside it: the chip is barely wider than its own
  694. diameter text and already carries that over a
  695. filament-coloured background. */}
  696. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  697. {i + 1}
  698. </span>
  699. </div>
  700. </NozzleSlotHoverCard>
  701. );
  702. })}
  703. </div>
  704. </div>
  705. );
  706. }
  707. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  708. function WaterDropEmpty({ className }: { className?: string }) {
  709. return (
  710. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  711. <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"/>
  712. </svg>
  713. );
  714. }
  715. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  716. function WaterDropHalf({ className }: { className?: string }) {
  717. return (
  718. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  719. <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"/>
  720. <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"/>
  721. </svg>
  722. );
  723. }
  724. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  725. function WaterDropFull({ className }: { className?: string }) {
  726. return (
  727. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  728. <path d="M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z" fill="#1F8FEB"/>
  729. <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"/>
  730. </svg>
  731. );
  732. }
  733. // Thermometer SVG - empty outline
  734. function ThermometerEmpty({ className }: { className?: string }) {
  735. return (
  736. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  737. <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"/>
  738. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  739. </svg>
  740. );
  741. }
  742. // Thermometer SVG - half filled (gold - same as humidity fair)
  743. function ThermometerHalf({ className }: { className?: string }) {
  744. return (
  745. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  746. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  747. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  748. <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"/>
  749. </svg>
  750. );
  751. }
  752. // Thermometer SVG - fully filled (red - same as humidity bad)
  753. function ThermometerFull({ className }: { className?: string }) {
  754. return (
  755. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  756. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  757. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  758. <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"/>
  759. </svg>
  760. );
  761. }
  762. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  763. // Added for visual parity with the thermometer icons on the dual-nozzle card
  764. // that previously had no icon at all (#1115, design by @m4rtini2).
  765. function NozzleIcon({ className }: { className?: string }) {
  766. return (
  767. <svg
  768. className={className}
  769. viewBox="0 0 24 24"
  770. fill="none"
  771. xmlns="http://www.w3.org/2000/svg"
  772. stroke="currentColor"
  773. strokeWidth="1.5"
  774. strokeLinecap="round"
  775. strokeLinejoin="round"
  776. >
  777. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  778. <rect x="6" y="11.5" width="12.1" height="3.7" />
  779. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  780. </svg>
  781. );
  782. }
  783. // Heater thermometer icon - filled when heating, outline when off
  784. interface HeaterThermometerProps {
  785. className?: string;
  786. color: string; // The color class (e.g., "text-orange-400")
  787. isHeating: boolean;
  788. }
  789. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  790. // Extract the actual color from Tailwind class for SVG fill
  791. const colorMap: Record<string, string> = {
  792. 'text-orange-400': '#fb923c',
  793. 'text-blue-400': '#60a5fa',
  794. 'text-green-400': '#4ade80',
  795. };
  796. const fillColor = colorMap[color] || '#888';
  797. // Glow style when heating
  798. const glowStyle = isHeating ? {
  799. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  800. } : {};
  801. if (isHeating) {
  802. // Filled thermometer with glow - heater is ON
  803. return (
  804. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  805. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  806. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  807. <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"/>
  808. </svg>
  809. );
  810. }
  811. // Empty thermometer - heater is OFF
  812. return (
  813. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  814. <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"/>
  815. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  816. </svg>
  817. );
  818. }
  819. // AMS Filament Backup tri-state indicator + toggle.
  820. // state=true → ON, click to disable
  821. // state=false → OFF, click opens modal
  822. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  823. interface AmsBackupBadgeProps {
  824. state: boolean | null;
  825. onClick: () => void;
  826. }
  827. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  828. const { t } = useTranslation();
  829. const known = state !== null;
  830. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  831. let title: string;
  832. if (state === true) {
  833. className += known
  834. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  835. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  836. title = t('printers.amsBackup.titleOn');
  837. } else if (state === false) {
  838. className += known
  839. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  840. : 'bg-bambu-dark text-bambu-gray cursor-default';
  841. title = t('printers.amsBackup.titleOff');
  842. } else {
  843. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  844. title = t('printers.amsBackup.titleUnknown');
  845. }
  846. return (
  847. <button
  848. type="button"
  849. disabled={!known}
  850. onClick={() => known && onClick()}
  851. className={className}
  852. title={title}
  853. aria-label={title}
  854. >
  855. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  856. </button>
  857. );
  858. }
  859. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  860. // like AmsBackupBadge so the two sit together in the section header, but
  861. // pinned to the right-hand end of the rule: this is a view preference for the
  862. // row, not a property of the printer.
  863. interface ExternalSpoolToggleProps {
  864. hidden: boolean;
  865. onClick: () => void;
  866. }
  867. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  868. const { t } = useTranslation();
  869. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  870. return (
  871. <button
  872. type="button"
  873. onClick={onClick}
  874. aria-pressed={hidden}
  875. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  876. hidden
  877. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  878. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  879. }`}
  880. title={title}
  881. aria-label={title}
  882. >
  883. {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)]" />}
  884. </button>
  885. );
  886. }
  887. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  888. // Reference: https://github.com/theicedmango/bambu-humidity
  889. interface HumidityIndicatorProps {
  890. humidity: number | string;
  891. goodThreshold?: number; // <= this is green
  892. fairThreshold?: number; // <= this is orange, > is red
  893. onClick?: () => void;
  894. compact?: boolean; // Smaller version for grid layout
  895. }
  896. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  897. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  898. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  899. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  900. // Status thresholds (configurable via settings)
  901. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  902. let textColor: string;
  903. let statusText: string;
  904. if (isNaN(humidityValue)) {
  905. textColor = '#C3C2C1';
  906. statusText = 'Unknown';
  907. } else if (humidityValue <= good) {
  908. textColor = '#22a352'; // Green - Good
  909. statusText = 'Good';
  910. } else if (humidityValue <= fair) {
  911. textColor = '#d4a017'; // Gold - Fair
  912. statusText = 'Fair';
  913. } else {
  914. textColor = '#c62828'; // Red - Bad
  915. statusText = 'Bad';
  916. }
  917. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  918. let DropComponent: React.FC<{ className?: string }>;
  919. if (isNaN(humidityValue)) {
  920. DropComponent = WaterDropEmpty;
  921. } else if (humidityValue <= good) {
  922. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  923. } else if (humidityValue <= fair) {
  924. DropComponent = WaterDropHalf; // Fair - half filled
  925. } else {
  926. DropComponent = WaterDropFull; // Bad - full (too humid)
  927. }
  928. return (
  929. <button
  930. type="button"
  931. onClick={onClick}
  932. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  933. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  934. >
  935. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  936. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  937. </button>
  938. );
  939. }
  940. // Temperature indicator with dynamic icon and coloring
  941. interface TemperatureIndicatorProps {
  942. temp: number;
  943. goodThreshold?: number; // <= this is blue
  944. fairThreshold?: number; // <= this is orange, > is red
  945. onClick?: () => void;
  946. compact?: boolean; // Smaller version for grid layout
  947. }
  948. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  949. // Ensure thresholds are numbers
  950. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  951. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  952. let textColor: string;
  953. let statusText: string;
  954. let ThermoComponent: React.FC<{ className?: string }>;
  955. if (temp <= good) {
  956. textColor = '#22a352'; // Green - good (same as humidity)
  957. statusText = 'Good';
  958. ThermoComponent = ThermometerEmpty;
  959. } else if (temp <= fair) {
  960. textColor = '#d4a017'; // Gold - fair (same as humidity)
  961. statusText = 'Fair';
  962. ThermoComponent = ThermometerHalf;
  963. } else {
  964. textColor = '#c62828'; // Red - bad (same as humidity)
  965. statusText = 'Bad';
  966. ThermoComponent = ThermometerFull;
  967. }
  968. return (
  969. <button
  970. type="button"
  971. onClick={onClick}
  972. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  973. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  974. >
  975. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  976. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  977. </button>
  978. );
  979. }
  980. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  981. *
  982. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  983. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  984. * every empty-by-bitmask slot lands here regardless of firmware payload
  985. * shape.
  986. *
  987. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  988. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  989. * the user cleared with "Reset Slot" where a physical spool may still be
  990. * loaded but unassigned.
  991. *
  992. * Returns null when the slot is loaded (tray_type is present).
  993. */
  994. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  995. if (tray?.tray_type) return null;
  996. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  997. // spool the firmware can't identify is physically present (exists === true)
  998. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  999. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  1000. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  1001. if (tray?.exists === true) return 'reset';
  1002. if (tray?.exists === false) return 'physical';
  1003. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  1004. }
  1005. // How long to wait for an AMS to report a live drying cycle after the printer
  1006. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  1007. // within a couple of seconds; 30s covers the slowest observed push cadence
  1008. // without leaving the user waiting on a verdict.
  1009. const DRY_START_CONFIRM_MS = 30_000;
  1010. export function CoverImage({
  1011. url,
  1012. printName,
  1013. className = 'w-20 h-20',
  1014. radiusClass = 'rounded-lg',
  1015. }: {
  1016. url: string | null;
  1017. printName?: string;
  1018. className?: string;
  1019. radiusClass?: string;
  1020. }) {
  1021. const { t } = useTranslation();
  1022. const [loaded, setLoaded] = useState(false);
  1023. const [error, setError] = useState(false);
  1024. const [showOverlay, setShowOverlay] = useState(false);
  1025. const imgRef = useRef<HTMLImageElement>(null);
  1026. // Cache-bust the image URL when the print name changes so the browser
  1027. // fetches the new cover instead of serving the stale cached image.
  1028. const cacheBustedUrl = useMemo(() => {
  1029. if (!url) return null;
  1030. const sep = url.includes('?') ? '&' : '?';
  1031. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1032. }, [url, printName]);
  1033. // Re-evaluate load state when the image URL changes, and ask the element
  1034. // whether it is already showing something rather than assuming it is not.
  1035. //
  1036. // `onLoad` used to be the only thing that could set `loaded`, and this
  1037. // effect reset it to false unconditionally. That is right when the URL
  1038. // really changes, but it also runs on mount — and the two are not the same
  1039. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1040. // constant for the duration of a print, so navigating away from the
  1041. // printers page and back re-mounts with a byte-identical src that the
  1042. // browser serves from its in-memory cache. The `load` event for a cache hit
  1043. // and React's passive-effect flush are both plain tasks with no ordering
  1044. // between them, so when `load` won, this effect ran afterwards and undid
  1045. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1046. // sat there until a full reload. Nothing recovered it, because the URL
  1047. // never changes again during the print and so this effect never re-runs.
  1048. //
  1049. // Being a race, it reproduced every time for #2826's reporter and not at
  1050. // all here, which is also why the network panel showed no request: there
  1051. // was no request to show.
  1052. //
  1053. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1054. // which of the two ran first. It is also correct for the case the reporter
  1055. // proposed (a `load` that fires before React's handler is live), so the
  1056. // fix stands whichever mechanism is really at work.
  1057. useEffect(() => {
  1058. setError(false);
  1059. const el = imgRef.current;
  1060. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1061. }, [cacheBustedUrl]);
  1062. return (
  1063. <>
  1064. <div
  1065. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1066. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1067. >
  1068. {cacheBustedUrl && !error ? (
  1069. <>
  1070. <img
  1071. ref={imgRef}
  1072. src={cacheBustedUrl}
  1073. alt={t('printers.printPreview')}
  1074. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1075. onLoad={() => setLoaded(true)}
  1076. onError={() => setError(true)}
  1077. />
  1078. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1079. </>
  1080. ) : (
  1081. <Box className="w-8 h-8 text-bambu-gray" />
  1082. )}
  1083. </div>
  1084. {/* Cover Image Overlay */}
  1085. {showOverlay && cacheBustedUrl && (
  1086. <div
  1087. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1088. onClick={() => setShowOverlay(false)}
  1089. >
  1090. <div className="relative max-w-2xl max-h-full">
  1091. <img
  1092. src={cacheBustedUrl}
  1093. alt={t('printers.printPreview')}
  1094. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1095. />
  1096. {printName && (
  1097. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1098. )}
  1099. </div>
  1100. </div>
  1101. )}
  1102. </>
  1103. );
  1104. }
  1105. interface PrinterMaintenanceInfo {
  1106. due_count: number;
  1107. warning_count: number;
  1108. total_print_hours: number;
  1109. }
  1110. // Status summary bar component - uses queryClient to read cached statuses
  1111. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1112. const { t } = useTranslation();
  1113. const queryClient = useQueryClient();
  1114. // Subscribe to query cache changes to re-render when status updates
  1115. // Throttled to prevent rapid re-renders from causing tab crashes
  1116. const [cacheTick, setCacheTick] = useState(0);
  1117. useEffect(() => {
  1118. let pending = false;
  1119. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1120. if (!pending) {
  1121. pending = true;
  1122. requestAnimationFrame(() => {
  1123. setCacheTick(t => t + 1);
  1124. pending = false;
  1125. });
  1126. }
  1127. });
  1128. return () => unsubscribe();
  1129. }, [queryClient]);
  1130. const { counts, nextFinish } = useMemo(() => {
  1131. let printing = 0;
  1132. let paused = 0;
  1133. let finished = 0;
  1134. let idle = 0;
  1135. let offline = 0;
  1136. let loading = 0;
  1137. let error = 0;
  1138. let nextPrinterName: string | null = null;
  1139. let nextRemainingMin: number | null = null;
  1140. let nextProgress: number = 0;
  1141. printers?.forEach((printer) => {
  1142. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1143. if (status === undefined) {
  1144. // Status not yet loaded - don't count as offline yet
  1145. loading++;
  1146. } else if (!status.connected) {
  1147. offline++;
  1148. } else {
  1149. // Count printers with active HMS errors as problems
  1150. const knownHmsCount =
  1151. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1152. if (knownHmsCount > 0) {
  1153. error++;
  1154. }
  1155. switch (status.state) {
  1156. case 'RUNNING':
  1157. printing++;
  1158. if (status.remaining_time != null && status.remaining_time > 0) {
  1159. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1160. nextRemainingMin = status.remaining_time;
  1161. nextPrinterName = printer.name;
  1162. nextProgress = status.progress || 0;
  1163. }
  1164. }
  1165. break;
  1166. case 'PAUSE':
  1167. paused++;
  1168. break;
  1169. case 'FINISH':
  1170. finished++;
  1171. break;
  1172. case 'FAILED':
  1173. // FAILED is the printer's terminal gcode_state after a print stops —
  1174. // including user cancellations, where there's no actual fault. Only
  1175. // count it as a "problem" when an HMS error is also active; otherwise
  1176. // it's just a print that ended unsuccessfully and the plate needs
  1177. // clearing (same as FINISH from the operator's perspective).
  1178. if (knownHmsCount > 0) {
  1179. // Already counted above
  1180. } else {
  1181. finished++;
  1182. }
  1183. break;
  1184. default:
  1185. idle++;
  1186. break;
  1187. }
  1188. }
  1189. });
  1190. return {
  1191. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1192. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1193. };
  1194. // eslint-disable-next-line react-hooks/exhaustive-deps
  1195. }, [printers, queryClient, cacheTick]);
  1196. if (!printers?.length) return null;
  1197. const badges: { count: number; dot: string; label: string }[] = [
  1198. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1199. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1200. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1201. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1202. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1203. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1204. ];
  1205. return (
  1206. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1207. {badges.map(({ count, dot, label }) => count > 0 && (
  1208. <div key={label} className="flex items-center gap-1.5">
  1209. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1210. <span className="text-bambu-gray">
  1211. <span className="text-white font-medium">{count}</span> {label}
  1212. </span>
  1213. </div>
  1214. ))}
  1215. {nextFinish && (
  1216. <>
  1217. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1218. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1219. <div className="flex items-center gap-2">
  1220. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1221. <span className="text-white font-medium">{nextFinish.name}</span>
  1222. </div>
  1223. <div className="flex items-center gap-2 w-full sm:w-auto">
  1224. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1225. <div
  1226. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1227. style={{ width: `${nextFinish.progress}%` }}
  1228. />
  1229. </div>
  1230. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1231. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1232. </div>
  1233. </div>
  1234. </>
  1235. )}
  1236. </div>
  1237. );
  1238. }
  1239. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1240. type ViewMode = 'expanded' | 'compact';
  1241. type ToolbarDropdownOption<T extends string> = {
  1242. value: T;
  1243. label: string;
  1244. };
  1245. function ToolbarDropdown<T extends string>({
  1246. value,
  1247. options,
  1248. onChange,
  1249. fullWidth = false,
  1250. }: {
  1251. value: T;
  1252. options: ToolbarDropdownOption<T>[];
  1253. onChange: (value: T) => void;
  1254. fullWidth?: boolean;
  1255. }) {
  1256. const [isOpen, setIsOpen] = useState(false);
  1257. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1258. return (
  1259. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1260. <button
  1261. type="button"
  1262. onClick={() => setIsOpen(open => !open)}
  1263. 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'}`}
  1264. >
  1265. <span className="truncate">{selectedOption?.label}</span>
  1266. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1267. </button>
  1268. {isOpen && (
  1269. <>
  1270. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1271. <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">
  1272. {options.map(option => (
  1273. <button
  1274. key={option.value}
  1275. type="button"
  1276. onClick={() => {
  1277. onChange(option.value);
  1278. setIsOpen(false);
  1279. }}
  1280. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1281. option.value === value ? 'text-bambu-green' : 'text-white'
  1282. }`}
  1283. >
  1284. {option.label}
  1285. </button>
  1286. ))}
  1287. </div>
  1288. </>
  1289. )}
  1290. </div>
  1291. );
  1292. }
  1293. function ToolbarMenu({
  1294. label,
  1295. icon,
  1296. children,
  1297. }: {
  1298. label: string;
  1299. icon: React.ReactNode;
  1300. children: React.ReactNode;
  1301. }) {
  1302. const [isOpen, setIsOpen] = useState(false);
  1303. return (
  1304. <div className="relative">
  1305. <button
  1306. type="button"
  1307. onClick={() => setIsOpen(open => !open)}
  1308. 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"
  1309. aria-label={label}
  1310. title={label}
  1311. >
  1312. {icon}
  1313. </button>
  1314. {isOpen && (
  1315. <>
  1316. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1317. <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">
  1318. {children}
  1319. </div>
  1320. </>
  1321. )}
  1322. </div>
  1323. );
  1324. }
  1325. function IndicatorControlPopover({
  1326. title,
  1327. options = [],
  1328. unit,
  1329. customMin,
  1330. customMax,
  1331. customStep = 1,
  1332. widthClass = 'w-[240px]',
  1333. popoverWidth = 240,
  1334. popoverHeight = 280,
  1335. isPending,
  1336. onClose,
  1337. onSubmit,
  1338. children,
  1339. }: {
  1340. title: string;
  1341. options?: Array<{ label: string; value: number }>;
  1342. unit?: string;
  1343. customMin?: number;
  1344. customMax?: number;
  1345. customStep?: number;
  1346. widthClass?: string;
  1347. popoverWidth?: number;
  1348. popoverHeight?: number;
  1349. isPending?: boolean;
  1350. onClose: () => void;
  1351. onSubmit?: (value: number) => void;
  1352. children?: React.ReactNode;
  1353. }) {
  1354. const anchorRef = useRef<HTMLSpanElement>(null);
  1355. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1356. const [customValue, setCustomValue] = useState('');
  1357. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1358. // can position via fixed coords. Portaling to document.body escapes
  1359. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1360. // own contexts and would otherwise cover the popover even at z-[60].
  1361. useLayoutEffect(() => {
  1362. const trigger = anchorRef.current?.parentElement;
  1363. if (!trigger) return;
  1364. const measure = () => {
  1365. const rect = trigger.getBoundingClientRect();
  1366. setCoords(computePopoverPosition({
  1367. triggerRect: rect,
  1368. popoverWidth,
  1369. estimatedHeight: popoverHeight,
  1370. horizontalAlign: 'center',
  1371. }));
  1372. };
  1373. measure();
  1374. window.addEventListener('resize', measure);
  1375. window.addEventListener('scroll', measure, true);
  1376. return () => {
  1377. window.removeEventListener('resize', measure);
  1378. window.removeEventListener('scroll', measure, true);
  1379. };
  1380. }, [popoverWidth, popoverHeight]);
  1381. const showCustomInput = unit !== undefined;
  1382. const submitCustom = () => {
  1383. const value = Number(customValue);
  1384. if (!Number.isFinite(value)) return;
  1385. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1386. onSubmit?.(Math.round(bounded));
  1387. };
  1388. return (
  1389. <>
  1390. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1391. {createPortal(
  1392. <>
  1393. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1394. <div
  1395. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1396. style={{
  1397. top: coords?.top ?? -9999,
  1398. left: coords?.left ?? -9999,
  1399. visibility: coords ? 'visible' : 'hidden',
  1400. }}
  1401. onClick={e => e.stopPropagation()}
  1402. >
  1403. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1404. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1405. {options.length > 0 && (
  1406. <div className="px-3 py-2.5">
  1407. <div className="grid grid-cols-2 gap-1.5">
  1408. {options.map(option => (
  1409. <button
  1410. key={`${option.label}-${option.value}`}
  1411. type="button"
  1412. disabled={isPending}
  1413. onClick={() => onSubmit?.(option.value)}
  1414. 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"
  1415. >
  1416. {option.label}
  1417. </button>
  1418. ))}
  1419. </div>
  1420. </div>
  1421. )}
  1422. {children}
  1423. {showCustomInput && (
  1424. <>
  1425. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1426. <form
  1427. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1428. onSubmit={(e) => {
  1429. e.preventDefault();
  1430. submitCustom();
  1431. }}
  1432. >
  1433. <input
  1434. type="number"
  1435. min={customMin}
  1436. max={customMax}
  1437. step={customStep}
  1438. value={customValue}
  1439. onChange={e => setCustomValue(e.target.value)}
  1440. placeholder="Custom"
  1441. 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"
  1442. />
  1443. <button
  1444. type="submit"
  1445. disabled={isPending || customValue.trim() === ''}
  1446. 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"
  1447. >
  1448. Set
  1449. </button>
  1450. </form>
  1451. </>
  1452. )}
  1453. </div>
  1454. </>,
  1455. document.body
  1456. )}
  1457. </>
  1458. );
  1459. }
  1460. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1461. function NozzleTemperatureControlBox({
  1462. label,
  1463. current,
  1464. target,
  1465. isActive,
  1466. isPending,
  1467. onSubmit,
  1468. options = NOZZLE_TEMPERATURE_OPTIONS,
  1469. }: {
  1470. label: string;
  1471. current?: number;
  1472. target?: number;
  1473. isActive: boolean;
  1474. isPending?: boolean;
  1475. onSubmit: (value: number) => void;
  1476. options?: Array<{ label: string; value: number }>;
  1477. }) {
  1478. const [customValue, setCustomValue] = useState('');
  1479. const submitCustom = () => {
  1480. const value = Number(customValue);
  1481. if (!Number.isFinite(value)) return;
  1482. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1483. };
  1484. return (
  1485. <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'}`}>
  1486. <div className="mb-1.5 flex items-center justify-between gap-2">
  1487. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1488. <span className="text-[10px] text-bambu-gray">
  1489. {Math.round(current ?? 0)}°C
  1490. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1491. </span>
  1492. </div>
  1493. <div className="grid grid-cols-2 gap-1">
  1494. {options.map(option => (
  1495. <button
  1496. key={`${label}-${option.value}`}
  1497. type="button"
  1498. disabled={isPending}
  1499. onClick={() => onSubmit(option.value)}
  1500. 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"
  1501. >
  1502. {option.label}
  1503. </button>
  1504. ))}
  1505. </div>
  1506. <form
  1507. className="mt-1.5 flex gap-1"
  1508. onSubmit={(e) => {
  1509. e.preventDefault();
  1510. submitCustom();
  1511. }}
  1512. >
  1513. <input
  1514. type="number"
  1515. min={0}
  1516. max={320}
  1517. step={1}
  1518. value={customValue}
  1519. onChange={e => setCustomValue(e.target.value)}
  1520. placeholder="Custom"
  1521. 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"
  1522. />
  1523. <button
  1524. type="submit"
  1525. disabled={isPending || customValue.trim() === ''}
  1526. 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"
  1527. >
  1528. Set
  1529. </button>
  1530. </form>
  1531. </div>
  1532. );
  1533. }
  1534. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1535. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1536. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1537. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1538. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1539. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1540. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1541. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1542. };
  1543. /** Classify a printer into one of the UI status buckets. */
  1544. function classifyPrinterStatus(
  1545. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1546. ): PrinterState {
  1547. if (!status?.connected) return 'offline';
  1548. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1549. if (hmsErrors.length > 0) return 'error';
  1550. switch (status.state) {
  1551. case 'RUNNING': return 'printing';
  1552. case 'PAUSE': return 'paused';
  1553. case 'FINISH': return 'finished';
  1554. // FAILED without an active HMS error is the printer's terminal state after
  1555. // any unsuccessful end — including user-cancellations. Treat the same as
  1556. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1557. // HMS code is actually attached (handled by the early-return above).
  1558. case 'FAILED': return 'finished';
  1559. default: return 'idle';
  1560. }
  1561. }
  1562. /**
  1563. * Get human-readable status display text for a printer.
  1564. * Uses stg_cur_name for detailed calibration/preparation stages,
  1565. * otherwise formats the gcode_state nicely.
  1566. */
  1567. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1568. // If we have a specific stage name (calibration, heating, etc.), use it
  1569. if (stg_cur_name) {
  1570. return stg_cur_name;
  1571. }
  1572. // Format the gcode_state nicely
  1573. switch (state) {
  1574. case 'RUNNING':
  1575. return 'Printing';
  1576. case 'PAUSE':
  1577. return 'Paused';
  1578. case 'FINISH':
  1579. return 'Finished';
  1580. case 'FAILED':
  1581. return 'Failed';
  1582. case 'IDLE':
  1583. return 'Idle';
  1584. default:
  1585. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1586. }
  1587. }
  1588. // Bambu models that ship with an enclosure chamber fan (firmware field
  1589. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1590. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1591. // widget is hidden in fanItems instead of rendered greyed-out.
  1592. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1593. 'X1C',
  1594. 'X1',
  1595. 'X1E',
  1596. 'X2D',
  1597. 'P1S',
  1598. 'P2S',
  1599. 'H2D',
  1600. 'H2D Pro',
  1601. 'H2C',
  1602. 'H2S',
  1603. ]);
  1604. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1605. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1606. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1607. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1608. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1609. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1610. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1611. 'P2S',
  1612. 'X2D',
  1613. ]);
  1614. // Map SSDP model codes to display names
  1615. function mapModelCode(ssdpModel: string | null): string {
  1616. if (!ssdpModel) return '';
  1617. const modelMap: Record<string, string> = {
  1618. // H2 Series
  1619. 'O1D': 'H2D',
  1620. 'O1E': 'H2D Pro',
  1621. 'O2D': 'H2D Pro',
  1622. 'O1C': 'H2C',
  1623. 'O1C2': 'H2C',
  1624. 'O1S': 'H2S',
  1625. // X1 Series
  1626. 'BL-P001': 'X1C',
  1627. 'BL-P002': 'X1',
  1628. 'BL-P003': 'X1E',
  1629. // X2 Series
  1630. 'N6': 'X2D',
  1631. // A2 Series
  1632. 'N9': 'A2L',
  1633. // P Series
  1634. 'C11': 'P1S',
  1635. 'C12': 'P1P',
  1636. 'C13': 'P2S',
  1637. // A1 Series
  1638. 'N2S': 'A1',
  1639. 'N1': 'A1 Mini',
  1640. // Direct matches
  1641. 'X1C': 'X1C',
  1642. 'X1': 'X1',
  1643. 'X1E': 'X1E',
  1644. 'X2D': 'X2D',
  1645. 'P1S': 'P1S',
  1646. 'P1P': 'P1P',
  1647. 'P2S': 'P2S',
  1648. 'A1': 'A1',
  1649. 'A1 Mini': 'A1 Mini',
  1650. 'A2L': 'A2L',
  1651. 'H2D': 'H2D',
  1652. 'H2D Pro': 'H2D Pro',
  1653. 'H2C': 'H2C',
  1654. 'H2S': 'H2S',
  1655. };
  1656. return modelMap[ssdpModel] || ssdpModel;
  1657. }
  1658. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1659. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1660. // • User-defined friendly name (editable, protected by printers:update)
  1661. // • AMS serial number
  1662. // • AMS firmware version
  1663. export function AmsNameHoverCard({
  1664. ams,
  1665. printerId,
  1666. label,
  1667. amsLabels,
  1668. canEdit,
  1669. onSaved,
  1670. children,
  1671. }: {
  1672. ams: import('../api/client').AMSUnit;
  1673. printerId: number;
  1674. label: string; // auto-generated label, e.g. "AMS-A"
  1675. amsLabels?: Record<number, string>;
  1676. canEdit: boolean;
  1677. onSaved: () => void;
  1678. children: React.ReactNode;
  1679. }) {
  1680. const { t } = useTranslation();
  1681. const [isVisible, setIsVisible] = useState(false);
  1682. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1683. const [editValue, setEditValue] = useState('');
  1684. const [isSaving, setIsSaving] = useState(false);
  1685. const [saveError, setSaveError] = useState<string | null>(null);
  1686. const [isInputFocused, setIsInputFocused] = useState(false);
  1687. const triggerRef = useRef<HTMLDivElement>(null);
  1688. const cardRef = useRef<HTMLDivElement>(null);
  1689. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1690. useEffect(() => {
  1691. if (isVisible) {
  1692. setEditValue(amsLabels?.[ams.id] ?? '');
  1693. setSaveError(null);
  1694. requestAnimationFrame(() => {
  1695. if (triggerRef.current && cardRef.current) {
  1696. const rect = triggerRef.current.getBoundingClientRect();
  1697. const spaceAbove = rect.top - 56;
  1698. const spaceBelow = window.innerHeight - rect.bottom;
  1699. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1700. }
  1701. });
  1702. }
  1703. }, [isVisible, amsLabels, ams.id]);
  1704. const handleMouseEnter = () => {
  1705. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1706. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1707. };
  1708. const handleMouseLeave = () => {
  1709. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1710. if (!isInputFocused) {
  1711. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1712. }
  1713. };
  1714. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1715. const handleSave = async () => {
  1716. if (!canEdit) return;
  1717. setIsSaving(true);
  1718. setSaveError(null);
  1719. try {
  1720. const trimmed = editValue.trim();
  1721. if (trimmed) {
  1722. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1723. } else {
  1724. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1725. }
  1726. onSaved();
  1727. setIsVisible(false);
  1728. } catch (err) {
  1729. setSaveError(err instanceof Error ? err.message : String(err));
  1730. } finally {
  1731. setIsSaving(false);
  1732. }
  1733. };
  1734. const handleClear = async () => {
  1735. if (!canEdit) return;
  1736. setIsSaving(true);
  1737. setSaveError(null);
  1738. try {
  1739. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1740. onSaved();
  1741. setIsVisible(false);
  1742. } catch (err) {
  1743. setSaveError(err instanceof Error ? err.message : String(err));
  1744. } finally {
  1745. setIsSaving(false);
  1746. }
  1747. };
  1748. return (
  1749. <div
  1750. ref={triggerRef}
  1751. className="relative inline-block"
  1752. onMouseEnter={handleMouseEnter}
  1753. onMouseLeave={handleMouseLeave}
  1754. >
  1755. {children}
  1756. {isVisible && (
  1757. <div
  1758. ref={cardRef}
  1759. className={`
  1760. absolute left-0 z-50
  1761. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1762. animate-in fade-in-0 zoom-in-95 duration-150
  1763. `}
  1764. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1765. onMouseEnter={handleMouseEnter}
  1766. onMouseLeave={handleMouseLeave}
  1767. >
  1768. <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">
  1769. {/* AMS auto-label */}
  1770. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1771. {/* Serial number */}
  1772. <div className="flex items-center justify-between gap-2">
  1773. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1774. {t('printers.amsPopup.serialNumber')}
  1775. </span>
  1776. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1777. </div>
  1778. {/* Firmware version */}
  1779. <div className="flex items-center justify-between gap-2">
  1780. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1781. {t('printers.amsPopup.firmwareVersion')}
  1782. </span>
  1783. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1784. </div>
  1785. {/* Friendly name editor */}
  1786. <div className="space-y-1">
  1787. <div className="flex items-center gap-2">
  1788. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1789. {t('printers.amsPopup.friendlyName')}
  1790. </span>
  1791. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1792. </div>
  1793. <input
  1794. type="text"
  1795. value={editValue}
  1796. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1797. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1798. onFocus={() => setIsInputFocused(true)}
  1799. onBlur={() => {
  1800. setIsInputFocused(false);
  1801. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1802. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1803. }}
  1804. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1805. disabled={!canEdit}
  1806. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1807. 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"
  1808. maxLength={100}
  1809. />
  1810. {canEdit && (
  1811. <div className="space-y-1">
  1812. {saveError && (
  1813. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1814. )}
  1815. <div className="flex gap-1 justify-end">
  1816. <button
  1817. onClick={handleSave}
  1818. disabled={isSaving}
  1819. 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"
  1820. >
  1821. {t('printers.amsPopup.save')}
  1822. </button>
  1823. {amsLabels?.[ams.id] && (
  1824. <button
  1825. onClick={handleClear}
  1826. disabled={isSaving}
  1827. 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"
  1828. >
  1829. {t('printers.amsPopup.clear')}
  1830. </button>
  1831. )}
  1832. </div>
  1833. </div>
  1834. )}
  1835. </div>
  1836. </div>
  1837. </div>
  1838. )}
  1839. </div>
  1840. );
  1841. }
  1842. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1843. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1844. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1845. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1846. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1847. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1848. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1849. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1850. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1851. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1852. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1853. };
  1854. // How much the printer card's body type and icons grow at each card size
  1855. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1856. // 1.0 and an existing install looks identical until the user picks L or XL --
  1857. // the same control the request asked to have this follow.
  1858. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1859. // The scaled sizes, handed to the card subtree as custom properties. Every
  1860. // converted class names its old fixed value as the fallback, so anything that
  1861. // renders outside a card root -- the portalled temperature popover -- keeps
  1862. // exactly the size it has today.
  1863. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1864. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1865. // Rounded to a tenth so the values stay readable in devtools.
  1866. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1867. return {
  1868. '--pc-t8': px(8),
  1869. '--pc-t9': px(9),
  1870. '--pc-t10': px(10),
  1871. '--pc-t11': px(11),
  1872. '--pc-i2': px(8),
  1873. '--pc-i25': px(10),
  1874. '--pc-i3': px(12),
  1875. '--pc-i35': px(14),
  1876. '--pc-i4': px(16),
  1877. '--pc-i5': px(20),
  1878. '--pc-i7': px(28),
  1879. } as React.CSSProperties;
  1880. }
  1881. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1882. const { t } = useTranslation();
  1883. const queryClient = useQueryClient();
  1884. const { showToast } = useToast();
  1885. // One fleet-wide query shared by every card, not one per card: the list is
  1886. // nearly always empty and a 20-printer fleet would otherwise make 20
  1887. // requests every 30s. React Query dedupes on the key.
  1888. const { data: scheduled = [] } = useQuery({
  1889. queryKey: SCHEDULED_DRYINGS_KEY,
  1890. queryFn: () => api.listScheduledDryings(),
  1891. refetchInterval: 30_000,
  1892. });
  1893. // The live AMS status reports a starting cycle well before the next poll;
  1894. // refetch so a just-dispatched schedule doesn't linger as pending.
  1895. useEffect(() => {
  1896. if (dryingActive) {
  1897. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1898. }
  1899. }, [dryingActive, queryClient]);
  1900. const cancelMutation = useMutation({
  1901. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1902. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1903. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1904. });
  1905. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1906. // old firmware on a printer that was offline at schedule time), and without
  1907. // this the run just vanishes with only the backend log saying why.
  1908. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1909. if (rows.length === 0) return null;
  1910. return (
  1911. <div className="mt-2 space-y-1">
  1912. {rows.map(s => {
  1913. const failed = s.status === 'failed';
  1914. const reasonKey = waitingReasonKey(s.waiting_reason);
  1915. return (
  1916. <div
  1917. key={s.id}
  1918. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1919. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1920. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1921. }`}
  1922. >
  1923. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1924. {failed ? (
  1925. t('printers.drying.scheduleFailedReason', {
  1926. reason: s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1927. })
  1928. ) : (
  1929. <>
  1930. {s.start_after
  1931. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1932. : t('printers.drying.scheduledAsap')}
  1933. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1934. </>
  1935. )}
  1936. </span>
  1937. <button
  1938. onClick={() => cancelMutation.mutate(s.id)}
  1939. disabled={cancelMutation.isPending}
  1940. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1941. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1942. >
  1943. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1944. </button>
  1945. </div>
  1946. );
  1947. })}
  1948. </div>
  1949. );
  1950. }
  1951. function PrinterCard({
  1952. printer,
  1953. hideIfDisconnected,
  1954. maintenanceInfo,
  1955. viewMode = 'expanded',
  1956. cardSize = 2,
  1957. amsThresholds,
  1958. spoolmanEnabled = false,
  1959. linkedSpools,
  1960. spoolmanUrl,
  1961. spoolmanSyncMode,
  1962. onGetAssignment,
  1963. onUnassignSpool,
  1964. spoolmanSpools,
  1965. spoolmanSlotAssignments,
  1966. spoolmanLoading = false,
  1967. onUnassignSpoolmanSpool,
  1968. timeFormat = 'system',
  1969. cameraViewMode = 'window',
  1970. onOpenEmbeddedCamera,
  1971. onSelectCameraViewMode,
  1972. checkPrinterFirmware = true,
  1973. dryingPresets = DRYING_PRESETS,
  1974. requirePlateClear = false,
  1975. selectionMode = false,
  1976. isSelected = false,
  1977. onToggleSelect,
  1978. onOpenCompactCard,
  1979. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1980. bedTempPresets = BED_TEMP_DEFAULTS,
  1981. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1982. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1983. aiDetectionEnabled = false,
  1984. aiDetection,
  1985. aiLastError = null,
  1986. }: {
  1987. printer: Printer;
  1988. hideIfDisconnected?: boolean;
  1989. maintenanceInfo?: PrinterMaintenanceInfo;
  1990. viewMode?: ViewMode;
  1991. cardSize?: number;
  1992. amsThresholds?: {
  1993. humidityGood: number;
  1994. humidityFair: number;
  1995. tempGood: number;
  1996. tempFair: number;
  1997. };
  1998. spoolmanEnabled?: boolean;
  1999. hasUnlinkedSpools?: boolean;
  2000. linkedSpools?: Record<string, LinkedSpoolInfo>;
  2001. spoolmanUrl?: string | null;
  2002. spoolmanSyncMode?: string | null;
  2003. spoolAssignments?: SpoolAssignment[];
  2004. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  2005. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  2006. spoolmanSpools?: InventorySpool[];
  2007. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  2008. spoolmanLoading?: boolean;
  2009. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  2010. timeFormat?: 'system' | '12h' | '24h';
  2011. cameraViewMode?: CameraViewMode;
  2012. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  2013. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  2014. checkPrinterFirmware?: boolean;
  2015. dryingPresets?: Record<string, DryingPreset>;
  2016. requirePlateClear?: boolean;
  2017. selectionMode?: boolean;
  2018. isSelected?: boolean;
  2019. onToggleSelect?: (id: number) => void;
  2020. onOpenCompactCard?: (id: number) => void;
  2021. nozzleTempPresets?: readonly [number, number, number];
  2022. bedTempPresets?: readonly [number, number, number];
  2023. chamberTempPresets?: readonly [number, number, number];
  2024. fanSpeedPresets?: readonly [number, number, number];
  2025. aiDetectionEnabled?: boolean;
  2026. aiDetection?: AiDetection;
  2027. aiLastError?: string | null;
  2028. }) {
  2029. const { t } = useTranslation();
  2030. const queryClient = useQueryClient();
  2031. const navigate = useNavigate();
  2032. const { showToast } = useToast();
  2033. const { hasPermission, canModify } = useAuth();
  2034. const [showMenu, setShowMenu] = useState(false);
  2035. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  2036. const [deleteArchives, setDeleteArchives] = useState(true);
  2037. const [showEditModal, setShowEditModal] = useState(false);
  2038. const [showFileManager, setShowFileManager] = useState(false);
  2039. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  2040. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  2041. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  2042. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  2043. const [showHMSModal, setShowHMSModal] = useState(false);
  2044. // #1546: AI failure detection modal — opens from the AI badge.
  2045. const [showAiModal, setShowAiModal] = useState(false);
  2046. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  2047. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  2048. // External spool visibility (#1782) — browser-local, per printer. Read once
  2049. // per card; the toggle that writes it is the only thing that changes it.
  2050. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2051. isExternalSpoolHidden(printer.id),
  2052. );
  2053. const toggleExternalSpool = useCallback(() => {
  2054. setExternalSpoolHidden((prev) => {
  2055. const next = !prev;
  2056. persistExternalSpoolHidden(printer.id, next);
  2057. return next;
  2058. });
  2059. }, [printer.id]);
  2060. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2061. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2062. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2063. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2064. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2065. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2066. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2067. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2068. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2069. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2070. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2071. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2072. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2073. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2074. // AMS drying popover state: which AMS unit has the popover open
  2075. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2076. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2077. const [dryingFilament, setDryingFilament] = useState('PLA');
  2078. const [dryingTemp, setDryingTemp] = useState(50);
  2079. const [dryingDuration, setDryingDuration] = useState(4);
  2080. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2081. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2082. // go through scheduleDryingMutation.
  2083. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2084. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2085. const [dryingStartAt, setDryingStartAt] = useState('');
  2086. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2087. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2088. // Reset every field the popover owns, including the start mode. Leaving the
  2089. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2090. // the next open, by then in the past, and the POST rejected it.
  2091. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2092. const firstTray = ams.tray.find(t => t.tray_type);
  2093. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2094. // Only reachable if a custom preset set dropped PLA itself.
  2095. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2096. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2097. setDryingFilament(filType);
  2098. setDryingTemp(preset[moduleType] || preset.n3f);
  2099. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2100. setDryingRotateTray(false);
  2101. setDryingStartMode('now');
  2102. setDryingDelayMinutes(120);
  2103. setDryingStartAt('');
  2104. setDryingPopoverModuleType(ams.module_type);
  2105. setDryingPopoverAmsId(ams.id);
  2106. setDryingPopoverAnchor(trigger);
  2107. }, [dryingPresets]);
  2108. // Re-measure on resize/scroll so the popover and its arrow track the
  2109. // flame button, like IndicatorControlPopover.
  2110. useLayoutEffect(() => {
  2111. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2112. const measure = () => {
  2113. setDryingPopoverPos(computePopoverPosition({
  2114. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2115. popoverWidth: DRYING_POPOVER_WIDTH,
  2116. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2117. horizontalAlign: 'center',
  2118. }));
  2119. };
  2120. measure();
  2121. window.addEventListener('resize', measure);
  2122. window.addEventListener('scroll', measure, true);
  2123. return () => {
  2124. window.removeEventListener('resize', measure);
  2125. window.removeEventListener('scroll', measure, true);
  2126. };
  2127. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2128. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2129. // Whether the click hitting the backdrop is the one that dismissed the
  2130. // native datetime picker (see the backdrop's onMouseDown).
  2131. const dryingBackdropSkipCloseRef = useRef(false);
  2132. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2133. // an object rather than a bare id so restarting drying on the SAME unit produces
  2134. // a new identity and rearms the timeout below.
  2135. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2136. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2137. const [isDropUploading, setIsDropUploading] = useState(false);
  2138. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2139. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2140. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2141. // inside the card would have to open upward into the card body; anchored to
  2142. // the viewport it escapes the card and the grid's scroll container both.
  2143. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2144. const dragCounterRef = useRef(0);
  2145. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2146. amsId: number;
  2147. amsLabel: string;
  2148. mode: 'humidity' | 'temperature';
  2149. } | null>(null);
  2150. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2151. initialKind: HeaterSensorKind;
  2152. availableKinds: HeaterSensorKind[];
  2153. } | null>(null);
  2154. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2155. tagUid: string;
  2156. trayUuid: string;
  2157. printerId: number;
  2158. amsId: number;
  2159. trayId: number;
  2160. } | null>(null);
  2161. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2162. printerId: number;
  2163. amsId: number;
  2164. trayId: number;
  2165. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2166. } | null>(null);
  2167. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2168. amsId: number;
  2169. trayId: number;
  2170. trayCount: number;
  2171. trayType?: string;
  2172. trayColor?: string;
  2173. traySubBrands?: string;
  2174. trayInfoIdx?: string;
  2175. extruderId?: number;
  2176. caliIdx?: number | null;
  2177. savedPresetId?: string;
  2178. } | null>(null);
  2179. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2180. const [plateCheckResult, setPlateCheckResult] = useState<{
  2181. is_empty: boolean;
  2182. confidence: number;
  2183. difference_percent: number;
  2184. message: string;
  2185. debug_image_url?: string;
  2186. needs_calibration: boolean;
  2187. light_warning?: boolean;
  2188. reference_count?: number;
  2189. max_references?: number;
  2190. roi?: { x: number; y: number; w: number; h: number };
  2191. } | null>(null);
  2192. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2193. const [isCalibrating, setIsCalibrating] = useState(false);
  2194. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2195. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2196. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2197. const { data: status } = useQuery({
  2198. queryKey: ['printerStatus', printer.id],
  2199. queryFn: () => api.getPrinterStatus(printer.id),
  2200. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2201. });
  2202. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2203. const { data: firmwareInfo } = useQuery({
  2204. queryKey: ['firmwareUpdate', printer.id],
  2205. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2206. staleTime: 5 * 60 * 1000,
  2207. refetchInterval: 5 * 60 * 1000,
  2208. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2209. });
  2210. // Collect unique tray_info_idx values for cloud filament info lookup
  2211. const trayInfoIds = useMemo(() => {
  2212. const ids = new Set<string>();
  2213. if (status?.ams) {
  2214. for (const ams of status.ams) {
  2215. for (const tray of ams.tray || []) {
  2216. if (tray.tray_info_idx) {
  2217. ids.add(tray.tray_info_idx);
  2218. }
  2219. }
  2220. }
  2221. }
  2222. for (const vt of status?.vt_tray ?? []) {
  2223. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2224. }
  2225. if (status?.nozzle_rack) {
  2226. for (const slot of status.nozzle_rack) {
  2227. if (slot.filament_id) {
  2228. ids.add(slot.filament_id);
  2229. }
  2230. }
  2231. }
  2232. return Array.from(ids);
  2233. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2234. // Collect loaded filament types for queue widget filtering
  2235. const loadedFilamentTypes = useMemo(() => {
  2236. const types = new Set<string>();
  2237. if (status?.ams) {
  2238. for (const ams of status.ams) {
  2239. for (const tray of ams.tray || []) {
  2240. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2241. }
  2242. }
  2243. }
  2244. for (const vt of status?.vt_tray ?? []) {
  2245. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2246. }
  2247. return types;
  2248. }, [status?.ams, status?.vt_tray]);
  2249. // Collect loaded filament type+color pairs for queue widget override matching
  2250. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2251. const loadedFilaments = useMemo(() => {
  2252. const filaments = new Set<string>();
  2253. if (status?.ams) {
  2254. for (const ams of status.ams) {
  2255. for (const tray of ams.tray || []) {
  2256. if (tray.tray_type && tray.tray_color) {
  2257. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2258. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2259. }
  2260. }
  2261. }
  2262. }
  2263. for (const vt of status?.vt_tray ?? []) {
  2264. if (vt.tray_type && vt.tray_color) {
  2265. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2266. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2267. }
  2268. }
  2269. return filaments;
  2270. }, [status?.ams, status?.vt_tray]);
  2271. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2272. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2273. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2274. const loadedVariants = useMemo(() => {
  2275. const variants = new Set<string>();
  2276. if (status?.ams) {
  2277. for (const ams of status.ams) {
  2278. for (const tray of ams.tray || []) {
  2279. if (tray.tray_type && tray.tray_color) {
  2280. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2281. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2282. }
  2283. }
  2284. }
  2285. }
  2286. for (const vt of status?.vt_tray ?? []) {
  2287. if (vt.tray_type && vt.tray_color) {
  2288. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2289. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2290. }
  2291. }
  2292. return variants;
  2293. }, [status?.ams, status?.vt_tray]);
  2294. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2295. const { data: filamentInfo } = useQuery({
  2296. queryKey: ['filamentInfo', trayInfoIds],
  2297. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2298. enabled: trayInfoIds.length > 0,
  2299. staleTime: 5 * 60 * 1000, // 5 minutes
  2300. });
  2301. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2302. const { data: slotPresets } = useQuery({
  2303. queryKey: ['slotPresets', printer.id],
  2304. queryFn: () => api.getSlotPresets(printer.id),
  2305. staleTime: 2 * 60 * 1000, // 2 minutes
  2306. });
  2307. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2308. // Only queried when there's a running print backed by an archive; shared
  2309. // React Query cache with the Queue / Archives pages keeps it cheap.
  2310. const activeArchiveId =
  2311. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2312. const { data: activeArchivePlates } = useQuery({
  2313. queryKey: ['archive-plates', activeArchiveId],
  2314. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2315. enabled: activeArchiveId != null,
  2316. staleTime: 5 * 60 * 1000,
  2317. });
  2318. const activePlateLabel = (() => {
  2319. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2320. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2321. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2322. })();
  2323. // Fetch user-defined AMS friendly names from the database
  2324. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2325. queryKey: ['amsLabels', printer.id],
  2326. queryFn: () => api.getAmsLabels(printer.id),
  2327. staleTime: 5 * 60 * 1000, // 5 minutes
  2328. });
  2329. // Cache WiFi signal to prevent it disappearing on updates
  2330. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2331. useEffect(() => {
  2332. if (status?.wifi_signal != null) {
  2333. setCachedWifiSignal(status.wifi_signal);
  2334. }
  2335. }, [status?.wifi_signal]);
  2336. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2337. // Cache connected state to prevent flicker when status briefly becomes undefined
  2338. const cachedConnected = useRef<boolean | undefined>(undefined);
  2339. useEffect(() => {
  2340. if (status?.connected !== undefined) {
  2341. cachedConnected.current = status.connected;
  2342. }
  2343. }, [status?.connected]);
  2344. const isConnected = status?.connected ?? cachedConnected.current;
  2345. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2346. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2347. useEffect(() => {
  2348. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2349. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2350. }
  2351. }, [status?.ams_extruder_map]);
  2352. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2353. ? status.ams_extruder_map
  2354. : cachedAmsExtruderMap.current;
  2355. // Same caching for the Filament Track Switch inlet bindings, for the same
  2356. // reason: a partial MQTT frame briefly empties the map and the badges would
  2357. // otherwise blink out.
  2358. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2359. useEffect(() => {
  2360. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2361. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2362. }
  2363. }, [status?.ams_switch_inlet]);
  2364. const ftsInstalled = status?.fila_switch?.installed === true;
  2365. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2366. ? status.ams_switch_inlet
  2367. : cachedAmsSwitchInlet.current;
  2368. // Cache AMS data to prevent it disappearing on idle/offline printers
  2369. const cachedAmsData = useRef<AMSUnit[]>([]);
  2370. useEffect(() => {
  2371. if (status?.ams && status.ams.length > 0) {
  2372. cachedAmsData.current = status.ams;
  2373. }
  2374. }, [status?.ams]);
  2375. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2376. // #2532: the K-profile line only exists on slots the printer has actually
  2377. // calibrated. The AMS units and the external-spool group are flex siblings in
  2378. // one row, so on a card that shows a value anywhere, the slots without one
  2379. // reserve the same height -- otherwise their fill bars sit a line above their
  2380. // neighbours'. A card with no calibrated slot at all is unaffected.
  2381. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2382. || (status?.vt_tray ?? []).some(tray => tray.k);
  2383. // Confirm a drying cycle actually started (#2533). Firmware answers
  2384. // ams_filament_drying with result=success even when it then silently declines,
  2385. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2386. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2387. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2388. // means the printer took the command and dropped it.
  2389. useEffect(() => {
  2390. if (!dryStartWatch) return;
  2391. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2392. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2393. }, [dryStartWatch, amsData]);
  2394. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2395. // otherwise rearm the timeout on every frame, so it would never elapse.
  2396. useEffect(() => {
  2397. if (!dryStartWatch) return;
  2398. const timer = setTimeout(() => {
  2399. setDryStartWatch(null);
  2400. showToast(t('printers.drying.toastNotStarted'), 'error');
  2401. }, DRY_START_CONFIRM_MS);
  2402. return () => clearTimeout(timer);
  2403. }, [dryStartWatch, showToast, t]);
  2404. // Cache tray_now to prevent flickering when undefined values come in
  2405. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2406. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2407. const cachedTrayNow = useRef<number | undefined>(undefined);
  2408. const currentTrayNow = status?.tray_now;
  2409. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2410. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2411. cachedTrayNow.current = currentTrayNow;
  2412. } else if (currentTrayNow === 255) {
  2413. cachedTrayNow.current = undefined;
  2414. }
  2415. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2416. ? currentTrayNow
  2417. : cachedTrayNow.current;
  2418. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2419. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2420. // expectedTray = the slot the firmware now expects filament in
  2421. // previousTray = the slot that ran out
  2422. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2423. // so these are often different — the graphic highlights the expected one.
  2424. const expectedTray = status?.expected_tray ?? null;
  2425. const previousTray = status?.previous_tray ?? null;
  2426. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2427. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2428. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2429. if (globalId === null) return null;
  2430. if (globalId === 254) return t('printers.expectedSlot.external');
  2431. if (globalId >= 128 && globalId <= 135) {
  2432. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2433. }
  2434. const amsId = Math.floor(globalId / 4);
  2435. const slot = globalId % 4;
  2436. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2437. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2438. };
  2439. const runoutGuidance = status?.state === 'PAUSE'
  2440. ? {
  2441. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2442. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2443. }
  2444. : null;
  2445. // Fetch smart plug for this printer
  2446. const { data: smartPlug } = useQuery({
  2447. queryKey: ['smartPlugByPrinter', printer.id],
  2448. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2449. });
  2450. // Fetch script plugs for this printer (for multi-device control)
  2451. const { data: scriptPlugs } = useQuery({
  2452. queryKey: ['scriptPlugsByPrinter', printer.id],
  2453. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2454. });
  2455. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2456. const { data: plugStatus } = useQuery({
  2457. queryKey: ['smartPlugStatus', smartPlug?.id],
  2458. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2459. enabled: !!smartPlug,
  2460. refetchInterval: 10000, // 10 seconds for real-time power display
  2461. });
  2462. // Fetch queue count for this printer
  2463. const { data: queueItems } = useQuery({
  2464. queryKey: ['queue', printer.id, 'pending'],
  2465. queryFn: () => api.getQueue(printer.id, 'pending'),
  2466. });
  2467. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2468. // so the badge only shows on printers that can actually run the queued jobs.
  2469. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2470. const queueCount = useMemo(() => {
  2471. if (!queueItems?.length) return 0;
  2472. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2473. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2474. // Fetch currently printing queue item to show who started it (Issue #206)
  2475. const { data: printingQueueItems } = useQuery({
  2476. queryKey: ['queue', printer.id, 'printing'],
  2477. queryFn: () => api.getQueue(printer.id, 'printing'),
  2478. enabled: status?.state === 'RUNNING',
  2479. });
  2480. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2481. const { data: reprintUser } = useQuery({
  2482. queryKey: ['currentPrintUser', printer.id],
  2483. queryFn: () => api.getCurrentPrintUser(printer.id),
  2484. enabled: status?.state === 'RUNNING',
  2485. });
  2486. // Combine both sources: queue item user takes precedence, then reprint user
  2487. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2488. // Fetch last completed print for this printer
  2489. const { data: lastPrints } = useQuery({
  2490. queryKey: ['archives', printer.id, 'last'],
  2491. queryFn: () => api.getArchives(printer.id, 1, 0),
  2492. enabled: status?.connected && status?.state !== 'RUNNING',
  2493. });
  2494. const lastPrint = lastPrints?.[0];
  2495. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2496. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2497. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2498. // gate is up and the just-finished print asked for a verdict, offer
  2499. // Good/Reject right where the operator releases the plate. Releasing the
  2500. // plate without answering stays possible — the two are orthogonal (though
  2501. // the confirm_default_good_on_plate_clear setting can couple them).
  2502. // Only offered to whoever may record it: the PATCH checks archives:update
  2503. // against the archive's owner, so for anyone else the pair could only fail.
  2504. const pendingConfirmArchive =
  2505. lastPrint &&
  2506. lastPrint.status === 'completed' &&
  2507. lastPrint.confirm_requested &&
  2508. lastPrint.user_verdict == null &&
  2509. canModify('archives', 'update', lastPrint.created_by_id)
  2510. ? lastPrint
  2511. : null;
  2512. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2513. // Auto Power Off the printer is powered down exactly when the operator clears the
  2514. // plate. Hiding the control there left no way to release the gate (#2864).
  2515. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2516. const activePrintName = status?.current_print && isPrintingOrPaused
  2517. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2518. : null;
  2519. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2520. useEffect(() => {
  2521. if (activePrintName) {
  2522. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2523. } else if (!needsPlateClear) {
  2524. setRetainedPrintJob(null);
  2525. }
  2526. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2527. const plateStatus = (() => {
  2528. // Connected-only because the pill's only render site sits inside the live-status
  2529. // panel. For a powered-down printer the plate-clear button itself carries the
  2530. // state — see the standalone slot below the status block (#2864).
  2531. if (!requirePlateClear || !status?.connected) return null;
  2532. if (isPrintingOrPaused) {
  2533. return {
  2534. label: t('printers.plateStatus.inUse'),
  2535. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2536. };
  2537. }
  2538. if (status.awaiting_plate_clear) {
  2539. return {
  2540. label: t('printers.plateStatus.notCleared'),
  2541. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2542. };
  2543. }
  2544. return {
  2545. label: t('printers.plateStatus.cleared'),
  2546. className: 'bg-status-ok/20 text-status-ok',
  2547. };
  2548. })();
  2549. const plateStatusPill = plateStatus ? (
  2550. <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}`}>
  2551. {plateStatus.label}
  2552. </span>
  2553. ) : null;
  2554. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2555. const shouldHide = hideIfDisconnected && isConnected === false;
  2556. const deleteMutation = useMutation({
  2557. mutationFn: (options: { deleteArchives: boolean }) =>
  2558. api.deletePrinter(printer.id, options.deleteArchives),
  2559. onSuccess: () => {
  2560. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2561. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2562. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2563. },
  2564. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2565. });
  2566. const connectMutation = useMutation({
  2567. mutationFn: () => api.connectPrinter(printer.id),
  2568. onSuccess: () => {
  2569. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2570. },
  2571. });
  2572. const forceRefreshMutation = useMutation({
  2573. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2574. onSuccess: () => {
  2575. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2576. showToast(t('printers.forceRefreshSuccess'), 'success');
  2577. },
  2578. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2579. });
  2580. const unlinkSpoolMutation = useMutation({
  2581. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2582. onSuccess: (result) => {
  2583. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2584. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2585. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2586. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2587. },
  2588. onError: (error: Error) => {
  2589. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2590. },
  2591. });
  2592. // AMS drying mutations
  2593. const startDryingMutation = useMutation({
  2594. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2595. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2596. onSuccess: (_data, { amsId }) => {
  2597. setDryingPopoverAmsId(null);
  2598. setDryStartWatch({ amsId });
  2599. // "Command sent", not "drying started" — at this point the printer has only
  2600. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2601. // the cycle is genuinely live; the watcher below covers the case where it
  2602. // never appears.
  2603. showToast(t('printers.drying.toastCommandSent'), 'success');
  2604. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2605. },
  2606. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2607. });
  2608. // Scheduled (delayed / at-time) drying runs (#2638)
  2609. const scheduleDryingMutation = useMutation({
  2610. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2611. api.createScheduledDrying({
  2612. printer_id: printer.id,
  2613. ams_id: params.amsId,
  2614. temp: params.temp,
  2615. duration_hours: params.duration,
  2616. filament: params.filament,
  2617. rotate_tray: params.rotateTray,
  2618. start_after: params.startAfter,
  2619. }),
  2620. onSuccess: () => {
  2621. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2622. setDryingPopoverAmsId(null);
  2623. },
  2624. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2625. });
  2626. const stopDryingMutation = useMutation({
  2627. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2628. onSuccess: () => {
  2629. setDryStartWatch(null);
  2630. showToast(t('printers.drying.toastStopped'), 'success');
  2631. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2632. },
  2633. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2634. });
  2635. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2636. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2637. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2638. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2639. // showing the old backup state until the user reopens it.
  2640. const setAmsBackupMutation = useMutation({
  2641. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2642. onSuccess: (_data, enabled) => {
  2643. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2644. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2645. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2646. },
  2647. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2648. });
  2649. // Smart plug control mutations
  2650. const powerControlMutation = useMutation({
  2651. mutationFn: (action: 'on' | 'off') =>
  2652. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2653. onSuccess: () => {
  2654. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2655. },
  2656. });
  2657. const toggleAutoOffMutation = useMutation({
  2658. mutationFn: (enabled: boolean) =>
  2659. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2660. onSuccess: () => {
  2661. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2662. // Also invalidate the smart-plugs list to keep Settings page in sync
  2663. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2664. },
  2665. });
  2666. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2667. const runScriptMutation = useMutation({
  2668. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2669. onSuccess: () => {
  2670. showToast(t('printers.toast.scriptTriggered'));
  2671. },
  2672. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2673. });
  2674. // Print control mutations
  2675. const stopPrintMutation = useMutation({
  2676. mutationFn: () => api.stopPrint(printer.id),
  2677. onSuccess: () => {
  2678. showToast(t('printers.toast.printStopped'));
  2679. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2680. },
  2681. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2682. });
  2683. const pausePrintMutation = useMutation({
  2684. mutationFn: () => api.pausePrint(printer.id),
  2685. onSuccess: () => {
  2686. showToast(t('printers.toast.printPaused'));
  2687. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2688. },
  2689. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2690. });
  2691. const resumePrintMutation = useMutation({
  2692. mutationFn: () => api.resumePrint(printer.id),
  2693. onSuccess: () => {
  2694. showToast(t('printers.toast.printResumed'));
  2695. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2696. },
  2697. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2698. });
  2699. const clearPlateMutation = useMutation({
  2700. mutationFn: () => api.clearPlate(printer.id),
  2701. onSuccess: () => {
  2702. showToast(t('queue.clearPlateSuccess'));
  2703. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2704. old ? { ...old, awaiting_plate_clear: false } : old
  2705. );
  2706. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2707. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2708. },
  2709. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2710. });
  2711. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2712. // reject goes through the dialog for the optional reason + reprint.
  2713. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2714. // Only "good" is answered on the card. A reject wants a reason and possibly
  2715. // a reprint, so that button opens the dialog instead — and the parameter
  2716. // says as much, rather than accepting a verdict this path cannot send and
  2717. // then reporting it as good.
  2718. const cardVerdictMutation = useMutation({
  2719. mutationFn: (verdict: 'good') =>
  2720. api.updateArchive(pendingConfirmArchive!.id, {
  2721. user_verdict: verdict,
  2722. user_verdict_source: 'printer_card',
  2723. }),
  2724. onSuccess: () => {
  2725. showToast(t('confirmOutcome.savedGood'), 'success');
  2726. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2727. },
  2728. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2729. });
  2730. // Rendered from two places: inside the live-status block for a connected printer,
  2731. // and standalone below it for a powered-down one, whose status block isn't rendered
  2732. // at all (#2864). Shared so the two can't drift apart.
  2733. const expandedClearPlateButton = (
  2734. <>
  2735. {pendingConfirmArchive && (
  2736. <div className="mt-2 flex items-center gap-1.5">
  2737. <span
  2738. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2739. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2740. >
  2741. {t('confirmOutcome.cardPrompt')}
  2742. </span>
  2743. <button
  2744. type="button"
  2745. onClick={() => setShowConfirmOutcome(true)}
  2746. disabled={cardVerdictMutation.isPending}
  2747. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2748. title={t('confirmOutcome.reject')}
  2749. >
  2750. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2751. </button>
  2752. <button
  2753. type="button"
  2754. onClick={() => cardVerdictMutation.mutate('good')}
  2755. disabled={cardVerdictMutation.isPending}
  2756. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2757. title={t('confirmOutcome.good')}
  2758. >
  2759. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2760. </button>
  2761. </div>
  2762. )}
  2763. <button
  2764. type="button"
  2765. onClick={() => clearPlateMutation.mutate()}
  2766. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2767. 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"
  2768. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2769. >
  2770. {clearPlateMutation.isPending ? (
  2771. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2772. ) : (
  2773. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2774. )}
  2775. {t('printers.plateStatus.markCleared')}
  2776. </button>
  2777. {showConfirmOutcome && pendingConfirmArchive && (
  2778. <ConfirmOutcomeDialog
  2779. archiveId={pendingConfirmArchive.id}
  2780. onClose={() => setShowConfirmOutcome(false)}
  2781. />
  2782. )}
  2783. </>
  2784. );
  2785. const nozzleTemperatureMutation = useMutation({
  2786. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2787. api.setNozzleTemperature(printer.id, target, nozzle),
  2788. onSuccess: (result) => {
  2789. setStatusControlMenu(null);
  2790. showToast(result.message);
  2791. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2792. },
  2793. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2794. });
  2795. const bedTemperatureMutation = useMutation({
  2796. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2797. onSuccess: (result) => {
  2798. setStatusControlMenu(null);
  2799. showToast(result.message);
  2800. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2801. },
  2802. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2803. });
  2804. const chamberTemperatureMutation = useMutation({
  2805. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2806. onSuccess: (result) => {
  2807. setStatusControlMenu(null);
  2808. showToast(result.message);
  2809. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2810. },
  2811. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2812. });
  2813. const fanSpeedMutation = useMutation({
  2814. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2815. api.setFanSpeed(printer.id, fan, speed),
  2816. onMutate: async ({ fan, speed }) => {
  2817. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2818. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2819. const fanField = {
  2820. part: 'cooling_fan_speed',
  2821. aux: 'big_fan1_speed',
  2822. aux2: 'left_aux_fan_speed',
  2823. chamber: 'big_fan2_speed',
  2824. }[fan];
  2825. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2826. old ? { ...old, [fanField]: speed } : old
  2827. );
  2828. return { previousStatus };
  2829. },
  2830. onSuccess: (result) => {
  2831. setStatusControlMenu(null);
  2832. showToast(result.message);
  2833. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2834. },
  2835. onError: (error: Error, _variables, context) => {
  2836. if (context?.previousStatus) {
  2837. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2838. }
  2839. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2840. },
  2841. });
  2842. const selectExtruderMutation = useMutation({
  2843. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2844. onMutate: async (extruder) => {
  2845. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2846. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2847. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2848. old ? { ...old, active_extruder: extruder } : old
  2849. );
  2850. return { previousStatus };
  2851. },
  2852. onSuccess: (result) => {
  2853. setStatusControlMenu(null);
  2854. showToast(result.message);
  2855. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2856. },
  2857. onError: (error: Error, _extruder, context) => {
  2858. if (context?.previousStatus) {
  2859. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2860. }
  2861. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2862. },
  2863. });
  2864. // Chamber light mutation with optimistic update
  2865. const chamberLightMutation = useMutation({
  2866. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2867. onMutate: async (on) => {
  2868. // Cancel any outgoing refetches
  2869. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2870. // Snapshot the previous value
  2871. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2872. // Optimistically update
  2873. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2874. ...old,
  2875. chamber_light: on,
  2876. }));
  2877. return { previousStatus };
  2878. },
  2879. onSuccess: (_, on) => {
  2880. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2881. },
  2882. onError: (error: Error, _, context) => {
  2883. // Rollback on error
  2884. if (context?.previousStatus) {
  2885. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2886. }
  2887. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2888. },
  2889. });
  2890. // Print speed mutation with optimistic update
  2891. const printSpeedMutation = useMutation({
  2892. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2893. onMutate: async (mode) => {
  2894. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2895. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2896. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2897. ...old,
  2898. speed_level: mode,
  2899. }));
  2900. return { previousStatus };
  2901. },
  2902. onError: (error: Error, _, context) => {
  2903. if (context?.previousStatus) {
  2904. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2905. }
  2906. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2907. },
  2908. });
  2909. const airductMutation = useMutation({
  2910. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2911. onMutate: async (mode) => {
  2912. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2913. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2914. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2915. ...old,
  2916. airduct_mode: mode === 'cooling' ? 0 : 1,
  2917. }));
  2918. return { previousStatus };
  2919. },
  2920. onError: (error: Error, _, context) => {
  2921. if (context?.previousStatus) {
  2922. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2923. }
  2924. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2925. },
  2926. });
  2927. const bedJogMutation = useMutation({
  2928. mutationFn: ({ distance }: { distance: number }) =>
  2929. api.bedJog(printer.id, distance),
  2930. onError: (error: Error) =>
  2931. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2932. });
  2933. const xyJogMutation = useMutation({
  2934. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2935. api.xyJog(printer.id, x, y),
  2936. onError: (error: Error) =>
  2937. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2938. });
  2939. const extruderJogMutation = useMutation({
  2940. mutationFn: (distance: number) =>
  2941. api.extruderJog(printer.id, distance),
  2942. onError: (error: Error) =>
  2943. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2944. });
  2945. const homeAxesMutation = useMutation({
  2946. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2947. onSuccess: () => {
  2948. showToast(t('printers.bedJog.homingStarted'));
  2949. },
  2950. onError: (error: Error) =>
  2951. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2952. });
  2953. // Plate detection setting mutation
  2954. const plateDetectionMutation = useMutation({
  2955. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2956. onSuccess: () => {
  2957. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2958. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2959. },
  2960. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2961. });
  2962. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2963. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2964. // metrics, and the print picker — so flipping this flag puts the printer
  2965. // out of service across every consumer in one place. Used from the
  2966. // overflow menu and EditPrinterModal.
  2967. const maintenanceMutation = useMutation({
  2968. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2969. onSuccess: (_data, isActive) => {
  2970. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2971. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2972. showToast(
  2973. isActive
  2974. ? t('printers.maintenance.toastExited', { name: printer.name })
  2975. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2976. 'success',
  2977. );
  2978. },
  2979. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2980. });
  2981. // Confirm before entering maintenance on a printing printer (entering mode
  2982. // disconnects MQTT, which stops progress tracking + completion notifications
  2983. // for the in-flight job).
  2984. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2985. const handleEnterMaintenance = () => {
  2986. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2987. setConfirmMaintenanceEnter(true);
  2988. } else {
  2989. maintenanceMutation.mutate(false);
  2990. }
  2991. };
  2992. // Query for printable objects (for skip functionality)
  2993. // Fetch when printing with 2+ objects OR when modal is open
  2994. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2995. const { data: objectsData } = useQuery({
  2996. queryKey: ['printableObjects', printer.id],
  2997. queryFn: () => api.getPrintableObjects(printer.id),
  2998. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2999. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  3000. });
  3001. // State for tracking which AMS slot is being refreshed
  3002. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  3003. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  3004. const seenBusyStateRef = useRef<boolean>(false);
  3005. // Fallback timeout ref
  3006. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3007. // Minimum display time passed
  3008. const minTimePassedRef = useRef<boolean>(false);
  3009. // AMS slot refresh mutation
  3010. const refreshAmsSlotMutation = useMutation({
  3011. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  3012. api.refreshAmsSlot(printer.id, amsId, slotId),
  3013. onMutate: ({ amsId, slotId }) => {
  3014. // Clear any existing timeout
  3015. if (refreshTimeoutRef.current) {
  3016. clearTimeout(refreshTimeoutRef.current);
  3017. }
  3018. // Reset state
  3019. seenBusyStateRef.current = false;
  3020. minTimePassedRef.current = false;
  3021. setRefreshingSlot({ amsId, slotId });
  3022. // Minimum display time (2 seconds)
  3023. setTimeout(() => {
  3024. minTimePassedRef.current = true;
  3025. }, 2000);
  3026. // Fallback timeout (30 seconds max)
  3027. refreshTimeoutRef.current = setTimeout(() => {
  3028. setRefreshingSlot(null);
  3029. }, 30000);
  3030. },
  3031. onSuccess: (data) => {
  3032. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  3033. },
  3034. onError: (error: Error) => {
  3035. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  3036. if (refreshTimeoutRef.current) {
  3037. clearTimeout(refreshTimeoutRef.current);
  3038. }
  3039. setRefreshingSlot(null);
  3040. },
  3041. });
  3042. // AMS load/unload mutations (#891)
  3043. const loadAmsTrayMutation = useMutation({
  3044. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  3045. api.loadAmsTray(printer.id, trayId, extruderId),
  3046. onSuccess: (data) => {
  3047. setFeedDirectionRequest(null);
  3048. showToast(data.message || t('printers.toast.loadInitiated'));
  3049. },
  3050. onError: (error: Error) => {
  3051. setFeedDirectionRequest(null);
  3052. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3053. },
  3054. });
  3055. const unloadAmsMutation = useMutation({
  3056. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3057. onSuccess: (data) => {
  3058. showToast(data.message || t('printers.toast.unloadInitiated'));
  3059. },
  3060. onError: (error: Error) => {
  3061. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3062. },
  3063. });
  3064. // Pending "which hotend?" question, non-null only while the dialog is open.
  3065. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3066. // load command has to name one — see FeedDirectionModal.
  3067. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3068. trayId: number;
  3069. amsId: number;
  3070. slotId: number;
  3071. slotLabel: string;
  3072. } | null>(null);
  3073. // Whether a load from this printer has to ask which hotend to feed.
  3074. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3075. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3076. // The external holder needs no question: its two tray ids name the side
  3077. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3078. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3079. // external spool, because it would occupy an extruder channel permanently.
  3080. //
  3081. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3082. // carries does not address an HT unit, so the load is refused whatever the
  3083. // answer. Asking first would only put a dialog in front of the same error.
  3084. const isExternal = amsId === 255;
  3085. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3086. loadAmsTrayMutation.mutate({ trayId });
  3087. return;
  3088. }
  3089. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3090. // front rather than sending a command the firmware will drop. BambuStudio
  3091. // shows the same message and returns without publishing anything.
  3092. if (!status?.fila_switch?.ready) {
  3093. showToast(t('printers.ams.switchNotReady'), 'warning');
  3094. return;
  3095. }
  3096. setFeedDirectionRequest({
  3097. trayId,
  3098. amsId,
  3099. slotId,
  3100. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3101. });
  3102. };
  3103. // Plate references state
  3104. const [plateReferences, setPlateReferences] = useState<{
  3105. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3106. max_references: number;
  3107. } | null>(null);
  3108. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3109. // Fetch plate references
  3110. const fetchPlateReferences = async () => {
  3111. try {
  3112. const data = await api.getPlateReferences(printer.id);
  3113. setPlateReferences(data);
  3114. } catch {
  3115. // Ignore errors - references will show as empty
  3116. }
  3117. };
  3118. // Toggle plate detection enabled/disabled
  3119. const handleTogglePlateDetection = () => {
  3120. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3121. };
  3122. // Open plate detection management modal (for calibration/references)
  3123. const handleOpenPlateManagement = async () => {
  3124. setIsCheckingPlate(true);
  3125. setPlateCheckResult(null);
  3126. // Auto-turn on light if it's off
  3127. const lightWasOff = status?.chamber_light === false;
  3128. setPlateCheckLightWasOff(lightWasOff);
  3129. if (lightWasOff) {
  3130. await api.setChamberLight(printer.id, true);
  3131. // Wait for light to physically turn on and camera to adjust exposure
  3132. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3133. await new Promise(resolve => setTimeout(resolve, 2500));
  3134. }
  3135. try {
  3136. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3137. setPlateCheckResult(result);
  3138. fetchPlateReferences();
  3139. } catch (error) {
  3140. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3141. // Restore light if check failed
  3142. if (lightWasOff) {
  3143. await api.setChamberLight(printer.id, false);
  3144. setPlateCheckLightWasOff(false);
  3145. }
  3146. } finally {
  3147. setIsCheckingPlate(false);
  3148. }
  3149. };
  3150. // Close plate check modal and restore light state
  3151. const closePlateCheckModal = useCallback(async () => {
  3152. setPlateCheckResult(null);
  3153. // Restore light to original state if we turned it on
  3154. if (plateCheckLightWasOff) {
  3155. await api.setChamberLight(printer.id, false);
  3156. setPlateCheckLightWasOff(false);
  3157. }
  3158. }, [plateCheckLightWasOff, printer.id]);
  3159. // Calibrate plate detection handler
  3160. const handleCalibratePlate = async (label?: string) => {
  3161. setIsCalibrating(true);
  3162. try {
  3163. const result = await api.calibratePlateDetection(printer.id, { label });
  3164. if (result.success) {
  3165. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3166. // Refresh references and re-check
  3167. fetchPlateReferences();
  3168. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3169. setPlateCheckResult(checkResult);
  3170. } else {
  3171. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3172. }
  3173. } catch (error) {
  3174. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3175. } finally {
  3176. setIsCalibrating(false);
  3177. }
  3178. };
  3179. // Update reference label
  3180. const handleUpdateRefLabel = async (index: number, label: string) => {
  3181. try {
  3182. await api.updatePlateReferenceLabel(printer.id, index, label);
  3183. setEditingRefLabel(null);
  3184. fetchPlateReferences();
  3185. } catch (error) {
  3186. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3187. }
  3188. };
  3189. // Delete reference
  3190. const handleDeleteRef = async (index: number) => {
  3191. try {
  3192. await api.deletePlateReference(printer.id, index);
  3193. showToast(t('printers.toast.referenceDeleted'), 'success');
  3194. fetchPlateReferences();
  3195. // Re-check to update counts
  3196. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3197. setPlateCheckResult(checkResult);
  3198. } catch (error) {
  3199. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3200. }
  3201. };
  3202. // Save ROI settings
  3203. const handleSaveRoi = async () => {
  3204. if (!editingRoi) return;
  3205. setIsSavingRoi(true);
  3206. try {
  3207. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3208. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3209. setEditingRoi(null);
  3210. // Re-check to see new ROI in action
  3211. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3212. setPlateCheckResult(checkResult);
  3213. } catch (error) {
  3214. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3215. } finally {
  3216. setIsSavingRoi(false);
  3217. }
  3218. };
  3219. // Close plate check modal on Escape key
  3220. useEffect(() => {
  3221. const handleEscape = (e: KeyboardEvent) => {
  3222. if (e.key === 'Escape' && plateCheckResult) {
  3223. closePlateCheckModal();
  3224. }
  3225. };
  3226. window.addEventListener('keydown', handleEscape);
  3227. return () => window.removeEventListener('keydown', handleEscape);
  3228. }, [plateCheckResult, closePlateCheckModal]);
  3229. // Watch ams_status_main to detect when RFID read completes
  3230. // ams_status_main: 0=idle, 2=rfid_identifying
  3231. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3232. useEffect(() => {
  3233. if (!refreshingSlot) return;
  3234. const amsStatus = status?.ams_status_main ?? 0;
  3235. // Track when we see non-idle state (printer is working)
  3236. if (amsStatus !== 0) {
  3237. seenBusyStateRef.current = true;
  3238. // Cancel any deferred clear since we're back to busy
  3239. if (deferredClearRef.current) {
  3240. clearTimeout(deferredClearRef.current);
  3241. deferredClearRef.current = null;
  3242. }
  3243. }
  3244. // When we've seen busy and now idle, clear (with min time check)
  3245. if (seenBusyStateRef.current && amsStatus === 0) {
  3246. if (minTimePassedRef.current) {
  3247. // Min time passed - clear now
  3248. if (refreshTimeoutRef.current) {
  3249. clearTimeout(refreshTimeoutRef.current);
  3250. }
  3251. setRefreshingSlot(null);
  3252. } else {
  3253. // Schedule clear after min time (2 seconds from start)
  3254. if (!deferredClearRef.current) {
  3255. deferredClearRef.current = setTimeout(() => {
  3256. if (refreshTimeoutRef.current) {
  3257. clearTimeout(refreshTimeoutRef.current);
  3258. }
  3259. setRefreshingSlot(null);
  3260. }, 2000);
  3261. }
  3262. }
  3263. }
  3264. return () => {
  3265. if (deferredClearRef.current) {
  3266. clearTimeout(deferredClearRef.current);
  3267. }
  3268. };
  3269. }, [status?.ams_status_main, refreshingSlot]);
  3270. useEffect(() => {
  3271. if (!showMenu) return;
  3272. const handleClickOutside = (event: MouseEvent) => {
  3273. const target = event.target as Node;
  3274. if (!printerActionsMenuRef.current?.contains(target)) {
  3275. setShowMenu(false);
  3276. }
  3277. };
  3278. document.addEventListener('mousedown', handleClickOutside);
  3279. return () => document.removeEventListener('mousedown', handleClickOutside);
  3280. }, [showMenu]);
  3281. if (shouldHide) {
  3282. return null;
  3283. }
  3284. // Size-based styling helpers
  3285. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3286. // width, its thumbnail and the printer name, but every label inside the
  3287. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3288. // S one -- the disparity was worst exactly where someone asking for more
  3289. // room ends up. These custom properties carry the scaled sizes into the
  3290. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3291. // unless they reach for a size that is already asking for more space.
  3292. // Plain computation rather than useMemo: this sits after the card's early
  3293. // returns, where a hook would break the rules-of-hooks ordering, and
  3294. // building ten strings per render costs nothing.
  3295. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3296. const getImageSize = () => {
  3297. switch (cardSize) {
  3298. case 1: return 'w-10 h-10';
  3299. case 2: return 'w-14 h-14';
  3300. case 3: return 'w-16 h-16';
  3301. case 4: return 'w-20 h-20';
  3302. default: return 'w-14 h-14';
  3303. }
  3304. };
  3305. const getTitleSize = () => {
  3306. switch (cardSize) {
  3307. case 1: return 'text-base truncate';
  3308. case 2: return 'text-lg';
  3309. case 3: return 'text-xl';
  3310. case 4: return 'text-2xl';
  3311. default: return 'text-lg';
  3312. }
  3313. };
  3314. const getSpacing = () => {
  3315. switch (cardSize) {
  3316. case 1: return 'mb-2';
  3317. case 2: return 'mb-4';
  3318. case 3: return 'mb-5';
  3319. case 4: return 'mb-6';
  3320. default: return 'mb-4';
  3321. }
  3322. };
  3323. // A dropped file always becomes a queue item, so a printer that is busy,
  3324. // offline or mid-drying is no reason to refuse the drop — it only means the
  3325. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3326. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3327. // what this would have done for them.
  3328. //
  3329. // What remains is what the flow actually performs: upload the file, then
  3330. // create a queue item. It never touches printers:control, which is what this
  3331. // used to check — so someone holding that but neither of these had the file
  3332. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3333. // button below has always checked this pair.
  3334. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3335. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3336. // and the modal's own "will start later" toast cannot disagree.
  3337. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3338. const handleCardDragEnter = (e: React.DragEvent) => {
  3339. e.preventDefault();
  3340. dragCounterRef.current++;
  3341. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3342. };
  3343. const handleCardDragOver = (e: React.DragEvent) => {
  3344. e.preventDefault();
  3345. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3346. };
  3347. const handleCardDragLeave = (e: React.DragEvent) => {
  3348. e.preventDefault();
  3349. dragCounterRef.current--;
  3350. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3351. };
  3352. const handleCardDrop = async (e: React.DragEvent) => {
  3353. e.preventDefault();
  3354. dragCounterRef.current = 0;
  3355. setIsDraggingFile(false);
  3356. if (!canDrop) return;
  3357. const droppedFiles = Array.from(e.dataTransfer.files);
  3358. const file = droppedFiles[0];
  3359. if (!file) return;
  3360. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3361. const lower = file.name.toLowerCase();
  3362. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3363. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3364. return;
  3365. }
  3366. setIsDropUploading(true);
  3367. try {
  3368. const result = await api.uploadLibraryFile(file, null);
  3369. // Check printer compatibility if sliced_for_model is available in metadata
  3370. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3371. const printerModel = mapModelCode(printer.model);
  3372. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3373. await api.deleteLibraryFile(result.id).catch(() => {});
  3374. showToast(
  3375. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3376. 'error'
  3377. );
  3378. return;
  3379. }
  3380. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3381. } catch {
  3382. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3383. } finally {
  3384. setIsDropUploading(false);
  3385. }
  3386. };
  3387. const handleCardClick = (e: React.MouseEvent) => {
  3388. if (viewMode !== 'compact' || selectionMode) return;
  3389. const target = e.target as HTMLElement;
  3390. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3391. onOpenCompactCard?.(printer.id);
  3392. };
  3393. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3394. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3395. // Opening a camera in a given mode, without touching which mode is remembered
  3396. // -- the split button's two halves want the same action but disagree about
  3397. // whether the choice was deliberate enough to keep.
  3398. const openCameraIn = (mode: CameraViewMode) => {
  3399. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3400. onOpenEmbeddedCamera(printer.id, printer.name);
  3401. } else {
  3402. openCameraWindow(printer.id);
  3403. }
  3404. };
  3405. // Picking a mode both opens the camera that way and makes it the mode the
  3406. // plain icon uses from now on. A menu that only changed a preference would
  3407. // leave the user with a second click to do the thing they already asked for.
  3408. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3409. [
  3410. {
  3411. mode: 'window' as const,
  3412. icon: <ExternalLink className="w-4 h-4" />,
  3413. label: t('settings.newWindow'),
  3414. title: t('settings.cameraWindowDescription'),
  3415. },
  3416. {
  3417. mode: 'embedded' as const,
  3418. icon: <PictureInPicture2 className="w-4 h-4" />,
  3419. label: t('settings.embeddedOverlay'),
  3420. title: t('settings.cameraOverlayDescription'),
  3421. },
  3422. ]
  3423. ).map(({ mode, icon, label, title }) => ({
  3424. icon,
  3425. // The remembered mode is marked in the label itself: the icon slot already
  3426. // carries the mode's own icon, and a separate tick column would push both
  3427. // entries out of line with every other card menu.
  3428. label: mode === cameraViewMode ? `${label} ✓` : label,
  3429. title,
  3430. onClick: () => {
  3431. onSelectCameraViewMode?.(mode);
  3432. openCameraIn(mode);
  3433. },
  3434. }));
  3435. const renderAmsSlotActions = ({
  3436. amsId,
  3437. slotId,
  3438. loadTrayId,
  3439. isRefreshing,
  3440. includeRfid = true,
  3441. }: {
  3442. amsId: number;
  3443. slotId: number;
  3444. loadTrayId: number;
  3445. isRefreshing?: boolean;
  3446. includeRfid?: boolean;
  3447. }) => {
  3448. const printerBusy = status?.state === 'RUNNING';
  3449. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3450. // ams*4+slot, so the id this menu carries does not name it to the load and
  3451. // unload endpoints — they reject it. Sending no slot falls back to the
  3452. // printer-wide unload, which is what this menu did for every slot before
  3453. // the per-slot form existed. Load has never worked on an HT slot for the
  3454. // same addressing reason; fixing that is a separate change.
  3455. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3456. return (
  3457. <>
  3458. {includeRfid && (
  3459. <button
  3460. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3461. hasPermission('printers:ams_rfid')
  3462. ? 'text-white hover:bg-bambu-dark-tertiary'
  3463. : 'text-bambu-gray/50 cursor-not-allowed'
  3464. }`}
  3465. onClick={(e) => {
  3466. e.stopPropagation();
  3467. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3468. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3469. }}
  3470. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3471. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3472. >
  3473. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3474. {t('printers.rfid.reread')}
  3475. </button>
  3476. )}
  3477. <button
  3478. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3479. hasPermission('printers:control')
  3480. ? 'text-white hover:bg-bambu-dark-tertiary'
  3481. : 'text-bambu-gray/50 cursor-not-allowed'
  3482. }`}
  3483. onClick={(e) => {
  3484. e.stopPropagation();
  3485. if (printerBusy || !hasPermission('printers:control')) return;
  3486. startAmsLoad(amsId, slotId, loadTrayId);
  3487. }}
  3488. disabled={printerBusy || !hasPermission('printers:control')}
  3489. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3490. >
  3491. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3492. {t('printers.ams.load')}
  3493. </button>
  3494. <button
  3495. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3496. hasPermission('printers:control')
  3497. ? 'text-white hover:bg-bambu-dark-tertiary'
  3498. : 'text-bambu-gray/50 cursor-not-allowed'
  3499. }`}
  3500. onClick={(e) => {
  3501. e.stopPropagation();
  3502. if (printerBusy || !hasPermission('printers:control')) return;
  3503. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3504. }}
  3505. disabled={printerBusy || !hasPermission('printers:control')}
  3506. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3507. >
  3508. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3509. {t('printers.ams.unload')}
  3510. </button>
  3511. </>
  3512. );
  3513. };
  3514. const printerActionsMenu = (
  3515. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3516. <Button
  3517. variant="secondary"
  3518. size="sm"
  3519. onClick={() => setShowMenu(!showMenu)}
  3520. title={t('common.more', 'More')}
  3521. className={footerIconButtonClass}
  3522. >
  3523. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3524. </Button>
  3525. {showMenu && (
  3526. <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">
  3527. <button
  3528. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3529. hasPermission('printers:update')
  3530. ? 'hover:bg-bambu-dark-tertiary'
  3531. : 'opacity-50 cursor-not-allowed'
  3532. }`}
  3533. onClick={() => {
  3534. if (!hasPermission('printers:update')) return;
  3535. setShowEditModal(true);
  3536. setShowMenu(false);
  3537. }}
  3538. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3539. >
  3540. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3541. {t('common.edit')}
  3542. </button>
  3543. <button
  3544. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3545. onClick={() => {
  3546. setShowPrinterInfo(true);
  3547. setShowMenu(false);
  3548. }}
  3549. >
  3550. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3551. {t('printers.printerInformation')}
  3552. </button>
  3553. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3554. <button
  3555. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3556. hasPermission('printers:update')
  3557. ? 'hover:bg-bambu-dark-tertiary'
  3558. : 'opacity-50 cursor-not-allowed'
  3559. }`}
  3560. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3561. onClick={() => {
  3562. if (!hasPermission('printers:update')) return;
  3563. setShowMenu(false);
  3564. if (printer.is_active !== false) {
  3565. handleEnterMaintenance();
  3566. } else {
  3567. maintenanceMutation.mutate(true);
  3568. }
  3569. }}
  3570. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3571. >
  3572. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3573. {printer.is_active !== false
  3574. ? t('printers.maintenance.menuEnter')
  3575. : t('printers.maintenance.menuExit')}
  3576. </button>
  3577. <button
  3578. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3579. onClick={() => {
  3580. connectMutation.mutate();
  3581. setShowMenu(false);
  3582. }}
  3583. >
  3584. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3585. {t('printers.reconnect')}
  3586. </button>
  3587. <button
  3588. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3589. disabled={forceRefreshMutation.isPending}
  3590. onClick={() => {
  3591. forceRefreshMutation.mutate();
  3592. setShowMenu(false);
  3593. }}
  3594. >
  3595. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3596. {t('printers.forceRefresh')}
  3597. </button>
  3598. <button
  3599. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3600. onClick={() => {
  3601. setShowMQTTDebug(true);
  3602. setShowMenu(false);
  3603. }}
  3604. >
  3605. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3606. {t('printers.mqttDebug')}
  3607. </button>
  3608. <button
  3609. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3610. onClick={() => {
  3611. setShowDiagnostic(true);
  3612. setShowMenu(false);
  3613. }}
  3614. >
  3615. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3616. {t('diagnostic.runButton')}
  3617. </button>
  3618. <button
  3619. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3620. hasPermission('printers:delete')
  3621. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3622. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3623. }`}
  3624. onClick={() => {
  3625. if (!hasPermission('printers:delete')) return;
  3626. setShowDeleteConfirm(true);
  3627. setShowMenu(false);
  3628. }}
  3629. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3630. >
  3631. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3632. {t('common.delete')}
  3633. </button>
  3634. </div>
  3635. )}
  3636. </div>
  3637. );
  3638. return (
  3639. <Card
  3640. id={`printer-card-${printer.id}`}
  3641. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3642. style={cardScaleStyle}
  3643. onClick={handleCardClick}
  3644. onDragEnter={handleCardDragEnter}
  3645. onDragOver={handleCardDragOver}
  3646. onDragLeave={handleCardDragLeave}
  3647. onDrop={handleCardDrop}
  3648. >
  3649. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3650. {selectionMode && (
  3651. <div
  3652. className="absolute inset-0 z-20 flex items-start p-2"
  3653. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3654. >
  3655. {isSelected ? (
  3656. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3657. ) : (
  3658. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3659. )}
  3660. </div>
  3661. )}
  3662. {/* Drop zone overlay */}
  3663. {(isDraggingFile || isDropUploading) && (
  3664. <div
  3665. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3666. isDropUploading
  3667. ? 'bg-bambu-green/10 border-bambu-green/50'
  3668. : canDrop
  3669. ? 'bg-bambu-green/10 border-bambu-green'
  3670. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3671. }`}
  3672. >
  3673. <div className="text-center">
  3674. {isDropUploading ? (
  3675. <>
  3676. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3677. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3678. </>
  3679. ) : canDrop ? (
  3680. <>
  3681. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3682. <p className="text-sm font-medium text-bambu-green">
  3683. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3684. </p>
  3685. </>
  3686. ) : (
  3687. <>
  3688. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3689. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3690. {!hasPermission('library:upload')
  3691. ? t('fileManager.noPermissionUpload')
  3692. : t('fileManager.noPermissionAddToQueue')}
  3693. </p>
  3694. </>
  3695. )}
  3696. </div>
  3697. </div>
  3698. )}
  3699. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3700. {/* Header */}
  3701. <div className={getSpacing()}>
  3702. {/* Top row: Image, Name, Menu */}
  3703. <div className="flex items-start justify-between gap-2">
  3704. <div className="flex items-center gap-3 min-w-0 flex-1">
  3705. {/* Printer Model Image */}
  3706. <img
  3707. src={getPrinterImage(printer.model)}
  3708. alt={printer.model || t('common.printer')}
  3709. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3710. />
  3711. <div className="min-w-0 flex-1">
  3712. <div className="flex items-center justify-between gap-2">
  3713. <div className="flex min-w-0 items-center gap-2">
  3714. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3715. {/* Connection indicator dot for compact mode */}
  3716. {viewMode === 'compact' && (() => {
  3717. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3718. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3719. const hasWarning = hmsErrors.length > 0;
  3720. const pipColor = !status?.connected
  3721. ? 'bg-status-error'
  3722. : hasSevere
  3723. ? 'bg-status-error'
  3724. : hasWarning
  3725. ? 'bg-status-warning'
  3726. : 'bg-status-ok';
  3727. const pipTitle = !status?.connected
  3728. ? t('printers.connection.offline')
  3729. : hasWarning
  3730. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3731. : t('printers.connection.connected');
  3732. return (
  3733. <div
  3734. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3735. title={pipTitle}
  3736. />
  3737. );
  3738. })()}
  3739. </div>
  3740. {viewMode === 'compact' && showClearPlateButton && (
  3741. <button
  3742. type="button"
  3743. onClick={() => clearPlateMutation.mutate()}
  3744. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3745. aria-label={t('printers.plateStatus.markCleared')}
  3746. 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"
  3747. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3748. >
  3749. {clearPlateMutation.isPending ? (
  3750. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3751. ) : (
  3752. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3753. )}
  3754. </button>
  3755. )}
  3756. </div>
  3757. <p className="text-sm text-bambu-gray">
  3758. {printer.model || 'Unknown Model'}
  3759. {/* Nozzle Info - only in expanded. Every fitted size, not
  3760. just nozzles[0]: the array is indexed by extruder, so on a
  3761. dual-nozzle machine with two sizes fitted showing the
  3762. first entry alone named one hotend and implied it was the
  3763. whole printer. Deduplicated, so the usual matching pair
  3764. still reads as a single "0.4mm". */}
  3765. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3766. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3767. • {installedNozzleDiameters(status).join(' / ')}mm
  3768. </span>
  3769. )}
  3770. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3771. <span className="ml-2 text-bambu-gray">
  3772. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3773. {Math.round(maintenanceInfo.total_print_hours)}h
  3774. </span>
  3775. )}
  3776. </p>
  3777. </div>
  3778. </div>
  3779. </div>
  3780. {/* Badges row - only in expanded mode */}
  3781. {viewMode === 'expanded' && (
  3782. <div className="mt-2">
  3783. <div className="flex flex-wrap items-center gap-2">
  3784. {/* Connection status badge (or Maintenance pill when out of service).
  3785. Defensive: only swap when is_active is EXPLICITLY false. An
  3786. undefined / missing field defaults to "active" so the regular
  3787. pill renders — matches the backend default and prevents test
  3788. fixtures (or stale clients) from accidentally tripping the
  3789. maintenance UI. */}
  3790. {printer.is_active === false ? (
  3791. <span
  3792. 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"
  3793. title={t('printers.maintenance.subtitle')}
  3794. >
  3795. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3796. {t('printers.maintenance.pillLabel')}
  3797. </span>
  3798. ) : (
  3799. <span
  3800. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3801. status?.connected
  3802. ? 'bg-status-ok/20 text-status-ok'
  3803. : 'bg-status-error/20 text-status-error'
  3804. }`}
  3805. >
  3806. {status?.connected ? (
  3807. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3808. ) : (
  3809. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3810. )}
  3811. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3812. </span>
  3813. )}
  3814. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3815. {printer.is_active !== false && !status?.connected && (
  3816. <button
  3817. onClick={() => setShowDiagnostic(true)}
  3818. 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"
  3819. title={t('diagnostic.runButton')}
  3820. >
  3821. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3822. {t('diagnostic.runButton')}
  3823. </button>
  3824. )}
  3825. {/* Network connection indicator */}
  3826. {status?.connected && status?.wired_network && (
  3827. <span
  3828. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3829. title={t('printers.connection.ethernet', 'Ethernet')}
  3830. >
  3831. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3832. {t('printers.connection.ethernet', 'Ethernet')}
  3833. </span>
  3834. )}
  3835. {/* WiFi signal indicator */}
  3836. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3837. <span
  3838. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3839. wifiSignal >= -50
  3840. ? 'bg-status-ok/20 text-status-ok'
  3841. : wifiSignal >= -60
  3842. ? 'bg-status-ok/20 text-status-ok'
  3843. : wifiSignal >= -70
  3844. ? 'bg-status-warning/20 text-status-warning'
  3845. : wifiSignal >= -80
  3846. ? 'bg-orange-500/20 text-orange-600'
  3847. : 'bg-status-error/20 text-status-error'
  3848. }`}
  3849. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3850. >
  3851. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3852. {wifiSignal}dBm
  3853. </span>
  3854. )}
  3855. {/* HMS Status Indicator */}
  3856. {status?.connected && (() => {
  3857. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3858. return (
  3859. <button
  3860. onClick={() => setShowHMSModal(true)}
  3861. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3862. knownErrors.length > 0
  3863. ? knownErrors.some(e => e.severity <= 2)
  3864. ? 'bg-status-error/20 text-status-error'
  3865. : 'bg-status-warning/20 text-status-warning'
  3866. : 'bg-status-ok/20 text-status-ok'
  3867. }`}
  3868. title={t('printers.clickToViewHmsErrors')}
  3869. >
  3870. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3871. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3872. </button>
  3873. );
  3874. })()}
  3875. {/* AI failure detection badge (#1546) — always shown while detection
  3876. is enabled for this printer, like the other health badges. Gray
  3877. "Idle" outside a monitored print, class-colored during one. */}
  3878. {aiDetectionEnabled && (() => {
  3879. const cls = aiDetectionClass(aiDetection);
  3880. const colorClass =
  3881. cls === 'failure'
  3882. ? 'bg-status-error/20 text-status-error'
  3883. : cls === 'warning'
  3884. ? 'bg-status-warning/20 text-status-warning'
  3885. : cls === 'safe'
  3886. ? 'bg-status-ok/20 text-status-ok'
  3887. : cls === 'error'
  3888. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3889. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3890. // 'error' and 'unknown' have no score to quote — saying
  3891. // "Safe (0.000)" for a print nothing is looking at is the
  3892. // whole of #2952.
  3893. const title =
  3894. cls === 'error'
  3895. ? t('printers.aiDetection.tooltipError', {
  3896. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3897. })
  3898. : cls === 'unknown'
  3899. ? t('printers.aiDetection.tooltipUnknown')
  3900. : aiDetection
  3901. ? t('printers.aiDetection.tooltip', {
  3902. status: t(`printers.aiDetection.${cls}`),
  3903. score: aiDetection.score.toFixed(3),
  3904. })
  3905. : t('printers.aiDetection.tooltipIdle');
  3906. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3907. return (
  3908. <button
  3909. onClick={() => setShowAiModal(true)}
  3910. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3911. title={title}
  3912. >
  3913. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3914. {t(`printers.aiDetection.${cls}`)}
  3915. </button>
  3916. );
  3917. })()}
  3918. {/* Maintenance Status Indicator */}
  3919. {maintenanceInfo && (
  3920. <button
  3921. onClick={() => navigate('/maintenance')}
  3922. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3923. maintenanceInfo.due_count > 0
  3924. ? 'bg-status-error/20 text-status-error'
  3925. : maintenanceInfo.warning_count > 0
  3926. ? 'bg-status-warning/20 text-status-warning'
  3927. : 'bg-status-ok/20 text-status-ok'
  3928. }`}
  3929. title={
  3930. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3931. ? `${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`
  3932. : t('printers.maintenanceUpToDate')
  3933. }
  3934. >
  3935. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3936. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3937. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3938. : 'OK'}
  3939. </button>
  3940. )}
  3941. {/* Queue Count Badge */}
  3942. {queueCount > 0 && (
  3943. <button
  3944. onClick={() => navigate('/queue')}
  3945. 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"
  3946. title={t('printers.queue.inQueue', { count: queueCount })}
  3947. >
  3948. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3949. {queueCount}
  3950. </button>
  3951. )}
  3952. {/* Firmware Version Badge */}
  3953. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3954. <button
  3955. onClick={() => setShowFirmwareModal(true)}
  3956. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3957. firmwareInfo.update_available
  3958. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3959. : 'bg-status-ok/20 text-status-ok'
  3960. }`}
  3961. title={
  3962. firmwareInfo.update_available
  3963. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3964. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3965. }
  3966. >
  3967. {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)]" />}
  3968. {firmwareInfo.current_version}
  3969. </button>
  3970. ) : status?.firmware_version ? (
  3971. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3972. {status.firmware_version}
  3973. </span>
  3974. ) : null}
  3975. {/* Enclosure Door Badge — models with an actual door sensor.
  3976. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3977. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3978. <span
  3979. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3980. status.door_open
  3981. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3982. : 'bg-status-ok/20 text-status-ok'
  3983. }`}
  3984. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3985. >
  3986. {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)]" />}
  3987. </span>
  3988. )}
  3989. </div>
  3990. </div>
  3991. )}
  3992. </div>
  3993. {/* Delete Confirmation */}
  3994. {showDeleteConfirm && (
  3995. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3996. <Card className="w-full max-w-md mx-4">
  3997. <CardContent>
  3998. <div className="flex items-start gap-3 mb-4">
  3999. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  4000. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  4001. </div>
  4002. <div>
  4003. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  4004. <p className="text-sm text-bambu-gray mt-1">
  4005. {t('printers.confirm.deleteMessage', { name: printer.name })}
  4006. </p>
  4007. </div>
  4008. </div>
  4009. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  4010. <label className="flex items-start gap-3 cursor-pointer">
  4011. <input
  4012. type="checkbox"
  4013. checked={deleteArchives}
  4014. onChange={(e) => setDeleteArchives(e.target.checked)}
  4015. 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"
  4016. />
  4017. <div>
  4018. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  4019. <p className="text-xs text-bambu-gray mt-0.5">
  4020. {deleteArchives
  4021. ? t('printers.confirm.deleteArchivesNote')
  4022. : t('printers.confirm.keepArchivesNote')}
  4023. </p>
  4024. </div>
  4025. </label>
  4026. </div>
  4027. <div className="flex justify-end gap-2">
  4028. <Button
  4029. variant="secondary"
  4030. onClick={() => {
  4031. setShowDeleteConfirm(false);
  4032. setDeleteArchives(true);
  4033. }}
  4034. >
  4035. {t('common.cancel')}
  4036. </Button>
  4037. <Button
  4038. variant="danger"
  4039. onClick={() => {
  4040. deleteMutation.mutate({ deleteArchives });
  4041. setShowDeleteConfirm(false);
  4042. setDeleteArchives(true);
  4043. }}
  4044. >
  4045. Delete
  4046. </Button>
  4047. </div>
  4048. </CardContent>
  4049. </Card>
  4050. </div>
  4051. )}
  4052. {/* Status — see the equivalent defensive `=== false` check on the
  4053. header pill above for why this is not `!printer.is_active`. */}
  4054. {printer.is_active === false ? (
  4055. // Maintenance mode (#1476) — replaces the cover/progress container
  4056. // so the card keeps the same height. Renders for both compact and
  4057. // expanded view modes so the printer stays visible but plainly
  4058. // out-of-service.
  4059. <>
  4060. {viewMode === 'compact' ? (
  4061. <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">
  4062. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4063. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4064. {t('printers.maintenance.pillLabel')}
  4065. </span>
  4066. </div>
  4067. ) : (
  4068. <>
  4069. <div className="flex items-center gap-2 mb-2">
  4070. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4071. {t('printers.status.title', 'Status')}
  4072. </span>
  4073. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4074. </div>
  4075. <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">
  4076. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4077. <div className="flex-1 min-w-0">
  4078. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4079. {t('printers.maintenance.title')}
  4080. </p>
  4081. <p className="text-xs text-bambu-gray mt-0.5">
  4082. {t('printers.maintenance.subtitle')}
  4083. </p>
  4084. </div>
  4085. <Button
  4086. variant="secondary"
  4087. size="sm"
  4088. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4089. onClick={() => maintenanceMutation.mutate(true)}
  4090. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4091. >
  4092. {t('printers.maintenance.exitButton')}
  4093. </Button>
  4094. </div>
  4095. </>
  4096. )}
  4097. </>
  4098. ) : status?.connected && (
  4099. <>
  4100. {/* Compact: Simple status bar */}
  4101. {viewMode === 'compact' ? (
  4102. (() => {
  4103. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4104. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4105. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4106. ? Math.max(0, Math.min(100, status.progress || 0))
  4107. : showClearPlateButton
  4108. ? 100
  4109. : hasProblem
  4110. ? 100
  4111. : 0;
  4112. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4113. const compactProgressClass = hasProblem
  4114. ? 'bg-status-error'
  4115. : status.state === 'PAUSE'
  4116. ? 'bg-status-warning'
  4117. : 'bg-bambu-green';
  4118. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4119. const hasCompactLayers =
  4120. isActiveCompactPrint &&
  4121. status.layer_num != null &&
  4122. status.total_layers != null &&
  4123. status.total_layers > 0;
  4124. return (
  4125. <>
  4126. <div className="relative mt-2 flex items-center gap-2">
  4127. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4128. <div
  4129. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4130. style={{ width: `${compactProgress}%` }}
  4131. />
  4132. </div>
  4133. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4134. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4135. </span>
  4136. </div>
  4137. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4138. enough to answer "which printer finishes first", which is what a
  4139. wall-mounted fleet view is for. One line of the metrics the
  4140. expanded card already renders, using the same formatters and the
  4141. same ETA styling so S and M read alike. The row keeps its height
  4142. when idle so cards don't shift as prints start and stop. */}
  4143. <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">
  4144. {hasCompactEta && (
  4145. <>
  4146. <span className="flex shrink-0 items-center gap-1">
  4147. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4148. {formatDuration(status.remaining_time! * 60)}
  4149. </span>
  4150. <span
  4151. className="shrink-0 font-medium text-bambu-green"
  4152. title={t('printers.estimatedCompletion')}
  4153. >
  4154. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4155. </span>
  4156. </>
  4157. )}
  4158. {hasCompactLayers && (
  4159. <span className="flex min-w-0 items-center gap-1 truncate">
  4160. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4161. {status.layer_num}/{status.total_layers}
  4162. </span>
  4163. )}
  4164. </div>
  4165. </>
  4166. );
  4167. })()
  4168. ) : (
  4169. /* Expanded: Full status section */
  4170. <>
  4171. <div className="flex items-center gap-2 mb-2">
  4172. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4173. {t('printers.status.title', 'Status')}
  4174. </span>
  4175. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4176. </div>
  4177. {/* Current Print or Idle Placeholder */}
  4178. {(() => {
  4179. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4180. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4181. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4182. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4183. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4184. // A running print always has at least one object, so a count of
  4185. // zero means "not loaded", not "nothing to skip" — after a
  4186. // restart mid-print the list is empty until something rebuilds
  4187. // it. Treating that as nothing-to-skip disabled the only
  4188. // control that opens the modal, and the modal's own fetch is
  4189. // what rebuilds the list, so the print could never get it back.
  4190. // Exactly one object is the real nothing-to-skip case.
  4191. const objectCount = status.printable_objects_count ?? 0;
  4192. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4193. return (
  4194. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4195. <button
  4196. onClick={() => setShowSkipObjectsModal(true)}
  4197. disabled={!canSkipObjects}
  4198. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4199. canSkipObjects
  4200. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4201. : 'text-bambu-gray/30 cursor-not-allowed'
  4202. }`}
  4203. title={
  4204. !hasPermission('printers:control')
  4205. ? t('printers.permission.noControl')
  4206. : !isActivePrint
  4207. ? t('printers.skipObjects.onlyWhilePrinting')
  4208. : objectCount === 1
  4209. ? t('printers.skipObjects.requiresMultiple')
  4210. : t('printers.skipObjects.tooltip')
  4211. }
  4212. >
  4213. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4214. {objectsData && objectsData.skipped_count > 0 && (
  4215. <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">
  4216. {objectsData.skipped_count}
  4217. </span>
  4218. )}
  4219. </button>
  4220. <div className="flex items-stretch gap-2">
  4221. <CoverImage
  4222. url={coverUrl}
  4223. printName={printName || undefined}
  4224. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4225. />
  4226. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4227. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4228. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4229. {plateStatusPill}
  4230. </div>
  4231. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4232. {printName || t('printers.noActiveJob', 'No active job')}
  4233. </p>
  4234. <div className="flex h-3 items-center gap-2 text-sm">
  4235. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4236. <div
  4237. 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`}
  4238. style={{ width: `${progress}%` }}
  4239. />
  4240. </div>
  4241. <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>
  4242. </div>
  4243. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4244. {isActivePrint ? (
  4245. <>
  4246. {status.remaining_time != null && status.remaining_time > 0 && (
  4247. <>
  4248. <span className="flex items-center gap-1">
  4249. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4250. {formatDuration(status.remaining_time * 60)}
  4251. </span>
  4252. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4253. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4254. </span>
  4255. </>
  4256. )}
  4257. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4258. <span className="flex items-center gap-1">
  4259. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4260. {status.layer_num}/{status.total_layers}
  4261. </span>
  4262. )}
  4263. {currentPrintUser && (
  4264. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4265. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4266. {currentPrintUser}
  4267. </span>
  4268. )}
  4269. </>
  4270. ) : lastPrint ? (
  4271. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4272. Last: {lastPrint.print_name || lastPrint.filename}
  4273. {lastPrint.completed_at && (
  4274. <span className="ml-1 text-bambu-gray/60">
  4275. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4276. </span>
  4277. )}
  4278. </p>
  4279. ) : (
  4280. <span>{t('printers.readyToPrint')}</span>
  4281. )}
  4282. </div>
  4283. </div>
  4284. </div>
  4285. <PrinterQueueWidget
  4286. printerId={printer.id}
  4287. printerModel={printer.model}
  4288. loadedFilamentTypes={loadedFilamentTypes}
  4289. loadedFilaments={loadedFilaments}
  4290. loadedVariants={loadedVariants}
  4291. variant="panelExtension"
  4292. />
  4293. </div>
  4294. );
  4295. })()}
  4296. </>
  4297. )}
  4298. {/* Temperatures */}
  4299. {status.temperatures && viewMode === 'expanded' && (() => {
  4300. // Use actual heater states from MQTT stream
  4301. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4302. const bedHeating = status.temperatures.bed_heating || false;
  4303. const chamberHeating = status.temperatures.chamber_heating || false;
  4304. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4305. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4306. const kinds: HeaterSensorKind[] = ['nozzle'];
  4307. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4308. kinds.push('bed');
  4309. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4310. return kinds;
  4311. })();
  4312. // active_extruder: 0=right, 1=left
  4313. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4314. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4315. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4316. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4317. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4318. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4319. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4320. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4321. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4322. 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 ${
  4323. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4324. }`;
  4325. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4326. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4327. // the widget there is at best dead UI and at worst suggests a
  4328. // control that does nothing. Mirrors the enclosure-door badge
  4329. // gate above.
  4330. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4331. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4332. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4333. // show it only when the printer actually reports it (airduct part id 3,
  4334. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4335. // have a built-in chamber fan that's always present, so they keep the
  4336. // existing model-list gate and the "Chamber Fan" label.
  4337. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4338. const chamberFanLabel = isExhaustModel
  4339. ? t('printers.fans.exhaust')
  4340. : t('printers.fans.chamber');
  4341. // Composed rather than either/or so both lists stay live for
  4342. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4343. // where that fan is an add-on kit — actually report it. Written
  4344. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4345. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4346. // which reads as if removing them were safe.
  4347. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4348. const fanItems: {
  4349. key: string;
  4350. label: string;
  4351. value: number;
  4352. Icon: typeof Fan;
  4353. activeClass: string;
  4354. }[] = [
  4355. {
  4356. key: 'part',
  4357. label: t('printers.fans.partCooling'),
  4358. value: status.cooling_fan_speed ?? 0,
  4359. Icon: Fan,
  4360. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4361. },
  4362. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4363. // Only reported (non-null) when the firmware lists airduct part
  4364. // id 10, i.e. when the fan is physically installed. Placed
  4365. // before the right-hand auxiliary fan so the two aux badges read
  4366. // left-to-right in the same order as the physical hardware.
  4367. ...(status.left_aux_fan_speed != null
  4368. ? [
  4369. {
  4370. key: 'aux2',
  4371. label: t('printers.fans.leftAuxiliary'),
  4372. value: status.left_aux_fan_speed,
  4373. Icon: Wind,
  4374. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4375. },
  4376. ]
  4377. : []),
  4378. {
  4379. key: 'aux',
  4380. label: t('printers.fans.auxiliary'),
  4381. value: status.big_fan1_speed ?? 0,
  4382. Icon: Wind,
  4383. activeClass: 'text-blue-600 dark:text-blue-400',
  4384. },
  4385. ...(showChamberFan
  4386. ? [
  4387. {
  4388. key: 'chamber',
  4389. label: chamberFanLabel,
  4390. value: status.big_fan2_speed ?? 0,
  4391. Icon: AirVent,
  4392. activeClass: 'text-green-600 dark:text-green-400',
  4393. },
  4394. ]
  4395. : []),
  4396. ];
  4397. return (
  4398. <>
  4399. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4400. {/* Nozzle temp - combined for dual nozzle */}
  4401. <div
  4402. className={statusControlClass}
  4403. title={statusControlTitle}
  4404. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4405. >
  4406. <button
  4407. type="button"
  4408. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4409. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4410. onClick={(e) => {
  4411. e.stopPropagation();
  4412. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4413. }}
  4414. >
  4415. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4416. </button>
  4417. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4418. {status.temperatures.nozzle_2 !== undefined ? (
  4419. <>
  4420. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4421. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4422. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4423. </p>
  4424. </>
  4425. ) : singleNozzleSlot ? (
  4426. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4427. <div className="cursor-default">
  4428. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4429. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4430. {Math.round(status.temperatures.nozzle || 0)}°C
  4431. </p>
  4432. </div>
  4433. </NozzleSlotHoverCard>
  4434. ) : (
  4435. <>
  4436. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4437. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4438. {Math.round(status.temperatures.nozzle || 0)}°C
  4439. </p>
  4440. </>
  4441. )}
  4442. {statusControlMenu === 'nozzle-temp' && (
  4443. isDualNozzle ? (
  4444. <IndicatorControlPopover
  4445. title="Set Nozzle Temperatures"
  4446. widthClass="w-[300px]"
  4447. popoverWidth={300}
  4448. popoverHeight={260}
  4449. isPending={nozzleTemperatureMutation.isPending}
  4450. onClose={() => setStatusControlMenu(null)}
  4451. >
  4452. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4453. <NozzleTemperatureControlBox
  4454. label="Left Temp"
  4455. current={status.temperatures.nozzle}
  4456. target={status.temperatures.nozzle_target}
  4457. isActive={activeNozzle === 'L'}
  4458. isPending={nozzleTemperatureMutation.isPending}
  4459. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4460. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4461. />
  4462. <NozzleTemperatureControlBox
  4463. label="Right Temp"
  4464. current={status.temperatures.nozzle_2}
  4465. target={status.temperatures.nozzle_2_target}
  4466. isActive={activeNozzle === 'R'}
  4467. isPending={nozzleTemperatureMutation.isPending}
  4468. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4469. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4470. />
  4471. </div>
  4472. </IndicatorControlPopover>
  4473. ) : (
  4474. <IndicatorControlPopover
  4475. title="Set Nozzle Temperature"
  4476. unit="°C"
  4477. customMin={0}
  4478. customMax={320}
  4479. isPending={nozzleTemperatureMutation.isPending}
  4480. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4481. onClose={() => setStatusControlMenu(null)}
  4482. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4483. />
  4484. )
  4485. )}
  4486. </div>
  4487. <div
  4488. className={statusControlClass}
  4489. title={statusControlTitle}
  4490. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4491. >
  4492. <button
  4493. type="button"
  4494. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4495. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4496. onClick={(e) => {
  4497. e.stopPropagation();
  4498. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4499. }}
  4500. >
  4501. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4502. </button>
  4503. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4504. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4505. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4506. {Math.round(status.temperatures.bed || 0)}°C
  4507. </p>
  4508. {statusControlMenu === 'bed-temp' && (
  4509. <IndicatorControlPopover
  4510. title="Set Bed Temperature"
  4511. unit="°C"
  4512. customMin={0}
  4513. customMax={140}
  4514. isPending={bedTemperatureMutation.isPending}
  4515. options={buildPresetOptions(bedTempPresets, 'C')}
  4516. onClose={() => setStatusControlMenu(null)}
  4517. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4518. />
  4519. )}
  4520. </div>
  4521. {status.temperatures.chamber !== undefined && (() => {
  4522. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4523. // but can't act on M141, so we keep the card read-only there.
  4524. const hasChamberHeater = status.supports_chamber_heater === true;
  4525. return (
  4526. <div
  4527. className={hasChamberHeater
  4528. ? statusControlClass
  4529. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4530. title={hasChamberHeater ? statusControlTitle : undefined}
  4531. onClick={hasChamberHeater
  4532. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4533. : undefined}
  4534. >
  4535. <button
  4536. type="button"
  4537. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4538. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4539. onClick={(e) => {
  4540. e.stopPropagation();
  4541. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4542. }}
  4543. >
  4544. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4545. </button>
  4546. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4547. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4548. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4549. {Math.round(status.temperatures.chamber || 0)}°C
  4550. </p>
  4551. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4552. <IndicatorControlPopover
  4553. title="Set Chamber Temperature"
  4554. unit="°C"
  4555. customMin={0}
  4556. customMax={MAX_CHAMBER_TEMP_C}
  4557. isPending={chamberTemperatureMutation.isPending}
  4558. options={buildPresetOptions(chamberTempPresets, 'C')}
  4559. onClose={() => setStatusControlMenu(null)}
  4560. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4561. />
  4562. )}
  4563. </div>
  4564. );
  4565. })()}
  4566. {/* Active nozzle indicator for dual-nozzle printers */}
  4567. {isDualNozzle && (
  4568. <DualNozzleHoverCard
  4569. leftSlot={leftNozzleSlot}
  4570. rightSlot={rightNozzleSlot}
  4571. activeNozzle={activeNozzle}
  4572. filamentInfo={filamentInfo}
  4573. >
  4574. <div
  4575. 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 ${
  4576. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4577. }`}
  4578. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4579. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4580. >
  4581. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4582. <div className="flex items-center gap-2">
  4583. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4584. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4585. </span>
  4586. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4587. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4588. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4589. </span>
  4590. </div>
  4591. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4592. {statusControlMenu === 'nozzle-select' && (
  4593. <IndicatorControlPopover
  4594. title="Set Nozzle Selection"
  4595. widthClass="w-[300px]"
  4596. popoverWidth={300}
  4597. popoverHeight={140}
  4598. isPending={selectExtruderMutation.isPending}
  4599. options={[
  4600. { label: 'Left', value: 1 },
  4601. { label: 'Right', value: 0 },
  4602. ]}
  4603. onClose={() => setStatusControlMenu(null)}
  4604. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4605. />
  4606. )}
  4607. </div>
  4608. </DualNozzleHoverCard>
  4609. )}
  4610. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4611. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4612. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4613. )}
  4614. </div>
  4615. <div className="mt-2 flex items-center gap-1.5">
  4616. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4617. const active = value > 0;
  4618. return (
  4619. <div
  4620. key={key}
  4621. 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 ${
  4622. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4623. }`}
  4624. title={canUseStatusControls ? label : statusControlTitle}
  4625. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4626. >
  4627. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4628. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4629. {value}%
  4630. </span>
  4631. {statusControlMenu === `fan-${key}` && (
  4632. <IndicatorControlPopover
  4633. title={`Set ${label} Speed`}
  4634. unit="%"
  4635. customMin={0}
  4636. customMax={100}
  4637. isPending={fanSpeedMutation.isPending}
  4638. options={buildPresetOptions(fanSpeedPresets, '%')}
  4639. onClose={() => setStatusControlMenu(null)}
  4640. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4641. />
  4642. )}
  4643. </div>
  4644. );
  4645. })}
  4646. </div>
  4647. </>
  4648. );
  4649. })()}
  4650. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4651. {/* Controls */}
  4652. {viewMode === 'expanded' && (() => {
  4653. // Determine print state for control buttons
  4654. const isRunning = status.state === 'RUNNING';
  4655. const isPaused = status.state === 'PAUSE';
  4656. const isPrinting = isRunning || isPaused;
  4657. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4658. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4659. 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';
  4660. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4661. return (
  4662. <div className="mt-3">
  4663. {/* Section Header */}
  4664. <div className="flex items-center gap-2 mb-2">
  4665. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4666. {t('printers.controls')}
  4667. </span>
  4668. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4669. </div>
  4670. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4671. {/* Left: Secondary controls */}
  4672. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4673. <button
  4674. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4675. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4676. className={`${iconControlClass} ${
  4677. status.chamber_light
  4678. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4679. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4680. }`}
  4681. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4682. >
  4683. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4684. </button>
  4685. {/* Airduct Mode (P2S / X2D / H2*) */}
  4686. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4687. const isHeating = status.airduct_mode === 1;
  4688. const Icon = isHeating ? Flame : Snowflake;
  4689. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4690. 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';
  4691. return (
  4692. <div className="relative">
  4693. <button
  4694. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4695. disabled={!hasPermission('printers:control')}
  4696. className={`${iconControlClass} ${bg}`}
  4697. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4698. >
  4699. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4700. </button>
  4701. {showAirductMenu === printer.id && (
  4702. <>
  4703. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4704. <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]">
  4705. {([
  4706. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4707. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4708. ] as const).map(({ mode, label, modeId }) => (
  4709. <button
  4710. key={mode}
  4711. onClick={() => {
  4712. airductMutation.mutate(mode);
  4713. setShowAirductMenu(null);
  4714. }}
  4715. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4716. status.airduct_mode === modeId
  4717. ? 'text-bambu-green bg-bambu-green/10'
  4718. : 'text-white hover:bg-bambu-dark-tertiary'
  4719. }`}
  4720. >
  4721. {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)]" />}
  4722. {label}
  4723. </button>
  4724. ))}
  4725. </div>
  4726. </>
  4727. )}
  4728. </div>
  4729. );
  4730. })()}
  4731. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4732. {(() => {
  4733. const canControl = hasPermission('printers:control');
  4734. const disabled = isPrinting || !canControl;
  4735. 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';
  4736. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4737. // nozzle-bed gap that means the same thing on every printer, so the
  4738. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4739. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4740. // plate toward the nozzle and closes it.
  4741. const zMovesToolhead = isBedSlinger(printer.model);
  4742. const requestZJog = (arrow: 'up' | 'down') => {
  4743. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4744. // No not-homed gate here, and no endstop bypass to gate either:
  4745. // since #2579 the jog is a bare move that never touches M211. That
  4746. // does not make it clamped — the firmware ignores soft endstops on
  4747. // MQTT G-code entirely, which is what the banner above warns about.
  4748. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4749. };
  4750. const requestXyJog = (x: number, y: number) => {
  4751. xyJogMutation.mutate({ x, y });
  4752. };
  4753. const requestExtruderJog = (distance: number) => {
  4754. extruderJogMutation.mutate(distance);
  4755. };
  4756. return (
  4757. <div className="relative">
  4758. <button
  4759. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4760. disabled={disabled}
  4761. className={`${iconControlClass} ${
  4762. disabled
  4763. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4764. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4765. }`}
  4766. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4767. >
  4768. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4769. </button>
  4770. {showBedJogMenu === printer.id && (
  4771. <>
  4772. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4773. <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">
  4774. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4775. {t('printers.bedJog.title')}
  4776. </div>
  4777. <div className="h-px bg-bambu-dark-tertiary" />
  4778. {/* #2579: Bambu firmware does not enforce soft endstops on
  4779. G-code sent over MQTT, so manual moves can drive past the
  4780. travel limits and cause a collision. Not fixable from our
  4781. side — warn prominently. */}
  4782. <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">
  4783. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4784. <span>{t('printers.bedJog.limitWarning')}</span>
  4785. </div>
  4786. <div className="h-px bg-bambu-dark-tertiary" />
  4787. <div className="flex justify-center px-3 py-2.5">
  4788. <div className="flex items-center justify-center gap-3">
  4789. <div className="grid grid-cols-3 gap-1">
  4790. <div />
  4791. <button
  4792. onClick={() => requestXyJog(0, bedJogStep)}
  4793. disabled={xyJogMutation.isPending}
  4794. className={jogButtonClass}
  4795. aria-label="Move Y forward"
  4796. >
  4797. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4798. </button>
  4799. <div />
  4800. <button
  4801. onClick={() => requestXyJog(-bedJogStep, 0)}
  4802. disabled={xyJogMutation.isPending}
  4803. className={jogButtonClass}
  4804. aria-label="Move X left"
  4805. >
  4806. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4807. </button>
  4808. <button
  4809. onClick={() => {
  4810. setShowBedJogMenu(null);
  4811. homeAxesMutation.mutate('all');
  4812. }}
  4813. disabled={homeAxesMutation.isPending}
  4814. className={jogButtonClass}
  4815. aria-label={t('printers.bedJog.homeZ')}
  4816. >
  4817. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4818. </button>
  4819. <button
  4820. onClick={() => requestXyJog(bedJogStep, 0)}
  4821. disabled={xyJogMutation.isPending}
  4822. className={jogButtonClass}
  4823. aria-label="Move X right"
  4824. >
  4825. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4826. </button>
  4827. <div />
  4828. <button
  4829. onClick={() => requestXyJog(0, -bedJogStep)}
  4830. disabled={xyJogMutation.isPending}
  4831. className={jogButtonClass}
  4832. aria-label="Move Y back"
  4833. >
  4834. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4835. </button>
  4836. <div />
  4837. </div>
  4838. <div className="flex flex-col items-center gap-1">
  4839. <button
  4840. onClick={() => requestZJog('up')}
  4841. disabled={bedJogMutation.isPending}
  4842. className={jogButtonClass}
  4843. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4844. >
  4845. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4846. </button>
  4847. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4848. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4849. </div>
  4850. <button
  4851. onClick={() => requestZJog('down')}
  4852. disabled={bedJogMutation.isPending}
  4853. className={jogButtonClass}
  4854. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4855. >
  4856. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4857. </button>
  4858. </div>
  4859. <div className="flex flex-col items-center gap-1">
  4860. <button
  4861. onClick={() => requestExtruderJog(-bedJogStep)}
  4862. disabled={extruderJogMutation.isPending}
  4863. className={jogButtonClass}
  4864. aria-label="Retract filament"
  4865. >
  4866. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4867. </button>
  4868. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4869. <span className="text-sm font-semibold leading-none">E</span>
  4870. </div>
  4871. <button
  4872. onClick={() => requestExtruderJog(bedJogStep)}
  4873. disabled={extruderJogMutation.isPending}
  4874. className={jogButtonClass}
  4875. aria-label="Extrude filament"
  4876. >
  4877. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4878. </button>
  4879. </div>
  4880. </div>
  4881. </div>
  4882. <div className="h-px bg-bambu-dark-tertiary" />
  4883. <div className="px-3 pt-2.5 pb-3">
  4884. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4885. {t('printers.bedJog.step')}
  4886. </div>
  4887. <div className="flex gap-1">
  4888. {[1, 10, 50].map((step) => (
  4889. <button
  4890. key={step}
  4891. onClick={() => setBedJogStep(step)}
  4892. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4893. bedJogStep === step
  4894. ? 'bg-bambu-green/20 text-bambu-green'
  4895. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4896. }`}
  4897. >
  4898. {step}
  4899. </button>
  4900. ))}
  4901. </div>
  4902. </div>
  4903. </div>
  4904. </>
  4905. )}
  4906. </div>
  4907. );
  4908. })()}
  4909. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4910. <button
  4911. onClick={handleTogglePlateDetection}
  4912. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4913. className={`${iconControlClass} rounded-r-none ${
  4914. printer.plate_detection_enabled
  4915. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4916. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4917. }`}
  4918. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4919. >
  4920. {plateDetectionMutation.isPending ? (
  4921. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4922. ) : (
  4923. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4924. )}
  4925. </button>
  4926. <button
  4927. onClick={handleOpenPlateManagement}
  4928. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4929. 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 ${
  4930. printer.plate_detection_enabled
  4931. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4932. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4933. }`}
  4934. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4935. >
  4936. {isCheckingPlate ? (
  4937. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4938. ) : (
  4939. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4940. )}
  4941. </button>
  4942. </div>
  4943. {/* Print Speed */}
  4944. {(() => (
  4945. <div className="relative">
  4946. <button
  4947. data-testid="speed-control"
  4948. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4949. disabled={!isPrinting || !hasPermission('printers:control')}
  4950. className={`${iconControlClass} ${
  4951. isPrinting
  4952. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4953. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4954. }`}
  4955. title={isPrinting ? t('printers.speed.title') : undefined}
  4956. >
  4957. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4958. </button>
  4959. {showSpeedMenu === printer.id && (
  4960. <>
  4961. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4962. <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]">
  4963. {([
  4964. { mode: 1, label: t('printers.speed.silent') },
  4965. { mode: 2, label: t('printers.speed.standard') },
  4966. { mode: 3, label: t('printers.speed.sport') },
  4967. { mode: 4, label: t('printers.speed.ludicrous') },
  4968. ] as const).map(({ mode, label }) => (
  4969. <button
  4970. key={mode}
  4971. onClick={() => {
  4972. printSpeedMutation.mutate(mode);
  4973. setShowSpeedMenu(null);
  4974. }}
  4975. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4976. status.speed_level === mode
  4977. ? 'text-bambu-green bg-bambu-green/10'
  4978. : 'text-white hover:bg-bambu-dark-tertiary'
  4979. }`}
  4980. >
  4981. {label}
  4982. </button>
  4983. ))}
  4984. </div>
  4985. </>
  4986. )}
  4987. </div>
  4988. ))()}
  4989. </div>
  4990. {/* Right: Print Control Buttons */}
  4991. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4992. {/* Pause/Resume button */}
  4993. {(() => {
  4994. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4995. return (
  4996. <button
  4997. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4998. disabled={pauseUnavailable}
  4999. className={`
  5000. ${printControlClass}
  5001. ${pauseUnavailable
  5002. ? unavailablePrintActionClass
  5003. : isPaused
  5004. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5005. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  5006. }
  5007. `}
  5008. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  5009. >
  5010. {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)]" />}
  5011. {isPaused ? t('printers.resume') : t('printers.pause')}
  5012. </button>
  5013. );
  5014. })()}
  5015. {/* Stop button */}
  5016. {(() => {
  5017. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  5018. return (
  5019. <button
  5020. onClick={() => setShowStopConfirm(true)}
  5021. disabled={stopUnavailable}
  5022. className={`
  5023. ${printControlClass}
  5024. ${stopUnavailable
  5025. ? unavailablePrintActionClass
  5026. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  5027. }
  5028. `}
  5029. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  5030. >
  5031. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5032. {t('printers.stop')}
  5033. </button>
  5034. );
  5035. })()}
  5036. </div>
  5037. </div>
  5038. </div>
  5039. );
  5040. })()}
  5041. {/* AMS Units - 2-Column Grid Layout */}
  5042. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  5043. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  5044. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  5045. const htAms = amsData.filter(ams => ams.tray.length === 1);
  5046. // The external spool can only be hidden while some AMS remains to
  5047. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  5048. // filament section, so the toggle is not offered there and a stored
  5049. // preference from a printer that later lost its AMS cannot blank the
  5050. // row either — both read through canHideExternalSpool.
  5051. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  5052. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5053. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5054. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5055. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5056. // floating point, and that lands verbatim in the DOM.
  5057. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5058. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5059. // already grow to fill the row, so the 3.5rem is a floor they sit
  5060. // well above in practice -- raising it just costs a unit its place
  5061. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5062. // its line, and flex-grow stretches its single slot across the whole
  5063. // card. The AMS-HT's own width does scale, below, because its
  5064. // readings sit beside the slot rather than under it.
  5065. const slotMinWidth = '3.5rem';
  5066. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5067. // The AMS-HT holds a single spool, and its slot is the only thing
  5068. // on that row able to grow -- so it swallowed every spare pixel and
  5069. // shoved the temperature and humidity hard against the card's edge.
  5070. // Capping it at roughly two ordinary slots keeps the readings clear
  5071. // of the edge; the cap scales because the text inside the slot does.
  5072. const htSlotStyle: React.CSSProperties = {
  5073. minWidth: slotMinWidth,
  5074. maxWidth: scaledRem(7.25),
  5075. };
  5076. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5077. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5078. });
  5079. // #1762 (comment 2): while a print is running/paused, overlay a small
  5080. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5081. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5082. // staged to a printer with mismatched filament: the wrong-slot pill
  5083. // is visible the instant printing starts.
  5084. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5085. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5086. ? status.ams_mapping
  5087. : [];
  5088. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5089. const boundedSlotCount = Math.max(1, slotCount);
  5090. const gapCount = Math.max(0, boundedSlotCount - 1);
  5091. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5092. return {
  5093. flex: `1 1 ${minWidth}`,
  5094. minWidth,
  5095. };
  5096. };
  5097. return (
  5098. <div className="mt-3">
  5099. {/* Section Header */}
  5100. <div className="flex items-center gap-2 mb-2">
  5101. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5102. {t('printers.filaments')}
  5103. </span>
  5104. <AmsBackupBadge
  5105. state={status.ams_filament_backup}
  5106. onClick={() => setAmsBackupModalOpen(true)}
  5107. />
  5108. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5109. {/* Offered only when an AMS is present: on a printer that
  5110. feeds from the external spool alone, hiding it would
  5111. empty the row entirely (#1782). */}
  5112. {canHideExternalSpool && (
  5113. <>
  5114. <ExternalSpoolToggle
  5115. hidden={externalSpoolHidden}
  5116. onClick={toggleExternalSpool}
  5117. />
  5118. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5119. </>
  5120. )}
  5121. </div>
  5122. {/* AMS Content */}
  5123. <div className="flex flex-wrap gap-2">
  5124. {/* Regular AMS units */}
  5125. {regularAms.map((ams) => {
  5126. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5127. return (
  5128. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5129. {/* Header: Label + Stats (no icon) */}
  5130. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5131. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5132. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5133. <AmsNameHoverCard
  5134. ams={ams}
  5135. printerId={printer.id}
  5136. label={getAmsLabel(ams.id, ams.tray.length)}
  5137. amsLabels={amsLabels}
  5138. canEdit={hasPermission('printers:update')}
  5139. onSaved={refetchAmsLabels}
  5140. >
  5141. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5142. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5143. </span>
  5144. </AmsNameHoverCard>
  5145. {sideBadge?.kind === 'inlet' ? (
  5146. <InletBadge
  5147. inlet={sideBadge.inlet}
  5148. title={t('printers.amsSwitchInletTooltip', {
  5149. inlet: sideBadge.inlet,
  5150. side: FTS_INLET_SIDE[sideBadge.inlet],
  5151. })}
  5152. />
  5153. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5154. <NozzleBadge side={sideBadge.side} />
  5155. ) : null}
  5156. </div>
  5157. {(ams.humidity != null || ams.temp != null) && (
  5158. <div className="flex shrink-0 items-center gap-1.5">
  5159. {ams.humidity != null && (
  5160. <HumidityIndicator
  5161. humidity={ams.humidity}
  5162. goodThreshold={amsThresholds?.humidityGood}
  5163. fairThreshold={amsThresholds?.humidityFair}
  5164. onClick={() => setAmsHistoryModal({
  5165. amsId: ams.id,
  5166. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5167. mode: 'humidity',
  5168. })}
  5169. compact
  5170. />
  5171. )}
  5172. {ams.temp != null && (
  5173. <div className="mr-1">
  5174. <TemperatureIndicator
  5175. temp={ams.temp}
  5176. goodThreshold={amsThresholds?.tempGood}
  5177. fairThreshold={amsThresholds?.tempFair}
  5178. onClick={() => setAmsHistoryModal({
  5179. amsId: ams.id,
  5180. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5181. mode: 'temperature',
  5182. })}
  5183. compact
  5184. />
  5185. </div>
  5186. )}
  5187. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5188. Screen-only models (P1 series) keep the control but can't
  5189. be commanded: it stays disabled and says why (#2533). */}
  5190. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5191. <button
  5192. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5193. onClick={(e) => {
  5194. if (ams.dry_time > 0) {
  5195. stopDryingMutation.mutate(ams.id);
  5196. } else if (dryingPopoverAmsId === ams.id) {
  5197. setDryingPopoverAmsId(null);
  5198. } else {
  5199. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5200. }
  5201. }}
  5202. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5203. ams.dry_time > 0
  5204. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5205. : status.drying_screen_only || ams.dry_sf_reason?.length
  5206. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5207. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5208. }`}
  5209. 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')}
  5210. >
  5211. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5212. </button>
  5213. )}
  5214. </div>
  5215. )}
  5216. </div>
  5217. {/* Drying status bar */}
  5218. {ams.dry_time > 0 && (
  5219. <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)]">
  5220. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5221. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5222. {/* The temperature is only ever known from the target we
  5223. cached when sending the command — the filament can also
  5224. be read off a uniformly loaded unit, so it can outlive
  5225. the temperature (#2759). */}
  5226. {ams.dry_filament && (
  5227. <span className="text-amber-700/80 dark:text-amber-300/70">
  5228. {ams.dry_target_temp != null
  5229. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5230. : ams.dry_filament}
  5231. </span>
  5232. )}
  5233. <span className="text-amber-700/80 dark:text-amber-300/70">
  5234. {t('printers.drying.timeRemaining', {
  5235. time: ams.dry_time >= 60
  5236. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5237. : `${ams.dry_time}m`
  5238. })}
  5239. </span>
  5240. {/* A cycle on a screen-only model was started at the printer
  5241. and can only be stopped there (#2533). */}
  5242. {!status.drying_screen_only && (
  5243. <button
  5244. onClick={() => stopDryingMutation.mutate(ams.id)}
  5245. disabled={stopDryingMutation.isPending}
  5246. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5247. title={t('printers.drying.stop')}
  5248. >
  5249. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5250. </button>
  5251. )}
  5252. </div>
  5253. )}
  5254. {/* Slots grid: 4 columns - always render 4 slots */}
  5255. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5256. {[0, 1, 2, 3].map((slotIdx) => {
  5257. // Find tray data for this slot (may be undefined if data incomplete)
  5258. // Use array index if available, as tray.id may not always be set
  5259. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5260. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5261. const isEmpty = !tray?.tray_type;
  5262. const emptyKind = getEmptySlotKind(tray);
  5263. // Check if this is the currently loaded tray
  5264. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5265. const globalTrayId = ams.id * 4 + slotIdx;
  5266. const isActive = effectiveTrayNow === globalTrayId;
  5267. // Runout guidance (#2587): the slot the paused print now
  5268. // expects filament in, and the slot that ran out.
  5269. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5270. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5271. // Get cloud preset info if available
  5272. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5273. // Get saved slot preset mapping (for user-configured slots)
  5274. const slotPreset = slotPresets?.[globalTrayId];
  5275. // Only trusted while it still describes what the printer reports in the
  5276. // slot: the row survives a spool swap, and the display chain below puts
  5277. // it ahead of the live filament id (see slotPresetDescribesTray).
  5278. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5279. ? slotPreset?.preset_name
  5280. : undefined;
  5281. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5282. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5283. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5284. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5285. // Slot-assigned-only spool fill (no tag link required)
  5286. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5287. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5288. : undefined;
  5289. const slotSpoolForFill = slotAssignmentForFill
  5290. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5291. : undefined;
  5292. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5293. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5294. : null;
  5295. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5296. const inventoryFill = (() => {
  5297. const sp = inventoryAssignment?.spool;
  5298. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5299. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5300. }
  5301. return null;
  5302. })();
  5303. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5304. // (inventory weight_used may be stale or over-counted — #676)
  5305. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5306. ? null : inventoryFill;
  5307. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5308. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5309. : resolvedInventoryFill !== null ? 'inventory' as const
  5310. : hasFillLevel ? 'ams' as const
  5311. : undefined;
  5312. // Build filament data for hover card
  5313. const filamentData = tray?.tray_type ? {
  5314. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5315. // Spoolman spool name wins over cloud lookup so a slot bound to
  5316. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5317. // Design PLA") instead of whatever the printer's filament_id
  5318. // resolves to in the cloud catalog (often "Generic PLA" for
  5319. // P-prefix local presets). Spoolman's filament.name is just the
  5320. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5321. // the hover card shows "Devil Design PLA Basic" rather than the
  5322. // vendor-less form. Strip the "@<printer>..." suffix that
  5323. // BambuStudio appends to user-preset names.
  5324. 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,
  5325. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5326. colorHex: tray.tray_color || null,
  5327. kFactor: formatKValue(tray.k),
  5328. fillLevel: effectiveFill,
  5329. trayUuid: tray.tray_uuid || null,
  5330. tagUid: tray.tag_uid || null,
  5331. fillSource,
  5332. } : null;
  5333. // Check if this specific slot is being refreshed
  5334. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5335. refreshingSlot?.slotId === slotIdx;
  5336. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5337. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5338. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5339. ? `P${activePrintSlotIdx + 1}`
  5340. : null;
  5341. // Slot visual content (goes inside hover card)
  5342. const slotVisual = (
  5343. <div
  5344. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5345. isExpectedSlot
  5346. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5347. : isRanOutSlot
  5348. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5349. : isActive
  5350. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5351. : ''
  5352. }`}
  5353. >
  5354. {isExpectedSlot && (
  5355. <span
  5356. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5357. title={t('printers.expectedSlot.title')}
  5358. 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"
  5359. >
  5360. ↓
  5361. </span>
  5362. )}
  5363. {activePrintSlotLabel && (
  5364. <span
  5365. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5366. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5367. 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"
  5368. >
  5369. {activePrintSlotLabel}
  5370. </span>
  5371. )}
  5372. {/* Filament color circle with 1-based slot number centered inside */}
  5373. <FilamentSlotCircle
  5374. trayColor={tray?.tray_color}
  5375. trayType={tray?.tray_type}
  5376. isEmpty={isEmpty}
  5377. emptyKind={emptyKind}
  5378. slotNumber={slotIdx + 1}
  5379. />
  5380. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5381. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5382. </div>
  5383. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5384. {/* Fill bar */}
  5385. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5386. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5387. <div
  5388. className="h-full rounded-full transition-all"
  5389. style={{
  5390. width: `${effectiveFill}%`,
  5391. backgroundColor: getFillBarColor(effectiveFill),
  5392. }}
  5393. />
  5394. )}
  5395. </div>
  5396. </div>
  5397. );
  5398. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5399. return (
  5400. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5401. {/* Loading overlay during RFID re-read */}
  5402. {isRefreshing && (
  5403. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5404. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5405. </div>
  5406. )}
  5407. {/* Hover card wraps only the visual content */}
  5408. {filamentData ? (
  5409. <FilamentHoverCard
  5410. data={filamentData}
  5411. actions={renderAmsSlotActions({
  5412. amsId: ams.id,
  5413. slotId: slotIdx,
  5414. loadTrayId: ams.id * 4 + slotIdx,
  5415. isRefreshing,
  5416. })}
  5417. spoolman={{
  5418. enabled: spoolmanEnabled,
  5419. // #1457: slot assignment is the user's most explicit action — it must
  5420. // outrank the tag-link, which can be stale when a non-RFID slot's
  5421. // fallback tag is still attached to a previous spool in Spoolman.
  5422. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5423. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5424. spoolmanUrl,
  5425. syncMode: spoolmanSyncMode,
  5426. // Suppress Link button when slot is already occupied by ANY assignment
  5427. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5428. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5429. // still appearing on slots with a local Devil Design PLA assigned.
  5430. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5431. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5432. setLinkSpoolModal({
  5433. tagUid: filamentData.tagUid || linkTag,
  5434. trayUuid: filamentData.trayUuid || '',
  5435. printerId: printer.id,
  5436. amsId: ams.id,
  5437. trayId: slotIdx,
  5438. });
  5439. } : undefined,
  5440. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5441. }}
  5442. inventory={(() => {
  5443. if (spoolmanEnabled) {
  5444. if (spoolmanLoading) return undefined;
  5445. const slotAssignment = slotAssignmentForFill;
  5446. const spoolmanSpool = slotSpoolForFill;
  5447. return {
  5448. assignedSpool: spoolmanSpool ? {
  5449. id: spoolmanSpool.id,
  5450. material: spoolmanSpool.material,
  5451. subtype: spoolmanSpool.subtype,
  5452. brand: spoolmanSpool.brand ?? null,
  5453. color_name: spoolmanSpool.color_name ?? null,
  5454. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5455. // The spool's own swatch (#2967). Spoolman carries the
  5456. // extra stops but has no effect field at all, so those
  5457. // rolls gradient and never shimmer.
  5458. rgba: spoolmanSpool.rgba ?? null,
  5459. extra_colors: spoolmanSpool.extra_colors ?? null,
  5460. effect_type: spoolmanSpool.effect_type ?? null,
  5461. remainingWeightGrams: spoolmanSpool.label_weight
  5462. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5463. : undefined,
  5464. } : null,
  5465. onAssignSpool: () => setAssignSpoolModal({
  5466. printerId: printer.id,
  5467. amsId: ams.id,
  5468. trayId: slotIdx,
  5469. trayInfo: {
  5470. type: tray?.tray_type || filamentData.profile,
  5471. material: tray?.tray_type ?? undefined,
  5472. profile: filamentData.profile,
  5473. color: filamentData.colorHex || '',
  5474. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5475. },
  5476. }),
  5477. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5478. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5479. };
  5480. }
  5481. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5482. return {
  5483. assignedSpool: assignment?.spool ? {
  5484. id: assignment.spool.id,
  5485. material: assignment.spool.material,
  5486. subtype: assignment.spool.subtype,
  5487. brand: assignment.spool.brand,
  5488. color_name: assignment.spool.color_name,
  5489. // The spool's own swatch (#2967).
  5490. rgba: assignment.spool.rgba ?? null,
  5491. extra_colors: assignment.spool.extra_colors ?? null,
  5492. effect_type: assignment.spool.effect_type ?? null,
  5493. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5494. } : null,
  5495. onAssignSpool: () => setAssignSpoolModal({
  5496. printerId: printer.id,
  5497. amsId: ams.id,
  5498. trayId: slotIdx,
  5499. trayInfo: {
  5500. type: tray?.tray_type || filamentData.profile,
  5501. material: tray?.tray_type ?? undefined,
  5502. profile: filamentData.profile,
  5503. color: filamentData.colorHex || '',
  5504. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5505. },
  5506. }),
  5507. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5508. isAssigned: !!assignment || isBambuLabSpool(tray),
  5509. };
  5510. })()}
  5511. configureSlot={{
  5512. enabled: hasPermission('printers:control'),
  5513. onConfigure: () => setConfigureSlotModal({
  5514. amsId: ams.id,
  5515. trayId: slotIdx,
  5516. trayCount: ams.tray.length,
  5517. trayType: tray?.tray_type || undefined,
  5518. trayColor: tray?.tray_color || undefined,
  5519. traySubBrands: tray?.tray_sub_brands || undefined,
  5520. trayInfoIdx: tray?.tray_info_idx || undefined,
  5521. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5522. caliIdx: tray?.cali_idx,
  5523. savedPresetId: slotPreset?.preset_id,
  5524. }),
  5525. }}
  5526. >
  5527. {slotVisual}
  5528. </FilamentHoverCard>
  5529. ) : (
  5530. <EmptySlotHoverCard
  5531. kind={emptyKind ?? undefined}
  5532. actions={renderAmsSlotActions({
  5533. amsId: ams.id,
  5534. slotId: slotIdx,
  5535. loadTrayId: ams.id * 4 + slotIdx,
  5536. isRefreshing,
  5537. })}
  5538. configureSlot={{
  5539. enabled: hasPermission('printers:control'),
  5540. onConfigure: () => setConfigureSlotModal({
  5541. amsId: ams.id,
  5542. trayId: slotIdx,
  5543. trayCount: ams.tray.length,
  5544. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5545. }),
  5546. }}
  5547. onAssignSpool={() => setAssignSpoolModal({
  5548. printerId: printer.id,
  5549. amsId: ams.id,
  5550. trayId: slotIdx,
  5551. trayInfo: {
  5552. type: '',
  5553. material: undefined,
  5554. profile: '',
  5555. color: '',
  5556. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5557. },
  5558. })}
  5559. >
  5560. {slotVisual}
  5561. </EmptySlotHoverCard>
  5562. )}
  5563. </div>
  5564. );
  5565. })}
  5566. </div>
  5567. </div>
  5568. );
  5569. })}
  5570. {/* HT AMS units */}
  5571. {htAms.map((ams) => {
  5572. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5573. const tray = ams.tray[0];
  5574. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5575. const isEmpty = !tray?.tray_type;
  5576. const emptyKind = getEmptySlotKind(tray);
  5577. // Check if this is the currently loaded tray
  5578. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5579. const isActive = effectiveTrayNow === globalTrayId;
  5580. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5581. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5582. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5583. // Get cloud preset info if available
  5584. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5585. // Get saved slot preset mapping (for user-configured slots)
  5586. const slotPreset = slotPresets?.[globalTrayId];
  5587. // Only trusted while it still describes what the printer reports in the
  5588. // slot: the row survives a spool swap, and the display chain below puts
  5589. // it ahead of the live filament id (see slotPresetDescribesTray).
  5590. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5591. ? slotPreset?.preset_name
  5592. : undefined;
  5593. const htSlotId = tray?.id ?? 0;
  5594. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5595. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5596. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5597. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5598. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5599. const htInventoryFill = (() => {
  5600. const sp = htInventoryAssignment?.spool;
  5601. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5602. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5603. }
  5604. return null;
  5605. })();
  5606. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5607. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5608. ? null : htInventoryFill;
  5609. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5610. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5611. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5612. : undefined;
  5613. const htSlotSpoolForFill = htSlotAssignmentForFill
  5614. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5615. : undefined;
  5616. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5617. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5618. : null;
  5619. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5620. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5621. : htResolvedInventoryFill !== null ? 'inventory' as const
  5622. : hasFillLevel ? 'ams' as const
  5623. : undefined;
  5624. // Build filament data for hover card
  5625. const filamentData = tray?.tray_type ? {
  5626. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5627. 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,
  5628. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5629. colorHex: tray.tray_color || null,
  5630. kFactor: formatKValue(tray.k),
  5631. fillLevel: htEffectiveFill,
  5632. trayUuid: tray.tray_uuid || null,
  5633. tagUid: tray.tag_uid || null,
  5634. fillSource: htFillSource,
  5635. } : null;
  5636. // Check if this specific slot is being refreshed
  5637. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5638. refreshingSlot?.slotId === htSlotId;
  5639. // #1762 (comment 2): active print-slot index for this HT slot.
  5640. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5641. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5642. ? `P${htActivePrintSlotIdx + 1}`
  5643. : null;
  5644. // Slot visual content (goes inside hover card)
  5645. const slotVisual = (
  5646. <div
  5647. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5648. isExpectedSlot
  5649. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5650. : isRanOutSlot
  5651. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5652. : isActive
  5653. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5654. : ''
  5655. }`}
  5656. >
  5657. {isExpectedSlot && (
  5658. <span
  5659. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5660. title={t('printers.expectedSlot.title')}
  5661. 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"
  5662. >
  5663. ↓
  5664. </span>
  5665. )}
  5666. {htActivePrintSlotLabel && (
  5667. <span
  5668. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5669. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5670. 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"
  5671. >
  5672. {htActivePrintSlotLabel}
  5673. </span>
  5674. )}
  5675. {/* Filament color circle with 1-based slot number centered inside */}
  5676. <FilamentSlotCircle
  5677. trayColor={tray?.tray_color}
  5678. trayType={tray?.tray_type}
  5679. isEmpty={isEmpty}
  5680. emptyKind={emptyKind}
  5681. slotNumber={1}
  5682. />
  5683. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5684. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5685. </div>
  5686. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5687. {/* Fill bar */}
  5688. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5689. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5690. <div
  5691. className="h-full rounded-full transition-all"
  5692. style={{
  5693. width: `${htEffectiveFill}%`,
  5694. backgroundColor: getFillBarColor(htEffectiveFill),
  5695. }}
  5696. />
  5697. )}
  5698. </div>
  5699. </div>
  5700. );
  5701. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5702. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5703. // Without this override, the L view squishes HT into a sliver next to the
  5704. // 4-slot AMS neighbors.
  5705. // 11rem holds one slot plus the temperature/humidity
  5706. // column beside it; both grow with the body scale.
  5707. const htCardWidth = scaledRem(11);
  5708. const htCardStyle: React.CSSProperties = {
  5709. flex: `1 1 ${htCardWidth}`,
  5710. minWidth: htCardWidth,
  5711. // An AMS-HT is never wider than a full AMS. Without a
  5712. // ceiling, a unit that wraps onto a line of its own is
  5713. // the only flex item there and grow stretches its single
  5714. // slot across the entire card, leaving the readings
  5715. // stranded at the far edge.
  5716. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5717. };
  5718. return (
  5719. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5720. {/* Row 1: Label + Nozzle + Drying */}
  5721. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5722. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5723. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5724. <AmsNameHoverCard
  5725. ams={ams}
  5726. printerId={printer.id}
  5727. label={getAmsLabel(ams.id, ams.tray.length)}
  5728. amsLabels={amsLabels}
  5729. canEdit={hasPermission('printers:update')}
  5730. onSaved={refetchAmsLabels}
  5731. >
  5732. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5733. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5734. </span>
  5735. </AmsNameHoverCard>
  5736. {sideBadge?.kind === 'inlet' ? (
  5737. <InletBadge
  5738. inlet={sideBadge.inlet}
  5739. title={t('printers.amsSwitchInletTooltip', {
  5740. inlet: sideBadge.inlet,
  5741. side: FTS_INLET_SIDE[sideBadge.inlet],
  5742. })}
  5743. />
  5744. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5745. <NozzleBadge side={sideBadge.side} />
  5746. ) : null}
  5747. </div>
  5748. {/* Drying button for HT AMS */}
  5749. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5750. <div className="relative ml-auto">
  5751. <button
  5752. disabled={status.drying_screen_only}
  5753. onClick={(e) => {
  5754. if (ams.dry_time > 0) {
  5755. stopDryingMutation.mutate(ams.id);
  5756. } else if (dryingPopoverAmsId === ams.id) {
  5757. setDryingPopoverAmsId(null);
  5758. } else {
  5759. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5760. }
  5761. }}
  5762. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5763. ams.dry_time > 0
  5764. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5765. : status.drying_screen_only
  5766. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5767. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5768. }`}
  5769. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5770. >
  5771. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5772. </button>
  5773. </div>
  5774. )}
  5775. </div>
  5776. {/* HT AMS drying status bar */}
  5777. {ams.dry_time > 0 && (
  5778. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
  5779. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5780. {ams.dry_filament && (
  5781. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5782. {ams.dry_target_temp != null
  5783. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5784. : ams.dry_filament}
  5785. </span>
  5786. )}
  5787. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5788. {ams.dry_time >= 60
  5789. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5790. : `${ams.dry_time}m`}
  5791. </span>
  5792. {!status.drying_screen_only && (
  5793. <button
  5794. onClick={() => stopDryingMutation.mutate(ams.id)}
  5795. disabled={stopDryingMutation.isPending}
  5796. 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"
  5797. title={t('printers.drying.stop')}
  5798. >
  5799. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5800. </button>
  5801. )}
  5802. </div>
  5803. )}
  5804. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5805. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5806. {/* Slot wrapper with loading overlay */}
  5807. <div className="relative group flex-1" style={htSlotStyle}>
  5808. {/* Loading overlay during RFID re-read */}
  5809. {isHtRefreshing && (
  5810. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5811. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5812. </div>
  5813. )}
  5814. {/* Hover card wraps only the visual content */}
  5815. {filamentData ? (
  5816. <FilamentHoverCard
  5817. data={filamentData}
  5818. actions={renderAmsSlotActions({
  5819. amsId: ams.id,
  5820. slotId: htSlotId,
  5821. loadTrayId: ams.id * 4 + htSlotId,
  5822. isRefreshing: isHtRefreshing,
  5823. })}
  5824. spoolman={{
  5825. enabled: spoolmanEnabled,
  5826. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5827. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5828. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5829. spoolmanUrl,
  5830. syncMode: spoolmanSyncMode,
  5831. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5832. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5833. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5834. setLinkSpoolModal({
  5835. tagUid: filamentData.tagUid || linkTag,
  5836. trayUuid: filamentData.trayUuid || '',
  5837. printerId: printer.id,
  5838. amsId: ams.id,
  5839. trayId: htSlotId,
  5840. });
  5841. } : undefined,
  5842. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5843. }}
  5844. inventory={(() => {
  5845. if (spoolmanEnabled) {
  5846. if (spoolmanLoading) return undefined;
  5847. const slotAssignment = htSlotAssignmentForFill;
  5848. const spoolmanSpool = htSlotSpoolForFill;
  5849. return {
  5850. assignedSpool: spoolmanSpool ? {
  5851. id: spoolmanSpool.id,
  5852. material: spoolmanSpool.material,
  5853. subtype: spoolmanSpool.subtype,
  5854. brand: spoolmanSpool.brand ?? null,
  5855. color_name: spoolmanSpool.color_name ?? null,
  5856. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5857. // The spool's own swatch (#2967). Spoolman carries the
  5858. // extra stops but has no effect field at all, so those
  5859. // rolls gradient and never shimmer.
  5860. rgba: spoolmanSpool.rgba ?? null,
  5861. extra_colors: spoolmanSpool.extra_colors ?? null,
  5862. effect_type: spoolmanSpool.effect_type ?? null,
  5863. remainingWeightGrams: spoolmanSpool.label_weight
  5864. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5865. : undefined,
  5866. } : null,
  5867. onAssignSpool: () => setAssignSpoolModal({
  5868. printerId: printer.id,
  5869. amsId: ams.id,
  5870. trayId: htSlotId,
  5871. trayInfo: {
  5872. type: tray?.tray_type || filamentData.profile,
  5873. material: tray?.tray_type ?? undefined,
  5874. profile: filamentData.profile,
  5875. color: filamentData.colorHex || '',
  5876. location: getAmsLabel(ams.id, ams.tray.length),
  5877. },
  5878. }),
  5879. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5880. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5881. };
  5882. }
  5883. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5884. return {
  5885. assignedSpool: assignment?.spool ? {
  5886. id: assignment.spool.id,
  5887. material: assignment.spool.material,
  5888. subtype: assignment.spool.subtype,
  5889. brand: assignment.spool.brand,
  5890. color_name: assignment.spool.color_name,
  5891. // The spool's own swatch (#2967).
  5892. rgba: assignment.spool.rgba ?? null,
  5893. extra_colors: assignment.spool.extra_colors ?? null,
  5894. effect_type: assignment.spool.effect_type ?? null,
  5895. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5896. } : null,
  5897. onAssignSpool: () => setAssignSpoolModal({
  5898. printerId: printer.id,
  5899. amsId: ams.id,
  5900. trayId: htSlotId,
  5901. trayInfo: {
  5902. type: tray?.tray_type || filamentData.profile,
  5903. material: tray?.tray_type ?? undefined,
  5904. profile: filamentData.profile,
  5905. color: filamentData.colorHex || '',
  5906. location: getAmsLabel(ams.id, ams.tray.length),
  5907. },
  5908. }),
  5909. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5910. isAssigned: !!assignment || isBambuLabSpool(tray),
  5911. };
  5912. })()}
  5913. configureSlot={{
  5914. enabled: hasPermission('printers:control'),
  5915. onConfigure: () => setConfigureSlotModal({
  5916. amsId: ams.id,
  5917. trayId: htSlotId,
  5918. trayCount: ams.tray.length,
  5919. trayType: tray?.tray_type || undefined,
  5920. trayColor: tray?.tray_color || undefined,
  5921. traySubBrands: tray?.tray_sub_brands || undefined,
  5922. trayInfoIdx: tray?.tray_info_idx || undefined,
  5923. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5924. caliIdx: tray?.cali_idx,
  5925. savedPresetId: slotPreset?.preset_id,
  5926. }),
  5927. }}
  5928. >
  5929. {slotVisual}
  5930. </FilamentHoverCard>
  5931. ) : (
  5932. <EmptySlotHoverCard
  5933. kind={emptyKind ?? undefined}
  5934. actions={renderAmsSlotActions({
  5935. amsId: ams.id,
  5936. slotId: htSlotId,
  5937. loadTrayId: ams.id * 4 + htSlotId,
  5938. isRefreshing: isHtRefreshing,
  5939. })}
  5940. configureSlot={{
  5941. enabled: hasPermission('printers:control'),
  5942. onConfigure: () => setConfigureSlotModal({
  5943. amsId: ams.id,
  5944. trayId: htSlotId,
  5945. trayCount: ams.tray.length,
  5946. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5947. }),
  5948. }}
  5949. onAssignSpool={() => setAssignSpoolModal({
  5950. printerId: printer.id,
  5951. amsId: ams.id,
  5952. trayId: htSlotId,
  5953. trayInfo: {
  5954. type: '',
  5955. material: undefined,
  5956. profile: '',
  5957. color: '',
  5958. location: getAmsLabel(ams.id, ams.tray.length),
  5959. },
  5960. })}
  5961. >
  5962. {slotVisual}
  5963. </EmptySlotHoverCard>
  5964. )}
  5965. </div>
  5966. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5967. {(ams.humidity != null || ams.temp != null) && (
  5968. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5969. {ams.temp != null && (
  5970. <TemperatureIndicator
  5971. temp={ams.temp}
  5972. goodThreshold={amsThresholds?.tempGood}
  5973. fairThreshold={amsThresholds?.tempFair}
  5974. onClick={() => setAmsHistoryModal({
  5975. amsId: ams.id,
  5976. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5977. mode: 'temperature',
  5978. })}
  5979. compact
  5980. />
  5981. )}
  5982. {ams.humidity != null && (
  5983. <HumidityIndicator
  5984. humidity={ams.humidity}
  5985. goodThreshold={amsThresholds?.humidityGood}
  5986. fairThreshold={amsThresholds?.humidityFair}
  5987. onClick={() => setAmsHistoryModal({
  5988. amsId: ams.id,
  5989. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5990. mode: 'humidity',
  5991. })}
  5992. compact
  5993. />
  5994. )}
  5995. </div>
  5996. )}
  5997. </div>
  5998. </div>
  5999. );
  6000. })}
  6001. {/* External spool(s) - grouped in one card like regular AMS */}
  6002. {status.vt_tray.length > 0 && showExternalSpool && (
  6003. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  6004. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  6005. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  6006. </div>
  6007. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  6008. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  6009. const extTrayId = extTray.id ?? 254;
  6010. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  6011. // generically — use active_extruder to determine L vs R:
  6012. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  6013. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  6014. ? (extTrayId === 254 && status.active_extruder === 1) ||
  6015. (extTrayId === 255 && status.active_extruder === 0)
  6016. : effectiveTrayNow === extTrayId;
  6017. const slotTrayId = extTrayId - 254; // 0 or 1
  6018. const extLabel = isDualNozzle
  6019. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6020. : '';
  6021. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6022. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6023. // Only trusted while it still describes what the printer reports in the
  6024. // slot: the row survives a spool swap, and the display chain below puts
  6025. // it ahead of the live filament id (see slotPresetDescribesTray).
  6026. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx)
  6027. ? extSlotPreset?.preset_name
  6028. : undefined;
  6029. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6030. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6031. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6032. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6033. const extInventoryFill = (() => {
  6034. const sp = extInventoryAssignment?.spool;
  6035. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6036. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6037. }
  6038. return null;
  6039. })();
  6040. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6041. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6042. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6043. ? null : extInventoryFill;
  6044. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6045. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6046. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6047. : undefined;
  6048. const extSlotSpoolForFill = extSlotAssignmentForFill
  6049. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6050. : undefined;
  6051. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6052. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6053. : null;
  6054. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6055. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6056. : extResolvedInventoryFill !== null ? 'inventory' as const
  6057. : extHasFillLevel ? 'ams' as const
  6058. : undefined;
  6059. const extFilamentData = {
  6060. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6061. 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',
  6062. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6063. colorHex: extTray.tray_color || null,
  6064. kFactor: formatKValue(extTray.k),
  6065. fillLevel: extEffectiveFill,
  6066. trayUuid: extTray.tray_uuid || null,
  6067. tagUid: extTray.tag_uid || null,
  6068. fillSource: extFillSource,
  6069. };
  6070. const isEmpty = !extTray.tray_type;
  6071. const emptyKind = getEmptySlotKind(extTray);
  6072. const extSlotContent = (
  6073. <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' : ''}`}>
  6074. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6075. the separate Ext-L/Ext-R caption that made the row taller than
  6076. regular AMS slots), 1-based slot number on single-nozzle. */}
  6077. <FilamentSlotCircle
  6078. trayColor={extTray.tray_color}
  6079. trayType={extTray.tray_type}
  6080. isEmpty={isEmpty}
  6081. emptyKind={emptyKind}
  6082. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6083. />
  6084. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6085. {extTray.tray_type || t('ams.slotEmpty')}
  6086. </div>
  6087. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6088. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6089. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6090. <div
  6091. className="h-full rounded-full transition-all"
  6092. style={{
  6093. width: `${extEffectiveFill}%`,
  6094. backgroundColor: getFillBarColor(extEffectiveFill),
  6095. }}
  6096. />
  6097. )}
  6098. </div>
  6099. </div>
  6100. );
  6101. return (
  6102. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6103. {!isEmpty ? (
  6104. <FilamentHoverCard
  6105. data={extFilamentData}
  6106. actions={renderAmsSlotActions({
  6107. amsId: 255,
  6108. slotId: slotTrayId,
  6109. loadTrayId: extTrayId,
  6110. includeRfid: false,
  6111. })}
  6112. spoolman={{
  6113. enabled: spoolmanEnabled,
  6114. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6115. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6116. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6117. spoolmanUrl,
  6118. syncMode: spoolmanSyncMode,
  6119. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6120. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6121. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6122. setLinkSpoolModal({
  6123. tagUid: extFilamentData.tagUid || linkTag,
  6124. trayUuid: extFilamentData.trayUuid || '',
  6125. printerId: printer.id,
  6126. amsId: 255,
  6127. trayId: slotTrayId,
  6128. });
  6129. } : undefined,
  6130. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6131. }}
  6132. inventory={(() => {
  6133. if (spoolmanEnabled) {
  6134. if (spoolmanLoading) return undefined;
  6135. const slotAssignment = extSlotAssignmentForFill;
  6136. const spoolmanSpool = extSlotSpoolForFill;
  6137. return {
  6138. assignedSpool: spoolmanSpool ? {
  6139. id: spoolmanSpool.id,
  6140. material: spoolmanSpool.material,
  6141. subtype: spoolmanSpool.subtype,
  6142. brand: spoolmanSpool.brand ?? null,
  6143. color_name: spoolmanSpool.color_name ?? null,
  6144. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6145. // The spool's own swatch (#2967). Spoolman carries the
  6146. // extra stops but has no effect field at all, so those
  6147. // rolls gradient and never shimmer.
  6148. rgba: spoolmanSpool.rgba ?? null,
  6149. extra_colors: spoolmanSpool.extra_colors ?? null,
  6150. effect_type: spoolmanSpool.effect_type ?? null,
  6151. remainingWeightGrams: spoolmanSpool.label_weight
  6152. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6153. : undefined,
  6154. } : null,
  6155. onAssignSpool: () => setAssignSpoolModal({
  6156. printerId: printer.id,
  6157. amsId: 255,
  6158. trayId: slotTrayId,
  6159. trayInfo: {
  6160. type: extTray.tray_type || extFilamentData.profile,
  6161. material: extTray.tray_type ?? undefined,
  6162. profile: extFilamentData.profile,
  6163. color: extFilamentData.colorHex || '',
  6164. location: extLabel || t('printers.external'),
  6165. },
  6166. }),
  6167. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6168. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6169. };
  6170. }
  6171. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6172. return {
  6173. assignedSpool: assignment?.spool ? {
  6174. id: assignment.spool.id,
  6175. material: assignment.spool.material,
  6176. subtype: assignment.spool.subtype,
  6177. brand: assignment.spool.brand,
  6178. color_name: assignment.spool.color_name,
  6179. // The spool's own swatch (#2967).
  6180. rgba: assignment.spool.rgba ?? null,
  6181. extra_colors: assignment.spool.extra_colors ?? null,
  6182. effect_type: assignment.spool.effect_type ?? null,
  6183. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6184. } : null,
  6185. onAssignSpool: () => setAssignSpoolModal({
  6186. printerId: printer.id,
  6187. amsId: 255,
  6188. trayId: slotTrayId,
  6189. trayInfo: {
  6190. type: extTray.tray_type || extFilamentData.profile,
  6191. material: extTray.tray_type ?? undefined,
  6192. profile: extFilamentData.profile,
  6193. color: extFilamentData.colorHex || '',
  6194. location: extLabel || t('printers.external'),
  6195. },
  6196. }),
  6197. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6198. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6199. };
  6200. })()}
  6201. configureSlot={{
  6202. enabled: hasPermission('printers:control'),
  6203. onConfigure: () => setConfigureSlotModal({
  6204. amsId: 255,
  6205. trayId: slotTrayId,
  6206. trayCount: 1,
  6207. trayType: extTray.tray_type || undefined,
  6208. trayColor: extTray.tray_color || undefined,
  6209. traySubBrands: extTray.tray_sub_brands || undefined,
  6210. trayInfoIdx: extTray.tray_info_idx || undefined,
  6211. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6212. caliIdx: extTray.cali_idx,
  6213. savedPresetId: extSlotPreset?.preset_id,
  6214. }),
  6215. }}
  6216. >
  6217. {extSlotContent}
  6218. </FilamentHoverCard>
  6219. ) : (
  6220. <EmptySlotHoverCard
  6221. kind={emptyKind ?? undefined}
  6222. actions={renderAmsSlotActions({
  6223. amsId: 255,
  6224. slotId: slotTrayId,
  6225. loadTrayId: extTrayId,
  6226. includeRfid: false,
  6227. })}
  6228. configureSlot={{
  6229. enabled: hasPermission('printers:control'),
  6230. onConfigure: () => setConfigureSlotModal({
  6231. amsId: 255,
  6232. trayId: slotTrayId,
  6233. trayCount: 1,
  6234. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6235. }),
  6236. }}
  6237. onAssignSpool={() => setAssignSpoolModal({
  6238. printerId: printer.id,
  6239. amsId: 255,
  6240. trayId: slotTrayId,
  6241. trayInfo: {
  6242. type: '',
  6243. material: undefined,
  6244. profile: '',
  6245. color: '',
  6246. location: `External Slot ${slotTrayId + 1}`,
  6247. },
  6248. })}
  6249. >
  6250. {extSlotContent}
  6251. </EmptySlotHoverCard>
  6252. )}
  6253. </div>
  6254. );
  6255. })}
  6256. </div>
  6257. </div>
  6258. )}
  6259. </div>
  6260. </div>
  6261. );
  6262. })()}
  6263. </>
  6264. )}
  6265. {/* Powered-down printer with a dirty plate: the status block above renders
  6266. nothing without a live connection, so the plate-clear control gets its own
  6267. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6268. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6269. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6270. expandedClearPlateButton
  6271. )}
  6272. {/* Bottom block (power row + action bar). Wrapped together so the
  6273. power row hugs the action bar at the card bottom instead of
  6274. floating up when there's less filament content above. */}
  6275. {viewMode === 'expanded' && (
  6276. <div className="mt-auto">
  6277. {smartPlug && (
  6278. <div className="pt-3">
  6279. <div className="flex items-center gap-2 mb-2">
  6280. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6281. {t('printers.power', 'Power')}
  6282. </span>
  6283. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6284. </div>
  6285. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6286. {/* Plug name + current power */}
  6287. <div className="flex items-center gap-2 min-w-0 pl-1">
  6288. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6289. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6290. <span
  6291. 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"
  6292. title={t('smartPlugs.power')}
  6293. >
  6294. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6295. </span>
  6296. </div>
  6297. {/* Spacer */}
  6298. <div className="flex-1" />
  6299. <div className="flex items-center gap-2">
  6300. {/* Auto-off */}
  6301. <button
  6302. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6303. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6304. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6305. 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 ${
  6306. !hasPermission('smart_plugs:control')
  6307. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6308. : smartPlug.auto_off || smartPlug.auto_off_executed
  6309. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6310. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6311. }`}
  6312. >
  6313. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6314. </button>
  6315. <button
  6316. onClick={() => {
  6317. if (plugStatus?.state === 'ON') {
  6318. setShowPowerOffConfirm(true);
  6319. } else {
  6320. setShowPowerOnConfirm(true);
  6321. }
  6322. }}
  6323. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6324. 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 ${
  6325. !hasPermission('smart_plugs:control')
  6326. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6327. : plugStatus?.state === 'ON'
  6328. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6329. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6330. }`}
  6331. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6332. >
  6333. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6334. </button>
  6335. </div>
  6336. </div>
  6337. {/* HA entity buttons row */}
  6338. {scriptPlugs && scriptPlugs.length > 0 && (
  6339. <div className="flex items-center gap-2 mt-2">
  6340. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6341. <span className="text-xs text-bambu-gray">HA:</span>
  6342. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6343. <div className="flex flex-wrap gap-1">
  6344. {scriptPlugs.map(script => {
  6345. const isScript = script.ha_entity_id?.startsWith('script.');
  6346. return (
  6347. <button
  6348. key={script.id}
  6349. onClick={() => {
  6350. if (isScript) {
  6351. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6352. } else {
  6353. setHaToggleConfirm(script);
  6354. }
  6355. }}
  6356. disabled={runScriptMutation.isPending}
  6357. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6358. 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"
  6359. >
  6360. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6361. {script.name}
  6362. </button>
  6363. );
  6364. })}
  6365. </div>
  6366. </div>
  6367. )}
  6368. </div>
  6369. )}
  6370. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6371. a printer can have an enclosure door contact without having a plug,
  6372. and nesting it there would hide the row on exactly those setups. */}
  6373. <PrinterHASensorRow printerId={printer.id} />
  6374. {/* Connection Info & Actions */}
  6375. <div className="pt-4">
  6376. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6377. <div className="flex items-center justify-between gap-2">
  6378. {printerActionsMenu}
  6379. <div className="flex items-center justify-end gap-2 flex-wrap">
  6380. {/* Camera split button: the icon opens whichever view was used
  6381. last, the caret picks between the two and remembers it.
  6382. Replaces the old Settings > General > Camera switch, which
  6383. made choosing between an overlay and a window a trip to
  6384. another page for something you decide per camera. */}
  6385. <div className="flex items-center flex-shrink-0">
  6386. <Button
  6387. variant="secondary"
  6388. size="sm"
  6389. onClick={() => openCameraIn(cameraViewMode)}
  6390. disabled={!status?.connected || !hasPermission('camera:view')}
  6391. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6392. className={`${footerIconButtonClass} !rounded-r-none`}
  6393. >
  6394. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6395. </Button>
  6396. <Button
  6397. variant="secondary"
  6398. size="sm"
  6399. onClick={(e) => {
  6400. // No open/close toggle: the menu's own outside-mousedown
  6401. // handler has already dismissed it by the time this lands.
  6402. const rect = e.currentTarget.getBoundingClientRect();
  6403. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6404. }}
  6405. disabled={!status?.connected || !hasPermission('camera:view')}
  6406. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6407. aria-label={t('settings.cameraViewMode')}
  6408. // Not footerIconButtonClass plus an override: both widths
  6409. // would carry !important and the stylesheet's own order,
  6410. // not this one, would decide which won.
  6411. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6412. >
  6413. <ChevronDown className="w-3 h-3" />
  6414. </Button>
  6415. </div>
  6416. {cameraMenuAnchor && (
  6417. <ContextMenu
  6418. x={cameraMenuAnchor.x}
  6419. y={cameraMenuAnchor.y}
  6420. items={cameraViewModeMenuItems}
  6421. onClose={() => setCameraMenuAnchor(null)}
  6422. />
  6423. )}
  6424. <Button
  6425. variant="secondary"
  6426. size="sm"
  6427. onClick={() => setShowFileManager(true)}
  6428. disabled={!hasPermission('printers:files')}
  6429. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6430. className={footerIconButtonClass}
  6431. >
  6432. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6433. </Button>
  6434. {/* Shown whatever the printer is doing (#2849): this uploads a
  6435. file and queues it, which a busy or offline printer is no
  6436. reason to refuse -- it only means the item waits. Hiding it
  6437. while the drop zone accepted the same file would have left
  6438. the two routes into this flow disagreeing. */}
  6439. <Button
  6440. size="sm"
  6441. onClick={() => setShowUploadForPrint(true)}
  6442. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6443. title={
  6444. !hasPermission('library:upload')
  6445. ? t('fileManager.noPermissionUpload')
  6446. : !hasPermission('queue:create')
  6447. ? t('fileManager.noPermissionAddToQueue')
  6448. : t('common.print')
  6449. }
  6450. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6451. >
  6452. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6453. {t('common.print')}
  6454. </Button>
  6455. </div>
  6456. </div>
  6457. </div>
  6458. </div>
  6459. )}
  6460. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6461. card's horizontal padding instead of running full-bleed into the
  6462. rounded bottom edge. */}
  6463. <ScheduledDryingBanner
  6464. printerId={printer.id}
  6465. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6466. timeFormat={timeFormat}
  6467. />
  6468. </CardContent>
  6469. {/* File Manager Modal */}
  6470. {showFileManager && (
  6471. <FileManagerModal
  6472. printerId={printer.id}
  6473. printerName={printer.name}
  6474. onClose={() => setShowFileManager(false)}
  6475. />
  6476. )}
  6477. {/* Upload for Print Modal */}
  6478. {showUploadForPrint && (
  6479. <FileUploadModal
  6480. folderId={null}
  6481. onClose={() => setShowUploadForPrint(false)}
  6482. onUploadComplete={() => {}}
  6483. autoUpload
  6484. accept=".gcode,.3mf"
  6485. validateFile={(file) => {
  6486. const lower = file.name.toLowerCase();
  6487. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6488. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6489. }
  6490. }}
  6491. onFileUploaded={(uploadedFile) => {
  6492. // Check printer compatibility if sliced_for_model is available in metadata
  6493. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6494. const printerModel = mapModelCode(printer.model);
  6495. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6496. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6497. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6498. }
  6499. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6500. }}
  6501. />
  6502. )}
  6503. {/* Print Modal (after upload) */}
  6504. {printAfterUpload && (
  6505. <PrintModal
  6506. mode="create"
  6507. libraryFileId={printAfterUpload.id}
  6508. archiveName={printAfterUpload.filename}
  6509. initialSelectedPrinterIds={[printer.id]}
  6510. onClose={() => setPrintAfterUpload(null)}
  6511. onSuccess={() => setPrintAfterUpload(null)}
  6512. cleanupLibraryAfterDispatch
  6513. />
  6514. )}
  6515. {/* MQTT Debug Modal */}
  6516. {showMQTTDebug && (
  6517. <MQTTDebugModal
  6518. printerId={printer.id}
  6519. printerName={printer.name}
  6520. onClose={() => setShowMQTTDebug(false)}
  6521. />
  6522. )}
  6523. {showDiagnostic && (
  6524. <ConnectionDiagnosticModal
  6525. printerId={printer.id}
  6526. printerName={printer.name}
  6527. onClose={() => setShowDiagnostic(false)}
  6528. />
  6529. )}
  6530. {showPrinterInfo && (
  6531. <PrinterInfoModal
  6532. printer={printer}
  6533. status={status}
  6534. totalPrintHours={maintenanceInfo?.total_print_hours}
  6535. onClose={closePrinterInfo}
  6536. />
  6537. )}
  6538. {/* Plate Check Result Modal */}
  6539. {plateCheckResult && (
  6540. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6541. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6542. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6543. <div className="flex items-center gap-2">
  6544. {plateCheckResult.needs_calibration ? (
  6545. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6546. ) : plateCheckResult.is_empty ? (
  6547. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6548. ) : (
  6549. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6550. )}
  6551. <h2 className="text-lg font-semibold text-white">
  6552. Build Plate Check
  6553. </h2>
  6554. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6555. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6556. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6557. </span>
  6558. )}
  6559. </div>
  6560. <button
  6561. onClick={() => closePlateCheckModal()}
  6562. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6563. >
  6564. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6565. </button>
  6566. </div>
  6567. <div className="p-4 space-y-4">
  6568. {plateCheckResult.needs_calibration ? (
  6569. <>
  6570. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6571. <p className="font-medium text-blue-700 dark:text-blue-400">
  6572. {t('printers.plateDetection.calibrationRequired')}
  6573. </p>
  6574. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6575. </div>
  6576. <div className="text-sm text-bambu-gray space-y-2">
  6577. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6578. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6579. </div>
  6580. </>
  6581. ) : (
  6582. <>
  6583. <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'}`}>
  6584. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6585. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6586. </p>
  6587. <p className="text-sm text-bambu-gray mt-1">
  6588. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6589. </p>
  6590. </div>
  6591. {plateCheckResult.debug_image_url && (
  6592. <div>
  6593. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6594. <img
  6595. src={plateCheckResult.debug_image_url}
  6596. alt={t('printers.plateDetection.analysisPreview')}
  6597. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6598. />
  6599. <p className="text-xs text-bambu-gray mt-2">
  6600. {t('printers.plateDetection.analysisLegend')}
  6601. </p>
  6602. </div>
  6603. )}
  6604. <p className="text-xs text-bambu-gray">
  6605. {plateCheckResult.message}
  6606. </p>
  6607. </>
  6608. )}
  6609. {/* Saved References Grid */}
  6610. {plateReferences && plateReferences.references.length > 0 && (
  6611. <div className="mt-4">
  6612. <div className="flex items-center gap-2 mb-2">
  6613. <p className="text-sm font-medium text-white shrink-0">
  6614. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6615. </p>
  6616. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6617. </div>
  6618. <div className="grid grid-cols-5 gap-2">
  6619. {plateReferences.references.map((ref) => (
  6620. <div key={ref.index} className="relative group">
  6621. <img
  6622. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6623. alt={ref.label || `Reference ${ref.index + 1}`}
  6624. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6625. />
  6626. {/* Delete button */}
  6627. <button
  6628. onClick={() => handleDeleteRef(ref.index)}
  6629. 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"
  6630. title={t('printers.plateDetection.deleteReference')}
  6631. >
  6632. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6633. </button>
  6634. {/* Label */}
  6635. {editingRefLabel?.index === ref.index ? (
  6636. <input
  6637. type="text"
  6638. value={editingRefLabel.label}
  6639. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6640. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6641. onKeyDown={(e) => {
  6642. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6643. if (e.key === 'Escape') setEditingRefLabel(null);
  6644. }}
  6645. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6646. autoFocus
  6647. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6648. />
  6649. ) : (
  6650. <p
  6651. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6652. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6653. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6654. >
  6655. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6656. </p>
  6657. )}
  6658. {/* Timestamp */}
  6659. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6660. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6661. </p>
  6662. </div>
  6663. ))}
  6664. </div>
  6665. </div>
  6666. )}
  6667. {/* ROI Editor */}
  6668. {!plateCheckResult.needs_calibration && (
  6669. <div className="mt-4">
  6670. <div className="flex items-center justify-between mb-2">
  6671. <div className="flex min-w-0 flex-1 items-center gap-2">
  6672. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6673. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6674. </div>
  6675. {!editingRoi ? (
  6676. <Button
  6677. variant="ghost"
  6678. size="sm"
  6679. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6680. >
  6681. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6682. {t('common.edit')}
  6683. </Button>
  6684. ) : (
  6685. <div className="flex gap-1">
  6686. <Button
  6687. variant="ghost"
  6688. size="sm"
  6689. onClick={() => setEditingRoi(null)}
  6690. disabled={isSavingRoi}
  6691. >
  6692. {t('common.cancel')}
  6693. </Button>
  6694. <Button
  6695. size="sm"
  6696. onClick={handleSaveRoi}
  6697. disabled={isSavingRoi}
  6698. >
  6699. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6700. </Button>
  6701. </div>
  6702. )}
  6703. </div>
  6704. {editingRoi ? (
  6705. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6706. <div className="grid grid-cols-2 gap-3">
  6707. <div>
  6708. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6709. <input
  6710. type="range"
  6711. min="0"
  6712. max="0.9"
  6713. step="0.01"
  6714. value={editingRoi.x}
  6715. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6716. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6717. />
  6718. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6719. </div>
  6720. <div>
  6721. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6722. <input
  6723. type="range"
  6724. min="0"
  6725. max="0.9"
  6726. step="0.01"
  6727. value={editingRoi.y}
  6728. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6729. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6730. />
  6731. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6732. </div>
  6733. <div>
  6734. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6735. <input
  6736. type="range"
  6737. min="0.1"
  6738. max="1"
  6739. step="0.01"
  6740. value={editingRoi.w}
  6741. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6742. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6743. />
  6744. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6745. </div>
  6746. <div>
  6747. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6748. <input
  6749. type="range"
  6750. min="0.1"
  6751. max="1"
  6752. step="0.01"
  6753. value={editingRoi.h}
  6754. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6755. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6756. />
  6757. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6758. </div>
  6759. </div>
  6760. <p className="text-xs text-bambu-gray">
  6761. {t('printers.roi.instruction')}
  6762. </p>
  6763. </div>
  6764. ) : (
  6765. <p className="text-xs text-bambu-gray">
  6766. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6767. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6768. </p>
  6769. )}
  6770. </div>
  6771. )}
  6772. </div>
  6773. <div className="flex justify-end gap-2 p-4">
  6774. {plateCheckResult.needs_calibration ? (
  6775. <>
  6776. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6777. {t('common.cancel')}
  6778. </Button>
  6779. <Button
  6780. onClick={() => handleCalibratePlate()}
  6781. disabled={isCalibrating}
  6782. >
  6783. {isCalibrating ? (
  6784. <>
  6785. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6786. Calibrating...
  6787. </>
  6788. ) : (
  6789. 'Calibrate Empty Plate'
  6790. )}
  6791. </Button>
  6792. </>
  6793. ) : (
  6794. <>
  6795. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6796. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6797. </Button>
  6798. <Button onClick={() => closePlateCheckModal()}>
  6799. Close
  6800. </Button>
  6801. </>
  6802. )}
  6803. </div>
  6804. </div>
  6805. </div>
  6806. )}
  6807. {/* Power On Confirmation */}
  6808. {showPowerOnConfirm && smartPlug && (
  6809. <ConfirmModal
  6810. title={t('printers.confirm.powerOnTitle')}
  6811. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6812. confirmText={t('printers.confirm.powerOnButton')}
  6813. variant="default"
  6814. onConfirm={() => {
  6815. powerControlMutation.mutate('on');
  6816. setShowPowerOnConfirm(false);
  6817. }}
  6818. onCancel={() => setShowPowerOnConfirm(false)}
  6819. />
  6820. )}
  6821. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6822. disconnects MQTT, which stops progress tracking + completion
  6823. notifications for the in-flight job. Idle / FINISH / FAILED states
  6824. skip this dialog and toggle directly. */}
  6825. {confirmMaintenanceEnter && (
  6826. <ConfirmModal
  6827. title={t('printers.maintenance.confirmMidPrintTitle')}
  6828. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6829. confirmText={t('printers.maintenance.menuEnter')}
  6830. variant="danger"
  6831. onConfirm={() => {
  6832. maintenanceMutation.mutate(false);
  6833. setConfirmMaintenanceEnter(false);
  6834. }}
  6835. onCancel={() => setConfirmMaintenanceEnter(false)}
  6836. />
  6837. )}
  6838. {/* Power Off Confirmation */}
  6839. {showPowerOffConfirm && smartPlug && (
  6840. <ConfirmModal
  6841. title={t('printers.confirm.powerOffTitle')}
  6842. message={
  6843. status?.state === 'RUNNING'
  6844. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6845. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6846. }
  6847. confirmText={t('printers.confirm.powerOffButton')}
  6848. variant="danger"
  6849. onConfirm={() => {
  6850. powerControlMutation.mutate('off');
  6851. setShowPowerOffConfirm(false);
  6852. }}
  6853. onCancel={() => setShowPowerOffConfirm(false)}
  6854. />
  6855. )}
  6856. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6857. {haToggleConfirm && (
  6858. <ConfirmModal
  6859. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6860. message={
  6861. status?.state === 'RUNNING'
  6862. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6863. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6864. }
  6865. confirmText={t('printers.confirm.haToggleButton')}
  6866. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6867. onConfirm={() => {
  6868. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6869. setHaToggleConfirm(null);
  6870. }}
  6871. onCancel={() => setHaToggleConfirm(null)}
  6872. />
  6873. )}
  6874. {/* Stop Print Confirmation */}
  6875. {showStopConfirm && (
  6876. <ConfirmModal
  6877. title={t('printers.confirm.stopTitle')}
  6878. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6879. confirmText={t('printers.confirm.stopButton')}
  6880. variant="danger"
  6881. onConfirm={() => {
  6882. stopPrintMutation.mutate();
  6883. setShowStopConfirm(false);
  6884. }}
  6885. onCancel={() => setShowStopConfirm(false)}
  6886. />
  6887. )}
  6888. {/* Pause Print Confirmation */}
  6889. {showPauseConfirm && (
  6890. <ConfirmModal
  6891. title={t('printers.confirm.pauseTitle')}
  6892. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6893. confirmText={t('printers.confirm.pauseButton')}
  6894. variant="default"
  6895. onConfirm={() => {
  6896. pausePrintMutation.mutate();
  6897. setShowPauseConfirm(false);
  6898. }}
  6899. onCancel={() => setShowPauseConfirm(false)}
  6900. />
  6901. )}
  6902. {/* Resume Print Confirmation */}
  6903. {showResumeConfirm && (
  6904. <ConfirmModal
  6905. title={t('printers.confirm.resumeTitle')}
  6906. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6907. confirmText={t('printers.confirm.resumeButton')}
  6908. variant="default"
  6909. onConfirm={() => {
  6910. resumePrintMutation.mutate();
  6911. setShowResumeConfirm(false);
  6912. }}
  6913. onCancel={() => setShowResumeConfirm(false)}
  6914. />
  6915. )}
  6916. {/* Skip Objects Modal */}
  6917. <SkipObjectsModal
  6918. printerId={printer.id}
  6919. isOpen={showSkipObjectsModal}
  6920. onClose={() => setShowSkipObjectsModal(false)}
  6921. />
  6922. {/* HMS Error Modal */}
  6923. {showHMSModal && (
  6924. <HMSErrorModal
  6925. printerName={printer.name}
  6926. errors={status?.hms_errors || []}
  6927. onClose={() => setShowHMSModal(false)}
  6928. printerId={printer.id}
  6929. hasPermission={hasPermission}
  6930. runoutGuidance={runoutGuidance}
  6931. />
  6932. )}
  6933. {/* AI failure detection modal (#1546) */}
  6934. {showAiModal && (
  6935. <AiDetectionModal
  6936. printerName={printer.name}
  6937. detection={aiDetection}
  6938. lastError={aiLastError}
  6939. onClose={() => setShowAiModal(false)}
  6940. />
  6941. )}
  6942. {/* AMS Filament Backup status / control modal (#1762) */}
  6943. {amsBackupModalOpen && status && (
  6944. <AmsBackupModal
  6945. isOpen={amsBackupModalOpen}
  6946. state={status.ams_filament_backup}
  6947. amsUnits={status.ams}
  6948. amsExtruderMap={status.ams_extruder_map}
  6949. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6950. canToggle={hasPermission('printers:control')}
  6951. pending={setAmsBackupMutation.isPending}
  6952. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6953. onClose={() => setAmsBackupModalOpen(false)}
  6954. />
  6955. )}
  6956. {/* AMS History Modal */}
  6957. {amsHistoryModal && (
  6958. <AMSHistoryModal
  6959. isOpen={!!amsHistoryModal}
  6960. onClose={() => setAmsHistoryModal(null)}
  6961. printerId={printer.id}
  6962. printerName={printer.name}
  6963. amsId={amsHistoryModal.amsId}
  6964. amsLabel={amsHistoryModal.amsLabel}
  6965. initialMode={amsHistoryModal.mode}
  6966. thresholds={amsThresholds}
  6967. />
  6968. )}
  6969. {/* Heater History Modal (nozzle / bed / chamber) */}
  6970. {heaterHistoryModal && (
  6971. <HeaterHistoryModal
  6972. isOpen={!!heaterHistoryModal}
  6973. onClose={() => setHeaterHistoryModal(null)}
  6974. printerId={printer.id}
  6975. printerName={printer.name}
  6976. initialKind={heaterHistoryModal.initialKind}
  6977. availableKinds={heaterHistoryModal.availableKinds}
  6978. />
  6979. )}
  6980. {/* Link Spool Modal */}
  6981. {linkSpoolModal && (
  6982. <LinkSpoolModal
  6983. isOpen={!!linkSpoolModal}
  6984. onClose={() => setLinkSpoolModal(null)}
  6985. tagUid={linkSpoolModal.tagUid}
  6986. trayUuid={linkSpoolModal.trayUuid}
  6987. printerId={linkSpoolModal.printerId}
  6988. amsId={linkSpoolModal.amsId}
  6989. trayId={linkSpoolModal.trayId}
  6990. />
  6991. )}
  6992. {/* Assign Spool Modal */}
  6993. {assignSpoolModal && (
  6994. <AssignSpoolModal
  6995. isOpen={!!assignSpoolModal}
  6996. onClose={() => setAssignSpoolModal(null)}
  6997. printerId={assignSpoolModal.printerId}
  6998. amsId={assignSpoolModal.amsId}
  6999. trayId={assignSpoolModal.trayId}
  7000. trayInfo={assignSpoolModal.trayInfo}
  7001. spoolmanEnabled={!!spoolmanEnabled}
  7002. />
  7003. )}
  7004. {/* Configure AMS Slot Modal */}
  7005. {configureSlotModal && (
  7006. <ConfigureAmsSlotModal
  7007. isOpen={!!configureSlotModal}
  7008. onClose={() => setConfigureSlotModal(null)}
  7009. printerId={printer.id}
  7010. slotInfo={configureSlotModal}
  7011. printerModel={mapModelCode(printer.model) || undefined}
  7012. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  7013. onSuccess={() => {
  7014. // Refresh slot presets to show updated profile name
  7015. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7016. // Printer status will update automatically via WebSocket when AMS data changes
  7017. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7018. }}
  7019. />
  7020. )}
  7021. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7022. {feedDirectionRequest && (
  7023. <FeedDirectionModal
  7024. slotLabel={feedDirectionRequest.slotLabel}
  7025. amsId={feedDirectionRequest.amsId}
  7026. slotId={feedDirectionRequest.slotId}
  7027. extruderSlots={status?.extruder_slots ?? {}}
  7028. isLoading={loadAmsTrayMutation.isPending}
  7029. onConfirm={(extruderId) =>
  7030. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7031. }
  7032. onCancel={() => setFeedDirectionRequest(null)}
  7033. />
  7034. )}
  7035. {/* Edit Printer Modal */}
  7036. {showEditModal && (
  7037. <EditPrinterModal
  7038. printer={printer}
  7039. onClose={() => setShowEditModal(false)}
  7040. />
  7041. )}
  7042. {/* Firmware Update Modal */}
  7043. {showFirmwareModal && firmwareInfo && (
  7044. <FirmwareUpdateModal
  7045. printer={printer}
  7046. firmwareInfo={firmwareInfo}
  7047. onClose={() => setShowFirmwareModal(false)}
  7048. />
  7049. )}
  7050. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7051. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7052. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7053. const sliderMin = 35;
  7054. const sliderMax = maxTemp + 10;
  7055. return (
  7056. <>
  7057. {/* Backdrop */}
  7058. <div
  7059. className="fixed inset-0 z-[100]"
  7060. data-testid="drying-popover-backdrop"
  7061. onMouseDown={() => {
  7062. // The click that dismisses the native datetime picker lands
  7063. // here; it must not close the popover. The input is still
  7064. // focused at mousedown, so remember that and swallow the
  7065. // matching click.
  7066. dryingBackdropSkipCloseRef.current =
  7067. dryingAtTimeInputRef.current !== null &&
  7068. document.activeElement === dryingAtTimeInputRef.current;
  7069. }}
  7070. onClick={() => {
  7071. if (dryingBackdropSkipCloseRef.current) {
  7072. dryingBackdropSkipCloseRef.current = false;
  7073. return;
  7074. }
  7075. setDryingPopoverAmsId(null);
  7076. }}
  7077. />
  7078. {/* An 'above' popover is anchored by its bottom edge (CSS
  7079. bottom) so late-appearing content grows it upward, staying on
  7080. screen and glued to the trigger. maxHeight caps to the space
  7081. on the anchored side; when the viewport is too short the body
  7082. scrolls and the footer stays pinned. dvh so iOS Safari's
  7083. bottom toolbar doesn't clip the footer. */}
  7084. <div
  7085. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7086. style={{
  7087. left: dryingPopoverPos.left,
  7088. ...(dryingPopoverPos.placement === 'above'
  7089. ? {
  7090. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7091. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7092. }
  7093. : {
  7094. top: dryingPopoverPos.top,
  7095. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7096. }),
  7097. }}
  7098. onClick={e => e.stopPropagation()}
  7099. >
  7100. {/* Header */}
  7101. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7102. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7103. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7104. </div>
  7105. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7106. {/* Body */}
  7107. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7108. {/* Filament type select */}
  7109. <div>
  7110. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7111. <ToolbarDropdown
  7112. value={dryingFilament}
  7113. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7114. onChange={fil => {
  7115. setDryingFilament(fil);
  7116. const preset = dryingPresets[fil];
  7117. if (preset) {
  7118. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7119. setDryingTemp(preset[key]);
  7120. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7121. }
  7122. }}
  7123. fullWidth
  7124. />
  7125. </div>
  7126. {/* Temperature */}
  7127. <div>
  7128. <div className="flex items-center justify-between mb-1">
  7129. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7130. <div className="flex items-center gap-1">
  7131. <input
  7132. type="number"
  7133. min={45}
  7134. max={maxTemp}
  7135. value={dryingTemp}
  7136. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  7137. 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"
  7138. />
  7139. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7140. </div>
  7141. </div>
  7142. <input
  7143. type="range"
  7144. min={sliderMin}
  7145. max={sliderMax}
  7146. value={dryingTemp}
  7147. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7148. className="w-full h-1 accent-bambu-green cursor-pointer"
  7149. />
  7150. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7151. <span>45°C</span>
  7152. <span>{maxTemp}°C</span>
  7153. </div>
  7154. </div>
  7155. {/* Duration */}
  7156. <div>
  7157. <div className="flex items-center justify-between mb-1">
  7158. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7159. <div className="flex items-center gap-1">
  7160. <input
  7161. type="number"
  7162. min={1}
  7163. max={24}
  7164. value={dryingDuration}
  7165. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  7166. 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"
  7167. />
  7168. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7169. </div>
  7170. </div>
  7171. <input
  7172. type="range"
  7173. min={1}
  7174. max={24}
  7175. value={dryingDuration}
  7176. onChange={e => setDryingDuration(Number(e.target.value))}
  7177. className="w-full h-1 accent-bambu-green cursor-pointer"
  7178. />
  7179. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7180. <span>1h</span>
  7181. <span>24h</span>
  7182. </div>
  7183. </div>
  7184. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7185. filament threaded out into the feed tube. The whole AMS
  7186. rotates as one mechanism (all 4 spools turn together), so a
  7187. single loaded slot locks the entire unit. Bambu per-tray
  7188. `state`: 9 = empty, 10 = spool present but not loaded
  7189. (rotation possible), 11 = loaded into tube (rotation impossible).
  7190. Catches both mid-print (active feed) AND idle-with-threaded-
  7191. filament — the H2D's post-print state leaves filament in the
  7192. tube but tray_now resets to 255, which a tray_now-only check
  7193. would silently miss. */}
  7194. {(() => {
  7195. const targetAms = dryingPopoverAmsId !== null
  7196. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7197. : undefined;
  7198. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7199. tray => tray.state === 11,
  7200. );
  7201. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7202. return (
  7203. <button
  7204. type="button"
  7205. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7206. aria-pressed={rotateChecked}
  7207. disabled={trayLoadedInThisAms}
  7208. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7209. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7210. rotateChecked
  7211. ? 'bg-bambu-green border-bambu-green text-white'
  7212. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7213. }`}
  7214. >
  7215. {t('printers.drying.rotateTray')}
  7216. </button>
  7217. );
  7218. })()}
  7219. {/* Start mode: now / after delay / at time (#2638) */}
  7220. <div>
  7221. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7222. <div className="grid grid-cols-3 gap-1">
  7223. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7224. <button
  7225. key={mode}
  7226. type="button"
  7227. onClick={() => setDryingStartMode(mode)}
  7228. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7229. dryingStartMode === mode
  7230. ? 'bg-bambu-green border-bambu-green text-white'
  7231. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7232. }`}
  7233. >
  7234. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7235. </button>
  7236. ))}
  7237. </div>
  7238. {dryingStartMode === 'delay' && (
  7239. // Inline chips: a dropdown menu would be clipped by
  7240. // the popover's scrollable body.
  7241. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7242. {DRYING_DELAY_OPTIONS.map(min => (
  7243. <button
  7244. key={min}
  7245. type="button"
  7246. aria-pressed={dryingDelayMinutes === min}
  7247. onClick={() => setDryingDelayMinutes(min)}
  7248. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7249. dryingDelayMinutes === min
  7250. ? 'bg-bambu-green border-bambu-green text-white'
  7251. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7252. }`}
  7253. >
  7254. {formatDurationFromHours(min / 60)}
  7255. </button>
  7256. ))}
  7257. </div>
  7258. )}
  7259. {dryingStartMode === 'at_time' && (
  7260. <input
  7261. ref={dryingAtTimeInputRef}
  7262. type="datetime-local"
  7263. data-testid="drying-start-at"
  7264. value={dryingStartAt}
  7265. onChange={e => setDryingStartAt(e.target.value)}
  7266. 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]"
  7267. />
  7268. )}
  7269. </div>
  7270. </div>
  7271. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7272. {/* Footer */}
  7273. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7274. <button
  7275. onClick={() => {
  7276. if (dryingPopoverAmsId !== null) {
  7277. // Clamp rotateTray off when any tray in this AMS is loaded into
  7278. // the tube — the rotate UI is disabled there, but the state may
  7279. // linger as `true` from a previous AMS, or a print may have
  7280. // started while the popover was open. Without this clamp the
  7281. // Start payload would carry rotate_tray=true and firmware would
  7282. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7283. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7284. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7285. tray => tray.state === 11,
  7286. );
  7287. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7288. if (dryingStartMode === 'now') {
  7289. startDryingMutation.mutate({
  7290. amsId: dryingPopoverAmsId,
  7291. temp: dryingTemp,
  7292. duration: dryingDuration,
  7293. filament: dryingFilament,
  7294. rotateTray: rotate,
  7295. });
  7296. } else {
  7297. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7298. if (startAfter) {
  7299. scheduleDryingMutation.mutate({
  7300. amsId: dryingPopoverAmsId,
  7301. temp: dryingTemp,
  7302. duration: dryingDuration,
  7303. filament: dryingFilament,
  7304. rotateTray: rotate,
  7305. startAfter,
  7306. });
  7307. }
  7308. }
  7309. }
  7310. }}
  7311. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7312. data-testid="drying-start-confirm"
  7313. 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"
  7314. >
  7315. {dryingStartMode === 'now'
  7316. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7317. : t('printers.drying.schedule')}
  7318. </button>
  7319. </div>
  7320. </div>
  7321. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7322. since the popover clips its own overflow. */}
  7323. <div
  7324. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7325. style={{
  7326. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7327. top: dryingPopoverPos.anchorY - 5,
  7328. ...(dryingPopoverPos.placement === 'above'
  7329. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7330. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7331. }}
  7332. />
  7333. </>
  7334. );
  7335. })()}
  7336. </Card>
  7337. );
  7338. }
  7339. export function AddPrinterModal({
  7340. onClose,
  7341. onAdd,
  7342. existingSerials,
  7343. }: {
  7344. onClose: () => void;
  7345. onAdd: (data: PrinterCreate) => void;
  7346. existingSerials: string[];
  7347. }) {
  7348. const { t } = useTranslation();
  7349. const [form, setForm] = useState<PrinterCreate>({
  7350. name: '',
  7351. serial_number: '',
  7352. ip_address: '',
  7353. access_code: '',
  7354. model: '',
  7355. location: '',
  7356. auto_archive: true,
  7357. });
  7358. // Discovery state
  7359. const [discovering, setDiscovering] = useState(false);
  7360. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7361. const [discoveryError, setDiscoveryError] = useState('');
  7362. const [hasScanned, setHasScanned] = useState(false);
  7363. const [isDocker, setIsDocker] = useState(false);
  7364. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7365. const [subnet, setSubnet] = useState('');
  7366. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7367. // text input so users can scan a subnet Bambuddy isn't directly on
  7368. // (printer behind a router on a different L3 segment — SSDP multicast
  7369. // won't cross that boundary, only an active unicast scan will). #1564
  7370. const [customSubnet, setCustomSubnet] = useState('');
  7371. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7372. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7373. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7374. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7375. // (not block) when checks fail, so the user doesn't add a printer that
  7376. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7377. // failed result awaiting an explicit "save anyway".
  7378. const [checkingSave, setCheckingSave] = useState(false);
  7379. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7380. // Fetch discovery info on mount + restore the last custom CIDR the user
  7381. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7382. // time they open this modal).
  7383. useEffect(() => {
  7384. discoveryApi.getInfo().then(info => {
  7385. setIsDocker(info.is_docker);
  7386. if (info.subnets.length > 0) {
  7387. setDetectedSubnets(info.subnets);
  7388. setSubnet(info.subnets[0]);
  7389. }
  7390. }).catch(() => {
  7391. // Ignore errors, assume not Docker
  7392. });
  7393. try {
  7394. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7395. if (saved) setCustomSubnet(saved);
  7396. } catch {
  7397. // localStorage unavailable (private mode, quota); recall is opportunistic
  7398. }
  7399. }, []);
  7400. // Filter out already-added printers
  7401. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7402. const handleAddSubmit = async (e: React.FormEvent) => {
  7403. e.preventDefault();
  7404. setCheckingSave(true);
  7405. try {
  7406. const result = await api.diagnoseConnection({
  7407. ip_address: form.ip_address.trim(),
  7408. serial_number: form.serial_number.trim() || undefined,
  7409. access_code: form.access_code || undefined,
  7410. });
  7411. if (result.checks.some((c) => c.status === 'fail')) {
  7412. setSaveWarning(result);
  7413. return;
  7414. }
  7415. } catch {
  7416. // Diagnostic infrastructure failed — never block the save on it.
  7417. } finally {
  7418. setCheckingSave(false);
  7419. }
  7420. onAdd(form);
  7421. };
  7422. const startDiscovery = async () => {
  7423. setDiscoveryError('');
  7424. setDiscovered([]);
  7425. setDiscovering(true);
  7426. setHasScanned(false);
  7427. setScanProgress({ scanned: 0, total: 0 });
  7428. // Native installs fall back to subnet scanning when the user picks
  7429. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7430. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7431. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7432. const wantsSubnetScan = isDocker || useCustomSubnet;
  7433. if (wantsSubnetScan && useCustomSubnet) {
  7434. try {
  7435. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7436. } catch {
  7437. // localStorage write best-effort; user just retypes next time
  7438. }
  7439. }
  7440. try {
  7441. if (wantsSubnetScan) {
  7442. await discoveryApi.startSubnetScan(scanCidr);
  7443. // Poll for scan status and results
  7444. const pollInterval = setInterval(async () => {
  7445. try {
  7446. const status = await discoveryApi.getScanStatus();
  7447. setScanProgress({ scanned: status.scanned, total: status.total });
  7448. const printers = await discoveryApi.getDiscoveredPrinters();
  7449. setDiscovered(printers);
  7450. if (!status.running) {
  7451. clearInterval(pollInterval);
  7452. setDiscovering(false);
  7453. setHasScanned(true);
  7454. }
  7455. } catch (e) {
  7456. console.error('Failed to get scan status:', e);
  7457. }
  7458. }, 500);
  7459. } else {
  7460. // Use SSDP discovery for native installs
  7461. await discoveryApi.startDiscovery(10);
  7462. // Poll for discovered printers every second
  7463. const pollInterval = setInterval(async () => {
  7464. try {
  7465. const printers = await discoveryApi.getDiscoveredPrinters();
  7466. setDiscovered(printers);
  7467. } catch (e) {
  7468. console.error('Failed to get discovered printers:', e);
  7469. }
  7470. }, 1000);
  7471. // Stop after 10 seconds
  7472. setTimeout(async () => {
  7473. clearInterval(pollInterval);
  7474. try {
  7475. await discoveryApi.stopDiscovery();
  7476. } catch {
  7477. // Ignore stop errors
  7478. }
  7479. setDiscovering(false);
  7480. setHasScanned(true);
  7481. // Final fetch
  7482. try {
  7483. const printers = await discoveryApi.getDiscoveredPrinters();
  7484. setDiscovered(printers);
  7485. } catch (e) {
  7486. console.error('Failed to get final discovered printers:', e);
  7487. }
  7488. }, 10000);
  7489. }
  7490. } catch (e) {
  7491. console.error('Failed to start discovery:', e);
  7492. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7493. setDiscovering(false);
  7494. setHasScanned(true);
  7495. }
  7496. };
  7497. // Reuse module-level mapModelCode
  7498. const selectPrinter = (printer: DiscoveredPrinter) => {
  7499. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7500. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7501. setForm({
  7502. ...form,
  7503. name: printer.name || '',
  7504. serial_number: serialNumber,
  7505. ip_address: printer.ip_address,
  7506. model: mapModelCode(printer.model),
  7507. });
  7508. // Clear discovery results after selection
  7509. setDiscovered([]);
  7510. };
  7511. // Cleanup discovery on unmount
  7512. useEffect(() => {
  7513. return () => {
  7514. discoveryApi.stopDiscovery().catch(() => {});
  7515. discoveryApi.stopSubnetScan().catch(() => {});
  7516. };
  7517. }, []);
  7518. // Close on Escape key
  7519. useEffect(() => {
  7520. const handleKeyDown = (e: KeyboardEvent) => {
  7521. if (e.key === 'Escape') onClose();
  7522. };
  7523. window.addEventListener('keydown', handleKeyDown);
  7524. return () => window.removeEventListener('keydown', handleKeyDown);
  7525. }, [onClose]);
  7526. return (
  7527. <>
  7528. <div
  7529. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7530. onClick={onClose}
  7531. >
  7532. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7533. <CardContent>
  7534. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7535. {/* Discovery Section */}
  7536. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7537. {/* Subnet picker — always visible. The dropdown lists detected
  7538. interface subnets and a "Custom..." sentinel that reveals
  7539. a CIDR text input for printers on a different L3 segment
  7540. (router, VLAN, etc.). #1564 */}
  7541. <div className="mb-3">
  7542. <label className="block text-sm text-bambu-gray mb-1">
  7543. {t('printers.discovery.subnetToScan')}
  7544. </label>
  7545. {detectedSubnets.length > 0 ? (
  7546. <select
  7547. 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"
  7548. value={useCustomSubnet ? '__custom__' : subnet}
  7549. onChange={(e) => {
  7550. if (e.target.value === '__custom__') {
  7551. setUseCustomSubnet(true);
  7552. } else {
  7553. setUseCustomSubnet(false);
  7554. setSubnet(e.target.value);
  7555. }
  7556. }}
  7557. disabled={discovering}
  7558. >
  7559. {detectedSubnets.map(s => (
  7560. <option key={s} value={s}>{s}</option>
  7561. ))}
  7562. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7563. </select>
  7564. ) : (
  7565. <input
  7566. type="text"
  7567. 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"
  7568. value={subnet}
  7569. onChange={(e) => setSubnet(e.target.value)}
  7570. placeholder="192.168.1.0/24"
  7571. disabled={discovering}
  7572. />
  7573. )}
  7574. {useCustomSubnet && (
  7575. <input
  7576. type="text"
  7577. aria-label={t('printers.discovery.customSubnetLabel')}
  7578. 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"
  7579. value={customSubnet}
  7580. onChange={(e) => setCustomSubnet(e.target.value)}
  7581. placeholder="10.1.1.0/24"
  7582. disabled={discovering}
  7583. />
  7584. )}
  7585. <p className="mt-1 text-xs text-bambu-gray">
  7586. {isDocker
  7587. ? t('printers.discovery.dockerNote')
  7588. : t('printers.discovery.customSubnetNote')}
  7589. </p>
  7590. </div>
  7591. <Button
  7592. type="button"
  7593. variant="secondary"
  7594. onClick={startDiscovery}
  7595. disabled={discovering}
  7596. className="w-full"
  7597. >
  7598. {discovering ? (
  7599. <>
  7600. <Loader2 className="w-4 h-4 animate-spin" />
  7601. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7602. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7603. : t('printers.discovery.scanning')}
  7604. </>
  7605. ) : (
  7606. <>
  7607. <Search className="w-4 h-4" />
  7608. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7609. </>
  7610. )}
  7611. </Button>
  7612. {discoveryError && (
  7613. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7614. )}
  7615. {newPrinters.length > 0 && (
  7616. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7617. {newPrinters.map((printer) => (
  7618. <div
  7619. key={printer.serial}
  7620. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7621. onClick={() => selectPrinter(printer)}
  7622. >
  7623. <div className="min-w-0 flex-1">
  7624. <p className="font-medium text-white text-sm truncate">
  7625. {printer.name || printer.serial}
  7626. </p>
  7627. <p className="text-xs text-bambu-gray truncate">
  7628. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7629. {printer.serial.startsWith('unknown-') && (
  7630. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7631. )}
  7632. </p>
  7633. </div>
  7634. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7635. </div>
  7636. ))}
  7637. </div>
  7638. )}
  7639. {discovering && (
  7640. <p className="mt-2 text-sm text-bambu-gray text-center">
  7641. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7642. </p>
  7643. )}
  7644. {hasScanned && !discovering && discovered.length === 0 && (
  7645. <p className="mt-2 text-sm text-bambu-gray text-center">
  7646. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7647. </p>
  7648. )}
  7649. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7650. <p className="mt-2 text-sm text-bambu-gray text-center">
  7651. {t('printers.discovery.allConfigured')}
  7652. </p>
  7653. )}
  7654. </div>
  7655. <form onSubmit={handleAddSubmit} className="space-y-4">
  7656. <div>
  7657. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7658. <input
  7659. type="text"
  7660. required
  7661. 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"
  7662. value={form.name}
  7663. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7664. placeholder={t('printers.modal.myPrinter')}
  7665. />
  7666. </div>
  7667. <div>
  7668. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7669. <input
  7670. type="text"
  7671. required
  7672. 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])?)*)"
  7673. 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"
  7674. value={form.ip_address}
  7675. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7676. placeholder="192.168.1.100 or printer.local"
  7677. />
  7678. </div>
  7679. <div>
  7680. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7681. <input
  7682. type="text"
  7683. required
  7684. 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"
  7685. value={form.serial_number}
  7686. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7687. placeholder="01P00A000000000"
  7688. />
  7689. </div>
  7690. <div>
  7691. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7692. <input
  7693. type="password"
  7694. required
  7695. 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"
  7696. value={form.access_code}
  7697. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7698. placeholder={t('printers.modal.fromPrinterSettings')}
  7699. />
  7700. </div>
  7701. <div>
  7702. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7703. <select
  7704. 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"
  7705. value={form.model || ''}
  7706. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7707. >
  7708. <option value="">{t('printers.modal.selectModel')}</option>
  7709. <optgroup label="A1 Series">
  7710. <option value="A1">A1</option>
  7711. <option value="A1 Mini">A1 Mini</option>
  7712. </optgroup>
  7713. <optgroup label="A2 Series">
  7714. <option value="A2L">A2L</option>
  7715. </optgroup>
  7716. <optgroup label="H2 Series">
  7717. <option value="H2C">H2C</option>
  7718. <option value="H2D">H2D</option>
  7719. <option value="H2D Pro">H2D Pro</option>
  7720. <option value="H2S">H2S</option>
  7721. </optgroup>
  7722. <optgroup label="P Series">
  7723. <option value="P1P">P1P</option>
  7724. <option value="P1S">P1S</option>
  7725. <option value="P2S">P2S</option>
  7726. </optgroup>
  7727. <optgroup label="X1 Series">
  7728. <option value="X1">X1</option>
  7729. <option value="X1C">X1 Carbon</option>
  7730. <option value="X1E">X1E</option>
  7731. </optgroup>
  7732. <optgroup label="X2 Series">
  7733. <option value="X2D">X2D</option>
  7734. </optgroup>
  7735. </select>
  7736. </div>
  7737. <div>
  7738. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7739. <input
  7740. type="text"
  7741. 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"
  7742. value={form.location || ''}
  7743. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7744. placeholder={t('printers.modal.locationPlaceholder')}
  7745. />
  7746. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7747. </div>
  7748. <div className="flex items-center gap-2">
  7749. <input
  7750. type="checkbox"
  7751. id="auto_archive"
  7752. checked={form.auto_archive}
  7753. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7754. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7755. />
  7756. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7757. {t('printers.modal.autoArchiveLabel')}
  7758. </label>
  7759. </div>
  7760. <button
  7761. type="button"
  7762. onClick={() => setShowDiagnostic(true)}
  7763. disabled={!form.ip_address.trim()}
  7764. 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"
  7765. >
  7766. <Stethoscope className="w-4 h-4" />
  7767. {t('diagnostic.runButton')}
  7768. </button>
  7769. {saveWarning ? (
  7770. <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">
  7771. <div className="flex items-start gap-2">
  7772. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7773. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7774. </div>
  7775. <DiagnosticChecklist result={saveWarning} />
  7776. <div className="flex gap-3">
  7777. <Button
  7778. type="button"
  7779. variant="secondary"
  7780. onClick={() => setSaveWarning(null)}
  7781. className="flex-1"
  7782. >
  7783. {t('printers.addPreflight.back')}
  7784. </Button>
  7785. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7786. {t('printers.addPreflight.saveAnyway')}
  7787. </Button>
  7788. </div>
  7789. </div>
  7790. ) : (
  7791. <div className="flex gap-3 pt-2">
  7792. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7793. {t('common.cancel')}
  7794. </Button>
  7795. <Button type="submit" disabled={checkingSave} className="flex-1">
  7796. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7797. </Button>
  7798. </div>
  7799. )}
  7800. </form>
  7801. </CardContent>
  7802. </Card>
  7803. </div>
  7804. {showDiagnostic && (
  7805. <ConnectionDiagnosticModal
  7806. connection={{
  7807. ip_address: form.ip_address.trim(),
  7808. serial_number: form.serial_number.trim() || undefined,
  7809. access_code: form.access_code || undefined,
  7810. }}
  7811. printerName={form.name || null}
  7812. onClose={() => setShowDiagnostic(false)}
  7813. />
  7814. )}
  7815. </>
  7816. );
  7817. }
  7818. function FirmwareUpdateModal({
  7819. printer,
  7820. firmwareInfo,
  7821. onClose,
  7822. }: {
  7823. printer: Printer;
  7824. firmwareInfo: FirmwareUpdateInfo;
  7825. onClose: () => void;
  7826. }) {
  7827. const { t } = useTranslation();
  7828. const queryClient = useQueryClient();
  7829. const { showToast } = useToast();
  7830. const { hasPermission } = useAuth();
  7831. const canUpdate = hasPermission('firmware:update');
  7832. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7833. const [isUploading, setIsUploading] = useState(false);
  7834. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7835. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7836. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7837. );
  7838. // Prepare check query — runs when a version is selected and user can update
  7839. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7840. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7841. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7842. staleTime: 30000,
  7843. enabled: !!selectedVersion && canUpdate && !isUploading,
  7844. });
  7845. // Start upload mutation
  7846. const uploadMutation = useMutation({
  7847. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7848. onSuccess: () => {
  7849. setIsUploading(true);
  7850. // Start polling for status
  7851. const interval = setInterval(async () => {
  7852. try {
  7853. const status = await firmwareApi.getUploadStatus(printer.id);
  7854. setUploadStatus(status);
  7855. if (status.status === 'complete' || status.status === 'error') {
  7856. clearInterval(interval);
  7857. setPollInterval(null);
  7858. setIsUploading(false);
  7859. if (status.status === 'complete') {
  7860. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7861. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7862. }
  7863. }
  7864. } catch {
  7865. // Ignore errors during polling
  7866. }
  7867. }, 2000);
  7868. setPollInterval(interval);
  7869. },
  7870. onError: (error: Error) => {
  7871. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7872. setIsUploading(false);
  7873. },
  7874. });
  7875. // Cleanup on unmount
  7876. useEffect(() => {
  7877. return () => {
  7878. if (pollInterval) clearInterval(pollInterval);
  7879. };
  7880. }, [pollInterval]);
  7881. const handleStartUpload = () => {
  7882. setUploadStatus(null);
  7883. uploadMutation.mutate();
  7884. };
  7885. return (
  7886. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7887. <Card className="w-full max-w-md mx-4">
  7888. <CardContent>
  7889. <div className="flex items-start gap-3 mb-4">
  7890. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7891. {firmwareInfo.update_available
  7892. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7893. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7894. </div>
  7895. <div className="flex-1">
  7896. <h3 className="text-lg font-semibold text-white">
  7897. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7898. </h3>
  7899. <p className="text-sm text-bambu-gray mt-1">
  7900. {printer.name}
  7901. </p>
  7902. </div>
  7903. </div>
  7904. {/* Version Info */}
  7905. {(() => {
  7906. const selectedEntry = selectedVersion
  7907. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7908. : null;
  7909. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7910. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7911. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7912. return (
  7913. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7914. <div className="flex justify-between items-center text-sm">
  7915. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7916. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7917. {firmwareInfo.current_version || t('common.unknown')}
  7918. </span>
  7919. </div>
  7920. {showSecondLine && (
  7921. <div className="flex justify-between items-center text-sm mt-1">
  7922. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7923. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7924. </div>
  7925. )}
  7926. {displayNotes && (
  7927. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7928. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7929. {t('printers.firmwareModal.releaseNotes')}
  7930. </summary>
  7931. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7932. {displayNotes}
  7933. </div>
  7934. </details>
  7935. )}
  7936. </div>
  7937. );
  7938. })()}
  7939. {/* Available versions list */}
  7940. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7941. <div className="mb-4">
  7942. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7943. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7944. {firmwareInfo.available_versions.map((v) => {
  7945. const isCurrent = firmwareInfo.current_version === v.version;
  7946. const isSelected = selectedVersion === v.version;
  7947. const cmp = firmwareInfo.current_version
  7948. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7949. : 0;
  7950. const relLabel = isCurrent
  7951. ? t('printers.firmwareModal.currentBadge')
  7952. : cmp > 0
  7953. ? t('printers.firmwareModal.newerBadge')
  7954. : t('printers.firmwareModal.olderBadge');
  7955. const relClass = isCurrent
  7956. ? 'text-bambu-gray'
  7957. : cmp > 0
  7958. ? 'text-orange-700 dark:text-orange-400'
  7959. : 'text-blue-700 dark:text-blue-400';
  7960. return (
  7961. <button
  7962. key={v.version}
  7963. type="button"
  7964. disabled={!v.file_available || !canUpdate || isCurrent}
  7965. onClick={() => setSelectedVersion(v.version)}
  7966. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7967. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7968. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7969. >
  7970. <div className="flex items-center gap-2 min-w-0">
  7971. <span className="font-mono text-white">{v.version}</span>
  7972. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7973. </div>
  7974. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7975. isCurrent
  7976. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7977. : v.file_available
  7978. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7979. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7980. }`}>
  7981. {isCurrent
  7982. ? t('printers.firmwareModal.installed')
  7983. : v.file_available
  7984. ? t('printers.firmwareModal.usable')
  7985. : t('printers.firmwareModal.unavailable')}
  7986. </span>
  7987. </button>
  7988. );
  7989. })}
  7990. </div>
  7991. </div>
  7992. )}
  7993. {/* Status / Progress (only when a version is selected) */}
  7994. {!selectedVersion ? null : isPreparing ? (
  7995. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7996. <Loader2 className="w-4 h-4 animate-spin" />
  7997. {t('printers.firmwareModal.checkingPrereqs')}
  7998. </div>
  7999. ) : prepareInfo && !isUploading && !uploadStatus ? (
  8000. <div className="mb-4">
  8001. {prepareInfo.can_proceed ? (
  8002. <div className="flex items-center gap-2 text-bambu-green text-sm">
  8003. <Box className="w-4 h-4" />
  8004. {t('printers.firmwareModal.sdCardReady')}
  8005. </div>
  8006. ) : (
  8007. <div className="space-y-1">
  8008. {prepareInfo.errors.map((error, i) => (
  8009. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  8010. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  8011. {error}
  8012. </div>
  8013. ))}
  8014. </div>
  8015. )}
  8016. </div>
  8017. ) : null}
  8018. {/* Upload Progress */}
  8019. {(isUploading || uploadStatus) && uploadStatus && (
  8020. <div className="mb-4">
  8021. <div className="flex items-center justify-between text-sm mb-1">
  8022. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8023. <span className="text-white">{uploadStatus.progress}%</span>
  8024. </div>
  8025. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8026. <div
  8027. className={`h-2 rounded-full transition-all ${
  8028. uploadStatus.status === 'error' ? 'bg-status-error' :
  8029. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8030. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8031. style={{ width: `${uploadStatus.progress}%` }}
  8032. />
  8033. </div>
  8034. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8035. {uploadStatus.error && (
  8036. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8037. )}
  8038. </div>
  8039. )}
  8040. {/* Success Message */}
  8041. {uploadStatus?.status === 'complete' && (
  8042. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8043. <p className="text-sm text-bambu-green font-medium mb-2">
  8044. {t('printers.firmwareModal.uploadedSuccess')}
  8045. </p>
  8046. <p className="text-xs text-bambu-gray">
  8047. {t('printers.firmwareModal.applyInstructions')}
  8048. </p>
  8049. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8050. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8051. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8052. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8053. <li>{t('printers.firmwareModal.step4')}</li>
  8054. </ol>
  8055. </div>
  8056. )}
  8057. {/* Buttons */}
  8058. <div className="flex gap-2 justify-end">
  8059. <Button variant="secondary" onClick={onClose}>
  8060. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8061. </Button>
  8062. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8063. <Button
  8064. onClick={handleStartUpload}
  8065. disabled={uploadMutation.isPending}
  8066. >
  8067. {uploadMutation.isPending ? (
  8068. <>
  8069. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8070. {t('printers.firmwareModal.starting')}
  8071. </>
  8072. ) : (
  8073. <>
  8074. <Download className="w-4 h-4 mr-2" />
  8075. {t('printers.firmwareModal.uploadFirmware')}
  8076. </>
  8077. )}
  8078. </Button>
  8079. )}
  8080. </div>
  8081. </CardContent>
  8082. </Card>
  8083. </div>
  8084. );
  8085. }
  8086. function EditPrinterModal({
  8087. printer,
  8088. onClose,
  8089. }: {
  8090. printer: Printer;
  8091. onClose: () => void;
  8092. }) {
  8093. const { t } = useTranslation();
  8094. const queryClient = useQueryClient();
  8095. const { showToast } = useToast();
  8096. const [form, setForm] = useState({
  8097. name: printer.name,
  8098. ip_address: printer.ip_address,
  8099. access_code: '',
  8100. model: printer.model || '',
  8101. location: printer.location || '',
  8102. auto_archive: printer.auto_archive,
  8103. is_active: printer.is_active,
  8104. });
  8105. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8106. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8107. const [checkingSave, setCheckingSave] = useState(false);
  8108. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8109. const updateMutation = useMutation({
  8110. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8111. onSuccess: () => {
  8112. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8113. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8114. onClose();
  8115. },
  8116. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8117. });
  8118. // Close on Escape key
  8119. useEffect(() => {
  8120. const handleKeyDown = (e: KeyboardEvent) => {
  8121. if (e.key === 'Escape') onClose();
  8122. };
  8123. window.addEventListener('keydown', handleKeyDown);
  8124. return () => window.removeEventListener('keydown', handleKeyDown);
  8125. }, [onClose]);
  8126. const doSave = () => {
  8127. const data: Partial<PrinterCreate> = {
  8128. name: form.name,
  8129. ip_address: form.ip_address,
  8130. model: form.model || undefined,
  8131. location: form.location || undefined,
  8132. auto_archive: form.auto_archive,
  8133. is_active: form.is_active,
  8134. };
  8135. // Only include access_code if it was changed
  8136. if (form.access_code) {
  8137. data.access_code = form.access_code;
  8138. }
  8139. updateMutation.mutate(data);
  8140. };
  8141. const handleSubmit = async (e: React.FormEvent) => {
  8142. e.preventDefault();
  8143. setCheckingSave(true);
  8144. try {
  8145. const result = await api.diagnoseConnection({
  8146. ip_address: form.ip_address.trim(),
  8147. serial_number: printer.serial_number,
  8148. access_code: form.access_code || undefined,
  8149. });
  8150. if (result.checks.some((c) => c.status === 'fail')) {
  8151. setSaveWarning(result);
  8152. return;
  8153. }
  8154. } catch {
  8155. // Diagnostic infrastructure failed — never block the save on it.
  8156. } finally {
  8157. setCheckingSave(false);
  8158. }
  8159. doSave();
  8160. };
  8161. return (
  8162. <div
  8163. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8164. onClick={onClose}
  8165. >
  8166. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8167. <CardContent>
  8168. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8169. <form onSubmit={handleSubmit} className="space-y-4">
  8170. <div>
  8171. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8172. <input
  8173. type="text"
  8174. required
  8175. 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"
  8176. value={form.name}
  8177. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8178. placeholder={t('printers.modal.myPrinter')}
  8179. />
  8180. </div>
  8181. <div>
  8182. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8183. <input
  8184. type="text"
  8185. required
  8186. 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])?)*)"
  8187. 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"
  8188. value={form.ip_address}
  8189. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8190. placeholder="192.168.1.100 or printer.local"
  8191. />
  8192. </div>
  8193. <div>
  8194. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8195. <input
  8196. type="text"
  8197. disabled
  8198. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8199. value={printer.serial_number}
  8200. />
  8201. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8202. </div>
  8203. <div>
  8204. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8205. <input
  8206. type="password"
  8207. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8208. value={form.access_code}
  8209. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8210. placeholder={t('printers.accessCodePlaceholder')}
  8211. />
  8212. </div>
  8213. <div>
  8214. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8215. <select
  8216. 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"
  8217. value={form.model}
  8218. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8219. >
  8220. <option value="">{t('printers.modal.selectModel')}</option>
  8221. <optgroup label="A1 Series">
  8222. <option value="A1">A1</option>
  8223. <option value="A1 Mini">A1 Mini</option>
  8224. </optgroup>
  8225. <optgroup label="A2 Series">
  8226. <option value="A2L">A2L</option>
  8227. </optgroup>
  8228. <optgroup label="H2 Series">
  8229. <option value="H2C">H2C</option>
  8230. <option value="H2D">H2D</option>
  8231. <option value="H2D Pro">H2D Pro</option>
  8232. <option value="H2S">H2S</option>
  8233. </optgroup>
  8234. <optgroup label="P Series">
  8235. <option value="P1P">P1P</option>
  8236. <option value="P1S">P1S</option>
  8237. <option value="P2S">P2S</option>
  8238. </optgroup>
  8239. <optgroup label="X1 Series">
  8240. <option value="X1">X1</option>
  8241. <option value="X1C">X1 Carbon</option>
  8242. <option value="X1E">X1E</option>
  8243. </optgroup>
  8244. <optgroup label="X2 Series">
  8245. <option value="X2D">X2D</option>
  8246. </optgroup>
  8247. </select>
  8248. </div>
  8249. <div>
  8250. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8251. <input
  8252. type="text"
  8253. 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"
  8254. value={form.location}
  8255. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8256. placeholder={t('printers.modal.locationPlaceholder')}
  8257. />
  8258. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8259. </div>
  8260. <div className="flex items-center gap-2">
  8261. <input
  8262. type="checkbox"
  8263. id="edit_auto_archive"
  8264. checked={form.auto_archive}
  8265. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8266. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8267. />
  8268. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8269. {t('printers.modal.autoArchiveLabel')}
  8270. </label>
  8271. </div>
  8272. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8273. is_active because the user-facing concept is "is this printer
  8274. in maintenance" not "is it active". */}
  8275. <div>
  8276. <div className="flex items-center gap-2">
  8277. <input
  8278. type="checkbox"
  8279. id="edit_maintenance_mode"
  8280. checked={!form.is_active}
  8281. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8282. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8283. />
  8284. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8285. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8286. {t('printers.maintenance.editFieldLabel')}
  8287. </label>
  8288. </div>
  8289. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8290. {t('printers.maintenance.editFieldHelp')}
  8291. </p>
  8292. </div>
  8293. {saveWarning ? (
  8294. <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">
  8295. <div className="flex items-start gap-2">
  8296. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8297. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8298. </div>
  8299. <DiagnosticChecklist result={saveWarning} />
  8300. <div className="flex gap-3">
  8301. <Button
  8302. type="button"
  8303. variant="secondary"
  8304. onClick={() => setSaveWarning(null)}
  8305. className="flex-1"
  8306. >
  8307. {t('printers.addPreflight.back')}
  8308. </Button>
  8309. <Button
  8310. type="button"
  8311. onClick={doSave}
  8312. className="flex-1"
  8313. disabled={updateMutation.isPending}
  8314. >
  8315. {t('printers.addPreflight.saveAnyway')}
  8316. </Button>
  8317. </div>
  8318. </div>
  8319. ) : (
  8320. <div className="flex gap-3 pt-4">
  8321. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8322. {t('common.cancel')}
  8323. </Button>
  8324. <Button
  8325. type="submit"
  8326. className="flex-1"
  8327. disabled={updateMutation.isPending || checkingSave}
  8328. >
  8329. {checkingSave
  8330. ? t('printers.addPreflight.checking')
  8331. : updateMutation.isPending
  8332. ? t('common.saving')
  8333. : t('printers.modal.saveChanges')}
  8334. </Button>
  8335. </div>
  8336. )}
  8337. </form>
  8338. </CardContent>
  8339. </Card>
  8340. </div>
  8341. );
  8342. }
  8343. // Component to check if a printer is offline (for power dropdown)
  8344. function usePrinterOfflineStatus(printerId: number) {
  8345. const { data: status } = useQuery({
  8346. queryKey: ['printerStatus', printerId],
  8347. queryFn: () => api.getPrinterStatus(printerId),
  8348. refetchInterval: 30000,
  8349. });
  8350. return !status?.connected;
  8351. }
  8352. // Power dropdown item for an offline printer
  8353. function PowerDropdownItem({
  8354. printer,
  8355. plug,
  8356. onPowerOn,
  8357. isPowering,
  8358. }: {
  8359. printer: Printer;
  8360. plug: { id: number; name: string };
  8361. onPowerOn: (plugId: number) => void;
  8362. isPowering: boolean;
  8363. }) {
  8364. const isOffline = usePrinterOfflineStatus(printer.id);
  8365. // Fetch plug status
  8366. const { data: plugStatus } = useQuery({
  8367. queryKey: ['smartPlugStatus', plug.id],
  8368. queryFn: () => api.getSmartPlugStatus(plug.id),
  8369. refetchInterval: 10000,
  8370. });
  8371. // Only show if printer is offline
  8372. if (!isOffline) {
  8373. return null;
  8374. }
  8375. return (
  8376. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8377. <div className="flex items-center gap-2 min-w-0">
  8378. <span className="text-sm text-white truncate">{printer.name}</span>
  8379. {plugStatus && (
  8380. <span
  8381. className={`text-xs px-1.5 py-0.5 rounded ${
  8382. plugStatus.state === 'ON'
  8383. ? 'bg-bambu-green/20 text-bambu-green'
  8384. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8385. }`}
  8386. >
  8387. {plugStatus.state || '?'}
  8388. </span>
  8389. )}
  8390. </div>
  8391. <button
  8392. onClick={() => onPowerOn(plug.id)}
  8393. disabled={isPowering || plugStatus?.state === 'ON'}
  8394. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8395. plugStatus?.state === 'ON'
  8396. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8397. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8398. }`}
  8399. >
  8400. <Power className="w-3 h-3" />
  8401. {isPowering ? '...' : 'On'}
  8402. </button>
  8403. </div>
  8404. );
  8405. }
  8406. export function PrintersPage() {
  8407. const { t } = useTranslation();
  8408. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8409. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8410. const accentButtonClass = {
  8411. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8412. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8413. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8414. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8415. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8416. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8417. }[activeAccent];
  8418. const [showAddModal, setShowAddModal] = useState(false);
  8419. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8420. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8421. });
  8422. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8423. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8424. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8425. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8426. });
  8427. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8428. return localStorage.getItem('printerSortAsc') !== 'false';
  8429. });
  8430. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8431. const [cardSize, setCardSize] = useState<number>(() => {
  8432. const saved = localStorage.getItem('printerCardSize');
  8433. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8434. });
  8435. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8436. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8437. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8438. });
  8439. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8440. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8441. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8442. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8443. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8444. });
  8445. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8446. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8447. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8448. });
  8449. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8450. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8451. // Defaulting to 'full' because the cards already show this info — users who
  8452. // pick cam-wall view still want to glance the same details without flipping.
  8453. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8454. const saved = localStorage.getItem('camWallStatusMode');
  8455. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8456. });
  8457. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8458. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8459. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8460. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8461. requestAnimationFrame(() => {
  8462. requestAnimationFrame(() => {
  8463. const card = document.getElementById(`printer-card-${printerId}`);
  8464. if (!card) return;
  8465. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8466. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8467. window.scrollTo({
  8468. top: Math.max(0, top),
  8469. behavior: 'smooth',
  8470. });
  8471. });
  8472. });
  8473. }, []);
  8474. const openCompactCard = useCallback((printerId: number) => {
  8475. setCompactDrilldownPrinterId(printerId);
  8476. setCardSize(2);
  8477. localStorage.setItem('printerCardSize', '2');
  8478. scrollPrinterIntoView(printerId);
  8479. }, [scrollPrinterIntoView]);
  8480. const returnToCompactCards = useCallback(() => {
  8481. const printerId = compactDrilldownPrinterId;
  8482. setCompactDrilldownPrinterId(null);
  8483. setCardSize(1);
  8484. localStorage.setItem('printerCardSize', '1');
  8485. if (printerId != null) {
  8486. scrollPrinterIntoView(printerId);
  8487. }
  8488. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8489. const [search, setSearch] = useState('');
  8490. // Both filters persist like every other preference on this page (#2833).
  8491. // `search` deliberately does not: a box that silently refills itself on
  8492. // return is more surprising than a dropdown that remembers.
  8493. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8494. // Validated on read: a value the dropdown no longer offers would filter
  8495. // every printer out, and nothing would explain why.
  8496. const saved = localStorage.getItem('printerStatusFilter');
  8497. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8498. });
  8499. const [locationFilter, setLocationFilter] = useState<string>(
  8500. () => localStorage.getItem('printerLocationFilter') || 'all'
  8501. );
  8502. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8503. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8504. try {
  8505. const saved = localStorage.getItem('printerCollapsedSections');
  8506. return saved ? JSON.parse(saved) : {};
  8507. } catch { return {}; }
  8508. });
  8509. const queryClient = useQueryClient();
  8510. const { showToast } = useToast();
  8511. const { hasPermission } = useAuth();
  8512. // Which way the camera buttons open a stream. Chosen per click from the
  8513. // button's own menu; null until this browser has made a choice, so the
  8514. // stored setting below can act as the default a fresh browser starts from.
  8515. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8516. () => readStoredCameraViewMode()
  8517. );
  8518. // Embedded camera viewer state - supports multiple simultaneous viewers
  8519. // Persisted to localStorage so cameras reopen after navigation
  8520. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8521. const saved = localStorage.getItem('openEmbeddedCameras');
  8522. if (saved) {
  8523. try {
  8524. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8525. return new Map(cameras.map(c => [c.id, c]));
  8526. } catch {
  8527. return new Map();
  8528. }
  8529. }
  8530. return new Map();
  8531. });
  8532. // Persist open cameras to localStorage when they change
  8533. useEffect(() => {
  8534. const cameras = Array.from(embeddedCameraPrinters.values());
  8535. if (cameras.length > 0) {
  8536. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8537. } else {
  8538. localStorage.removeItem('openEmbeddedCameras');
  8539. }
  8540. }, [embeddedCameraPrinters]);
  8541. const { data: printers, isLoading } = useQuery({
  8542. queryKey: ['printers'],
  8543. queryFn: api.getPrinters,
  8544. });
  8545. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8546. // so users with printers:read but no settings:read still get the values needed
  8547. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8548. const { data: settings } = useQuery({
  8549. queryKey: ['ui-preferences'],
  8550. queryFn: api.getUiPreferences,
  8551. });
  8552. // Parse user-configured temperature/fan presets once, with defensive fallback
  8553. // to built-in defaults on parse failure (validators on the backend already
  8554. // reject malformed writes, so this is just forward-compat).
  8555. const effectiveNozzleTempPresets = useMemo(
  8556. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8557. [settings?.nozzle_temp_presets],
  8558. );
  8559. const effectiveBedTempPresets = useMemo(
  8560. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8561. [settings?.bed_temp_presets],
  8562. );
  8563. const effectiveChamberTempPresets = useMemo(
  8564. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8565. [settings?.chamber_temp_presets],
  8566. );
  8567. const effectiveFanSpeedPresets = useMemo(
  8568. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8569. [settings?.fan_speed_presets],
  8570. );
  8571. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8572. const effectiveDryingPresets = useMemo(() => {
  8573. if (settings?.drying_presets) {
  8574. try {
  8575. const userPresets = JSON.parse(settings.drying_presets);
  8576. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8577. return { ...DRYING_PRESETS, ...userPresets };
  8578. }
  8579. } catch { /* ignore parse errors, use defaults */ }
  8580. }
  8581. return DRYING_PRESETS;
  8582. }, [settings?.drying_presets]);
  8583. // The local choice wins over the stored one: someone without settings:update
  8584. // cannot write their pick back, and a preference that silently reverted on
  8585. // the next render would be worse than none at all.
  8586. const cameraViewMode: CameraViewMode =
  8587. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8588. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8589. storeCameraViewMode(mode);
  8590. setChosenCameraViewMode(mode);
  8591. // Best effort, and only a default for other browsers -- the choice is
  8592. // already in effect here. Users below settings:update simply keep theirs
  8593. // locally, which is why the failure is logged rather than surfaced.
  8594. if (hasPermission('settings:update')) {
  8595. api.updateSettings({ camera_view_mode: mode })
  8596. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8597. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8598. }
  8599. }, [hasPermission, queryClient]);
  8600. // Fetch all smart plugs to know which printers have them
  8601. const { data: smartPlugs } = useQuery({
  8602. queryKey: ['smart-plugs'],
  8603. queryFn: api.getSmartPlugs,
  8604. });
  8605. // Fetch maintenance overview for all printers to show badges
  8606. const { data: maintenanceOverview } = useQuery({
  8607. queryKey: ['maintenanceOverview'],
  8608. queryFn: api.getMaintenanceOverview,
  8609. staleTime: 60 * 1000, // 1 minute
  8610. });
  8611. // Live AI failure detection state for the card badges (#1546). Matches the
  8612. // 10s refetch of the Failure Detection settings panel.
  8613. const { data: obicoPrinterStatus } = useQuery({
  8614. queryKey: ['obico-printer-status'],
  8615. queryFn: api.getObicoPrinterStatus,
  8616. refetchInterval: 10000,
  8617. });
  8618. // Badge visibility: detection enabled AND this printer in the monitored set
  8619. // (monitored_printers null = all). Live per-print state is passed separately.
  8620. const isAiMonitored = useCallback(
  8621. (printerId: number) =>
  8622. obicoPrinterStatus?.enabled === true &&
  8623. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8624. [obicoPrinterStatus],
  8625. );
  8626. // Fetch Spoolman status to enable link spool feature
  8627. const { data: spoolmanStatus } = useQuery({
  8628. queryKey: ['spoolman-status'],
  8629. queryFn: api.getSpoolmanStatus,
  8630. staleTime: 60 * 1000, // 1 minute
  8631. });
  8632. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8633. // Fetch Spoolman settings to get sync mode
  8634. const { data: spoolmanSettings } = useQuery({
  8635. queryKey: ['spoolman-settings'],
  8636. queryFn: api.getSpoolmanSettings,
  8637. enabled: !!spoolmanEnabled,
  8638. staleTime: 60 * 1000, // 1 minute
  8639. });
  8640. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8641. // Fetch unlinked spools to know if link button should be enabled
  8642. const { data: unlinkedSpools } = useQuery({
  8643. queryKey: ['unlinked-spools'],
  8644. queryFn: api.getUnlinkedSpools,
  8645. enabled: !!spoolmanEnabled,
  8646. staleTime: 30 * 1000, // 30 seconds
  8647. });
  8648. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8649. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8650. const { data: linkedSpoolsData } = useQuery({
  8651. queryKey: ['linked-spools'],
  8652. queryFn: api.getLinkedSpools,
  8653. enabled: !!spoolmanEnabled,
  8654. staleTime: 30 * 1000, // 30 seconds
  8655. });
  8656. const linkedSpools = linkedSpoolsData?.linked;
  8657. // Fetch spool assignments for inventory feature
  8658. const { data: spoolAssignments } = useQuery({
  8659. queryKey: ['spool-assignments'],
  8660. queryFn: () => api.getAssignments(),
  8661. enabled: hasPermission('inventory:view_assignments'),
  8662. staleTime: 30 * 1000,
  8663. });
  8664. const unassignMutation = useMutation({
  8665. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8666. api.unassignSpool(printerId, amsId, trayId),
  8667. onSuccess: () => {
  8668. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8669. },
  8670. });
  8671. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8672. queryKey: ['spoolman-inventory-spools'],
  8673. queryFn: () => api.getSpoolmanInventorySpools(false),
  8674. enabled: !!spoolmanEnabled,
  8675. staleTime: 30 * 1000,
  8676. });
  8677. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8678. queryKey: ['spoolman-slot-assignments'],
  8679. queryFn: () => api.getSpoolmanSlotAssignments(),
  8680. enabled: !!spoolmanEnabled,
  8681. staleTime: 30 * 1000,
  8682. });
  8683. const unassignSpoolmanMutation = useMutation({
  8684. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8685. onSuccess: () => {
  8686. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8687. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8688. },
  8689. });
  8690. // Helper to find assignment for a specific slot
  8691. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8692. return spoolAssignments?.find(
  8693. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8694. );
  8695. };
  8696. // Create a map of printer_id -> maintenance info for quick lookup
  8697. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8698. (acc, overview) => {
  8699. acc[overview.printer_id] = {
  8700. due_count: overview.due_count,
  8701. warning_count: overview.warning_count,
  8702. total_print_hours: overview.total_print_hours,
  8703. };
  8704. return acc;
  8705. },
  8706. {} as Record<number, PrinterMaintenanceInfo>
  8707. ) || {};
  8708. // Create a map of printer_id -> smart plug
  8709. const smartPlugByPrinter = smartPlugs?.reduce(
  8710. (acc, plug) => {
  8711. if (plug.printer_id) {
  8712. acc[plug.printer_id] = plug;
  8713. }
  8714. return acc;
  8715. },
  8716. {} as Record<number, typeof smartPlugs[0]>
  8717. ) || {};
  8718. const addMutation = useMutation({
  8719. mutationFn: api.createPrinter,
  8720. onSuccess: () => {
  8721. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8722. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8723. setShowAddModal(false);
  8724. },
  8725. onError: (error: Error) => {
  8726. // Localized message when the backend returns a stable error code;
  8727. // the raw message is an English fallback for non-UI clients.
  8728. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8729. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8730. return;
  8731. }
  8732. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8733. },
  8734. });
  8735. const powerOnMutation = useMutation({
  8736. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8737. onSuccess: () => {
  8738. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8739. setPoweringOn(null);
  8740. },
  8741. onError: () => {
  8742. setPoweringOn(null);
  8743. },
  8744. });
  8745. // Bulk selection state
  8746. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8747. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8748. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8749. const [bulkActionPending, setBulkActionPending] = useState(false);
  8750. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8751. const toggleSelect = useCallback((id: number) => {
  8752. setSelectedPrinterIds(prev => {
  8753. const next = new Set(prev);
  8754. if (next.has(id)) next.delete(id);
  8755. else next.add(id);
  8756. return next;
  8757. });
  8758. }, []);
  8759. const clearSelection = useCallback(() => {
  8760. setSelectedPrinterIds(new Set());
  8761. setIsSelectionMode(false);
  8762. }, []);
  8763. // Escape key exits selection mode
  8764. useEffect(() => {
  8765. const handleKeyDown = (e: KeyboardEvent) => {
  8766. if (e.key === 'Escape' && selectionMode) {
  8767. clearSelection();
  8768. }
  8769. };
  8770. window.addEventListener('keydown', handleKeyDown);
  8771. return () => window.removeEventListener('keydown', handleKeyDown);
  8772. }, [selectionMode, clearSelection]);
  8773. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8774. setBulkActionPending(true);
  8775. const ids = Array.from(selectedPrinterIds);
  8776. // Filter to only applicable printers based on cached state
  8777. const applicableIds = ids.filter(id => {
  8778. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8779. // clearPlate is checked before the connection filter: it only releases a
  8780. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8781. // down — every other action here needs to reach the machine (#2864).
  8782. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8783. if (!status?.connected) return false;
  8784. switch (action) {
  8785. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8786. case 'pause': return status.state === 'RUNNING';
  8787. case 'resume': return status.state === 'PAUSE';
  8788. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8789. default: return false;
  8790. }
  8791. });
  8792. if (applicableIds.length === 0) {
  8793. showToast(t('printers.bulk.noneApplicable'), 'error');
  8794. setBulkActionPending(false);
  8795. setBulkConfirmAction(null);
  8796. return;
  8797. }
  8798. const apiCall = {
  8799. stop: api.stopPrint,
  8800. pause: api.pausePrint,
  8801. resume: api.resumePrint,
  8802. clearPlate: api.clearPlate,
  8803. clearHMS: api.clearHMSErrors,
  8804. }[action];
  8805. const results = await Promise.allSettled(
  8806. applicableIds.map(id => apiCall(id))
  8807. );
  8808. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8809. const failed = results.filter(r => r.status === 'rejected').length;
  8810. if (failed === 0) {
  8811. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8812. } else {
  8813. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8814. }
  8815. // Invalidate status queries for affected printers
  8816. applicableIds.forEach(id => {
  8817. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8818. });
  8819. setBulkActionPending(false);
  8820. setBulkConfirmAction(null);
  8821. }, [selectedPrinterIds, queryClient, showToast, t]);
  8822. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8823. // Actions that need confirmation
  8824. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8825. setBulkConfirmAction(action);
  8826. } else {
  8827. executeBulkAction(action);
  8828. }
  8829. }, [executeBulkAction]);
  8830. const toggleHideDisconnected = () => {
  8831. const newValue = !hideDisconnected;
  8832. setHideDisconnected(newValue);
  8833. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8834. };
  8835. const handleSortChange = (newSort: SortOption) => {
  8836. setSortBy(newSort);
  8837. localStorage.setItem('printerSortBy', newSort);
  8838. };
  8839. const handleStatusFilterChange = (value: string) => {
  8840. setStatusFilter(value);
  8841. localStorage.setItem('printerStatusFilter', value);
  8842. };
  8843. const handleLocationFilterChange = (value: string) => {
  8844. setLocationFilter(value);
  8845. localStorage.setItem('printerLocationFilter', value);
  8846. };
  8847. const toggleSortDirection = () => {
  8848. const newAsc = !sortAsc;
  8849. setSortAsc(newAsc);
  8850. localStorage.setItem('printerSortAsc', String(newAsc));
  8851. };
  8852. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8853. const getGridClasses = () => {
  8854. switch (cardSize) {
  8855. 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
  8856. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8857. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8858. case 4: return 'grid-cols-1'; // XL: single column, full width
  8859. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8860. }
  8861. };
  8862. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8863. // Increment version counter whenever a printer status cache entry is updated so
  8864. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8865. useEffect(() => {
  8866. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8867. if (
  8868. event.type === 'updated' &&
  8869. Array.isArray(event.query.queryKey) &&
  8870. event.query.queryKey[0] === 'printerStatus'
  8871. ) {
  8872. setStatusCacheVersion(v => v + 1);
  8873. }
  8874. });
  8875. return unsubscribe;
  8876. }, [queryClient]);
  8877. // Filter printers by search term, status, and location
  8878. const filteredPrinters = useMemo(() => {
  8879. if (!printers) return [];
  8880. let result = printers;
  8881. // Text search
  8882. if (search.trim()) {
  8883. const q = search.trim().toLowerCase();
  8884. result = result.filter(p =>
  8885. p.name.toLowerCase().includes(q) ||
  8886. (p.model || '').toLowerCase().includes(q) ||
  8887. (p.location || '').toLowerCase().includes(q) ||
  8888. (p.serial_number || '').toLowerCase().includes(q)
  8889. );
  8890. }
  8891. // Location filter
  8892. if (locationFilter !== 'all') {
  8893. result = result.filter(p => (p.location || '') === locationFilter);
  8894. }
  8895. // Status filter
  8896. if (statusFilter !== 'all') {
  8897. result = result.filter(p => {
  8898. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8899. if (!status?.connected) return statusFilter === 'offline';
  8900. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8901. switch (statusFilter) {
  8902. case 'printing': return status.state === 'RUNNING';
  8903. case 'paused': return status.state === 'PAUSE';
  8904. case 'finished': return status.state === 'FINISH';
  8905. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8906. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8907. case 'offline': return false; // Connected printers are never offline
  8908. default: return true;
  8909. }
  8910. });
  8911. }
  8912. return result;
  8913. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8914. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8915. // Derive unique locations for the location filter dropdown
  8916. const availableLocations = useMemo(() => {
  8917. if (!printers) return [];
  8918. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8919. }, [printers]);
  8920. // A saved location can outlive what it matched -- renamed, cleared, or the
  8921. // only printer that had it deleted. The dropdown is rendered only while some
  8922. // printer has a location, so a stale one would hide every printer *and* the
  8923. // control to undo it, leaving an empty page and no way back (#2833).
  8924. // Deliberately waits for `printers`: it is undefined while the query is in
  8925. // flight, and acting on the empty list that produces would throw the saved
  8926. // filter away every time the page loads.
  8927. useEffect(() => {
  8928. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8929. setLocationFilter('all');
  8930. localStorage.setItem('printerLocationFilter', 'all');
  8931. }, [printers, availableLocations, locationFilter]);
  8932. // Sort printers based on selected option
  8933. const sortedPrinters = useMemo(() => {
  8934. const sorted = [...filteredPrinters];
  8935. switch (sortBy) {
  8936. case 'name':
  8937. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8938. break;
  8939. case 'model':
  8940. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8941. break;
  8942. case 'location':
  8943. // Sort by location, with ungrouped printers last
  8944. sorted.sort((a, b) => {
  8945. const locA = a.location || '';
  8946. const locB = b.location || '';
  8947. if (!locA && locB) return 1;
  8948. if (locA && !locB) return -1;
  8949. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  8950. });
  8951. break;
  8952. case 'status':
  8953. // Sort by status: HMS errors > printing > idle > offline
  8954. sorted.sort((a, b) => {
  8955. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  8956. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  8957. const getPriority = (s: typeof statusA) => {
  8958. if (!s?.connected) return 3; // offline
  8959. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  8960. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  8961. if (s.state === 'RUNNING') return 1; // printing
  8962. return 2; // idle
  8963. };
  8964. return getPriority(statusA) - getPriority(statusB);
  8965. });
  8966. break;
  8967. case 'eta':
  8968. sorted.sort((a, b) => {
  8969. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8970. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8971. const tier = (s: typeof statusA) => {
  8972. if (!s?.connected) return 3; // offline last
  8973. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8974. if (s.state === 'RUNNING') return 1; // printing without ETA
  8975. return 2; // idle
  8976. };
  8977. const ta = tier(statusA);
  8978. const tb = tier(statusB);
  8979. if (ta !== tb) return ta - tb;
  8980. if (ta === 0) {
  8981. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8982. if (diff !== 0) return diff;
  8983. }
  8984. return a.name.localeCompare(b.name);
  8985. });
  8986. break;
  8987. }
  8988. // Apply ascending/descending
  8989. if (!sortAsc) {
  8990. sorted.reverse();
  8991. }
  8992. return sorted;
  8993. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  8994. const selectAll = useCallback(() => {
  8995. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  8996. setIsSelectionMode(true);
  8997. }, [sortedPrinters]);
  8998. const selectByState = useCallback((state: PrinterState) => {
  8999. setSelectedPrinterIds(prev => {
  9000. const next = new Set(prev);
  9001. sortedPrinters.forEach(p => {
  9002. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  9003. if (classifyPrinterStatus(status) === state) next.add(p.id);
  9004. });
  9005. return next;
  9006. });
  9007. setIsSelectionMode(true);
  9008. }, [sortedPrinters, queryClient]);
  9009. const selectByLocation = useCallback((location: string) => {
  9010. setSelectedPrinterIds(prev => {
  9011. const next = new Set(prev);
  9012. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9013. return next;
  9014. });
  9015. setIsSelectionMode(true);
  9016. }, [sortedPrinters]);
  9017. const selectByModel = useCallback((model: string) => {
  9018. setSelectedPrinterIds(prev => {
  9019. const next = new Set(prev);
  9020. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9021. return next;
  9022. });
  9023. setIsSelectionMode(true);
  9024. }, [sortedPrinters]);
  9025. const toggleSectionCollapse = useCallback((key: string) => {
  9026. setCollapsedSections(prev => {
  9027. const next = { ...prev, [key]: !prev[key] };
  9028. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9029. return next;
  9030. });
  9031. }, []);
  9032. // Group printers when sorted by location, status, or model
  9033. const groupedPrinters = useMemo(() => {
  9034. if (sortBy === 'name' || sortBy === 'eta') return null;
  9035. const groups: Record<string, typeof sortedPrinters> = {};
  9036. if (sortBy === 'location') {
  9037. sortedPrinters.forEach(printer => {
  9038. const location = printer.location || 'Ungrouped';
  9039. if (!groups[location]) groups[location] = [];
  9040. groups[location].push(printer);
  9041. });
  9042. } else if (sortBy === 'model') {
  9043. sortedPrinters.forEach(printer => {
  9044. const model = printer.model || 'Unknown';
  9045. if (!groups[model]) groups[model] = [];
  9046. groups[model].push(printer);
  9047. });
  9048. } else if (sortBy === 'status') {
  9049. sortedPrinters.forEach(printer => {
  9050. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9051. const group = classifyPrinterStatus(status);
  9052. if (!groups[group]) groups[group] = [];
  9053. groups[group].push(printer);
  9054. });
  9055. }
  9056. return groups;
  9057. // 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
  9058. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9059. const toolbarRef = useRef<HTMLDivElement>(null);
  9060. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9061. const expandedToolbarWidthRef = useRef(0);
  9062. const [compactToolbar, setCompactToolbar] = useState(false);
  9063. const measureToolbar = useCallback(() => {
  9064. const toolbar = toolbarRef.current;
  9065. if (!toolbar) return;
  9066. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9067. if (measuredControlsWidth) {
  9068. expandedToolbarWidthRef.current = measuredControlsWidth;
  9069. }
  9070. const searchMinimumWidth = 220;
  9071. const gapWidth = 8;
  9072. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9073. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9074. }, []);
  9075. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9076. useLayoutEffect(() => {
  9077. measureToolbar();
  9078. const toolbar = toolbarRef.current;
  9079. if (!toolbar) return;
  9080. if (typeof ResizeObserver === 'undefined') {
  9081. window.addEventListener('resize', measureToolbar);
  9082. return () => window.removeEventListener('resize', measureToolbar);
  9083. }
  9084. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9085. resizeObserver.observe(toolbar);
  9086. window.addEventListener('resize', measureToolbar);
  9087. return () => {
  9088. resizeObserver.disconnect();
  9089. window.removeEventListener('resize', measureToolbar);
  9090. };
  9091. }, [
  9092. measureToolbar,
  9093. printers?.length,
  9094. availableLocations.length,
  9095. hideDisconnected,
  9096. smartPlugCount,
  9097. ]);
  9098. const renderFilterControls = (inMenu = false) => (
  9099. <>
  9100. {/* Status filter */}
  9101. {printers && printers.length > 0 && (
  9102. <ToolbarDropdown
  9103. value={statusFilter}
  9104. onChange={handleStatusFilterChange}
  9105. fullWidth={inMenu}
  9106. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9107. />
  9108. )}
  9109. {/* Location filter — only shown when at least one printer has a location */}
  9110. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9111. <ToolbarDropdown
  9112. value={locationFilter}
  9113. onChange={handleLocationFilterChange}
  9114. fullWidth={inMenu}
  9115. options={[
  9116. { value: 'all', label: t('printers.filter.allLocations') },
  9117. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9118. ]}
  9119. />
  9120. )}
  9121. <button
  9122. type="button"
  9123. onClick={toggleHideDisconnected}
  9124. aria-pressed={hideDisconnected}
  9125. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9126. hideDisconnected
  9127. ? 'bg-bambu-green border-bambu-green text-white'
  9128. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9129. }`}
  9130. >
  9131. {t('printers.hideOffline')}
  9132. </button>
  9133. </>
  9134. );
  9135. const renderViewControls = (inMenu = false) => (
  9136. <>
  9137. {/* Sort dropdown */}
  9138. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9139. <ToolbarDropdown<SortOption>
  9140. value={sortBy}
  9141. onChange={handleSortChange}
  9142. fullWidth={inMenu}
  9143. options={[
  9144. { value: 'name', label: t('printers.sort.name') },
  9145. { value: 'status', label: t('printers.sort.status') },
  9146. { value: 'model', label: t('printers.sort.model') },
  9147. { value: 'location', label: t('printers.sort.location') },
  9148. { value: 'eta', label: t('printers.sort.eta') },
  9149. ]}
  9150. />
  9151. <button
  9152. onClick={toggleSortDirection}
  9153. 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"
  9154. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9155. >
  9156. {sortAsc ? (
  9157. <ArrowUp className="w-4 h-4 text-white" />
  9158. ) : (
  9159. <ArrowDown className="w-4 h-4 text-white" />
  9160. )}
  9161. </button>
  9162. </div>
  9163. {/* Page view toggle: Cards / Cam Wall */}
  9164. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9165. <button
  9166. type="button"
  9167. onClick={() => {
  9168. setPageView('cards');
  9169. localStorage.setItem('printerPageView', 'cards');
  9170. }}
  9171. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9172. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9173. }`}
  9174. title={t('printers.pageView.cards')}
  9175. aria-pressed={pageView === 'cards'}
  9176. >
  9177. <LayoutGrid className="w-3.5 h-3.5" />
  9178. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9179. </button>
  9180. <button
  9181. type="button"
  9182. onClick={() => {
  9183. setPageView('camwall');
  9184. localStorage.setItem('printerPageView', 'camwall');
  9185. }}
  9186. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9187. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9188. }`}
  9189. title={t('printers.pageView.camWall')}
  9190. aria-pressed={pageView === 'camwall'}
  9191. disabled={!hasPermission('camera:view')}
  9192. >
  9193. <MonitorPlay className="w-3.5 h-3.5" />
  9194. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9195. </button>
  9196. </div>
  9197. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9198. view, and the page a kiosk token points at. Only offered once the wall
  9199. is the active view, so it doesn't compete with the toggle above. */}
  9200. {pageView === 'camwall' && hasPermission('camera:view') && (
  9201. <RouterLink
  9202. to="/camwall"
  9203. 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' : ''}`}
  9204. title={t('printers.pageView.openCamWallPage')}
  9205. >
  9206. <ExternalLink className="w-3.5 h-3.5" />
  9207. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9208. </RouterLink>
  9209. )}
  9210. {/* Card size selector */}
  9211. <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' : ''}`}>
  9212. {cardSizeLabels.map((label, index) => {
  9213. const size = index + 1;
  9214. const isSelected = cardSize === size;
  9215. return (
  9216. <button
  9217. key={label}
  9218. onClick={() => {
  9219. setCompactDrilldownPrinterId(null);
  9220. setCardSize(size);
  9221. localStorage.setItem('printerCardSize', String(size));
  9222. }}
  9223. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9224. index === 0 ? 'rounded-l-lg' : ''
  9225. } ${
  9226. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9227. } ${
  9228. isSelected
  9229. ? 'bg-bambu-green text-white'
  9230. : 'text-white hover:bg-bambu-dark-tertiary'
  9231. }`}
  9232. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  9233. >
  9234. {label}
  9235. </button>
  9236. );
  9237. })}
  9238. </div>
  9239. </>
  9240. );
  9241. const renderActionControls = (inMenu = false) => (
  9242. <>
  9243. {/* Bulk select toggle */}
  9244. <button
  9245. onClick={() => {
  9246. if (selectionMode) clearSelection();
  9247. else setIsSelectionMode(true);
  9248. }}
  9249. 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' : ''} ${
  9250. selectionMode
  9251. ? 'bg-bambu-green border-bambu-green text-white'
  9252. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9253. }`}
  9254. title={t('printers.bulk.select')}
  9255. disabled={!hasPermission('printers:control')}
  9256. >
  9257. <CheckSquare className="w-4 h-4" />
  9258. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9259. </button>
  9260. {/* Power dropdown for offline printers with smart plugs */}
  9261. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9262. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9263. <button
  9264. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9265. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9266. inMenu
  9267. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9268. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9269. }`}
  9270. >
  9271. <span className="flex items-center gap-1.5">
  9272. <Power className="w-4 h-4" />
  9273. {t('printers.powerOn')}
  9274. </span>
  9275. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9276. </button>
  9277. {showPowerDropdown && (
  9278. <>
  9279. {/* Backdrop to close dropdown */}
  9280. <div
  9281. className="fixed inset-0 z-10"
  9282. onClick={() => setShowPowerDropdown(false)}
  9283. />
  9284. <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">
  9285. <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">
  9286. {t('printers.offlinePrintersWithPlugs')}
  9287. </div>
  9288. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9289. <PowerDropdownItem
  9290. key={printer.id}
  9291. printer={printer}
  9292. plug={smartPlugByPrinter[printer.id]}
  9293. onPowerOn={(plugId) => {
  9294. setPoweringOn(plugId);
  9295. powerOnMutation.mutate(plugId);
  9296. }}
  9297. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9298. />
  9299. ))}
  9300. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9301. <div className="px-3 py-2 text-sm text-bambu-gray">
  9302. No printers with smart plugs
  9303. </div>
  9304. )}
  9305. </div>
  9306. </>
  9307. )}
  9308. </div>
  9309. )}
  9310. <Button
  9311. onClick={() => setShowAddModal(true)}
  9312. disabled={!hasPermission('printers:create')}
  9313. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9314. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9315. >
  9316. <Plus className="w-4 h-4" />
  9317. {t('printers.addPrinter')}
  9318. </Button>
  9319. </>
  9320. );
  9321. return (
  9322. <div className="p-4 md:p-8">
  9323. <div className="space-y-3 mb-6">
  9324. <div>
  9325. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9326. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9327. {t('printers.title')}
  9328. </h1>
  9329. <StatusSummaryBar printers={printers} />
  9330. </div>
  9331. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9332. {/* Only show search bar when printers exist */}
  9333. {printers && printers.length > 0 && (
  9334. <div className="relative min-w-0 flex-1">
  9335. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9336. <input
  9337. type="search"
  9338. name="printer-search"
  9339. autoComplete="off"
  9340. data-1p-ignore
  9341. data-lpignore="true"
  9342. value={search}
  9343. onChange={(e) => setSearch(e.target.value)}
  9344. placeholder={t('printers.search')}
  9345. aria-label={t('printers.search')}
  9346. 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"
  9347. />
  9348. {search && (
  9349. <button
  9350. type="button"
  9351. aria-label={t('common.clear')}
  9352. onClick={() => setSearch('')}
  9353. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9354. >
  9355. <X className="w-4 h-4" />
  9356. </button>
  9357. )}
  9358. </div>
  9359. )}
  9360. <div
  9361. ref={expandedToolbarControlsRef}
  9362. aria-hidden={compactToolbar}
  9363. inert={compactToolbar}
  9364. 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`}
  9365. >
  9366. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9367. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9368. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9369. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9370. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9371. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9372. </div>
  9373. {compactToolbar && (
  9374. <div className="ml-auto flex items-center justify-end gap-1">
  9375. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9376. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9377. </ToolbarMenu>
  9378. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9379. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9380. </ToolbarMenu>
  9381. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9382. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9383. </ToolbarMenu>
  9384. </div>
  9385. )}
  9386. </div>
  9387. </div>
  9388. {isLoading ? (
  9389. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9390. ) : printers?.length === 0 ? (
  9391. <Card>
  9392. <CardContent className="text-center py-12">
  9393. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9394. <Button
  9395. onClick={() => setShowAddModal(true)}
  9396. disabled={!hasPermission('printers:create')}
  9397. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9398. >
  9399. <Plus className="w-4 h-4" />
  9400. {t('printers.addPrinter')}
  9401. </Button>
  9402. </CardContent>
  9403. </Card>
  9404. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9405. <Card>
  9406. <CardContent className="text-center py-12">
  9407. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9408. </CardContent>
  9409. </Card>
  9410. ) : pageView === 'camwall' ? (
  9411. <CameraWall
  9412. printers={sortedPrinters}
  9413. maxLive={camWallMaxLive}
  9414. snapshotIntervalSec={camWallSnapshotSec}
  9415. onTileClick={(id, name) => {
  9416. // A wall tile has no room for a split button, so it follows the
  9417. // mode the card buttons last chose.
  9418. if (cameraViewMode === 'embedded') {
  9419. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9420. } else {
  9421. openCameraWindow(id);
  9422. }
  9423. }}
  9424. statusMode={camWallStatusMode}
  9425. onChangeMaxLive={(next) => {
  9426. setCamWallMaxLive(next);
  9427. localStorage.setItem('camWallMaxLive', String(next));
  9428. }}
  9429. onChangeSnapshotIntervalSec={(next) => {
  9430. setCamWallSnapshotSec(next);
  9431. localStorage.setItem('camWallSnapshotSec', String(next));
  9432. }}
  9433. onChangeStatusMode={(next) => {
  9434. setCamWallStatusMode(next);
  9435. localStorage.setItem('camWallStatusMode', next);
  9436. }}
  9437. />
  9438. ) : groupedPrinters ? (
  9439. /* Grouped view (location, status, or model) */
  9440. <div className="space-y-6">
  9441. {(() => {
  9442. const keys = sortBy === 'status'
  9443. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9444. : Object.keys(groupedPrinters);
  9445. // For status grouping, asc/desc flips the fixed priority order
  9446. // (asc = error→offline, desc = offline→error). This matches the
  9447. // sort-toggle behaviour for other groupings.
  9448. return (sortAsc ? keys : [...keys].reverse());
  9449. })().map((groupKey) => {
  9450. const groupPrinters = groupedPrinters[groupKey];
  9451. const collapseKey = `${sortBy}:${groupKey}`;
  9452. const isOpen = !collapsedSections[collapseKey];
  9453. const dot = sortBy === 'status'
  9454. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9455. : 'bg-bambu-green';
  9456. const label = sortBy === 'status'
  9457. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9458. : groupKey;
  9459. return (
  9460. <Collapsible
  9461. key={groupKey}
  9462. open={isOpen}
  9463. onToggle={() => toggleSectionCollapse(collapseKey)}
  9464. summaryClassName="py-1"
  9465. summary={
  9466. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9467. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9468. {label}
  9469. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9470. {selectionMode && (
  9471. <button
  9472. onClick={(e) => {
  9473. e.stopPropagation();
  9474. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9475. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9476. else if (sortBy === 'model') selectByModel(groupKey);
  9477. }}
  9478. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9479. >
  9480. {t('printers.bulk.selectAll')}
  9481. </button>
  9482. )}
  9483. </h2>
  9484. }
  9485. >
  9486. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9487. {groupPrinters.map((printer) => (
  9488. <PrinterCard
  9489. key={printer.id}
  9490. printer={printer}
  9491. hideIfDisconnected={hideDisconnected}
  9492. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9493. viewMode={viewMode}
  9494. cardSize={cardSize}
  9495. amsThresholds={settings ? {
  9496. humidityGood: Number(settings.ams_humidity_good) || 40,
  9497. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9498. tempGood: Number(settings.ams_temp_good) || 28,
  9499. tempFair: Number(settings.ams_temp_fair) || 35,
  9500. } : undefined}
  9501. spoolmanEnabled={spoolmanEnabled}
  9502. hasUnlinkedSpools={hasUnlinkedSpools}
  9503. linkedSpools={linkedSpools}
  9504. spoolmanUrl={spoolmanStatus?.url}
  9505. spoolmanSyncMode={spoolmanSyncMode}
  9506. onGetAssignment={getAssignment}
  9507. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9508. spoolmanSpools={spoolmanSpools}
  9509. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9510. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9511. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9512. timeFormat={settings?.time_format || 'system'}
  9513. cameraViewMode={cameraViewMode}
  9514. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9515. onSelectCameraViewMode={selectCameraViewMode}
  9516. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9517. dryingPresets={effectiveDryingPresets}
  9518. nozzleTempPresets={effectiveNozzleTempPresets}
  9519. bedTempPresets={effectiveBedTempPresets}
  9520. chamberTempPresets={effectiveChamberTempPresets}
  9521. fanSpeedPresets={effectiveFanSpeedPresets}
  9522. requirePlateClear={settings?.require_plate_clear === true}
  9523. selectionMode={selectionMode}
  9524. isSelected={selectedPrinterIds.has(printer.id)}
  9525. onToggleSelect={toggleSelect}
  9526. onOpenCompactCard={openCompactCard}
  9527. aiDetectionEnabled={isAiMonitored(printer.id)}
  9528. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9529. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9530. />
  9531. ))}
  9532. </div>
  9533. </Collapsible>
  9534. );
  9535. })}
  9536. </div>
  9537. ) : (
  9538. /* Regular grid view */
  9539. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9540. {sortedPrinters.map((printer) => (
  9541. <PrinterCard
  9542. key={printer.id}
  9543. printer={printer}
  9544. hideIfDisconnected={hideDisconnected}
  9545. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9546. viewMode={viewMode}
  9547. cardSize={cardSize}
  9548. spoolmanEnabled={spoolmanEnabled}
  9549. hasUnlinkedSpools={hasUnlinkedSpools}
  9550. linkedSpools={linkedSpools}
  9551. spoolmanUrl={spoolmanStatus?.url}
  9552. spoolmanSyncMode={spoolmanSyncMode}
  9553. onGetAssignment={getAssignment}
  9554. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9555. spoolmanSpools={spoolmanSpools}
  9556. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9557. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9558. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9559. amsThresholds={settings ? {
  9560. humidityGood: Number(settings.ams_humidity_good) || 40,
  9561. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9562. tempGood: Number(settings.ams_temp_good) || 28,
  9563. tempFair: Number(settings.ams_temp_fair) || 35,
  9564. } : undefined}
  9565. timeFormat={settings?.time_format || 'system'}
  9566. cameraViewMode={cameraViewMode}
  9567. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9568. onSelectCameraViewMode={selectCameraViewMode}
  9569. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9570. dryingPresets={effectiveDryingPresets}
  9571. nozzleTempPresets={effectiveNozzleTempPresets}
  9572. bedTempPresets={effectiveBedTempPresets}
  9573. chamberTempPresets={effectiveChamberTempPresets}
  9574. fanSpeedPresets={effectiveFanSpeedPresets}
  9575. requirePlateClear={settings?.require_plate_clear === true}
  9576. selectionMode={selectionMode}
  9577. isSelected={selectedPrinterIds.has(printer.id)}
  9578. onToggleSelect={toggleSelect}
  9579. onOpenCompactCard={openCompactCard}
  9580. aiDetectionEnabled={isAiMonitored(printer.id)}
  9581. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9582. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9583. />
  9584. ))}
  9585. </div>
  9586. )}
  9587. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9588. <button
  9589. type="button"
  9590. onClick={returnToCompactCards}
  9591. 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}`}
  9592. title={t('common.back', 'Back')}
  9593. >
  9594. <ArrowLeft className="w-4 h-4" />
  9595. {t('common.back', 'Back')}
  9596. </button>
  9597. )}
  9598. {showAddModal && (
  9599. <AddPrinterModal
  9600. onClose={() => setShowAddModal(false)}
  9601. onAdd={(data) => addMutation.mutate(data)}
  9602. existingSerials={printers?.map(p => p.serial_number) || []}
  9603. />
  9604. )}
  9605. {/* Bulk selection toolbar */}
  9606. {selectionMode && printers && (
  9607. <BulkPrinterToolbar
  9608. selectedIds={selectedPrinterIds}
  9609. printers={printers}
  9610. onClose={clearSelection}
  9611. onSelectAll={selectAll}
  9612. onSelectByLocation={selectByLocation}
  9613. onSelectByState={selectByState}
  9614. onAction={handleBulkAction}
  9615. actionPending={bulkActionPending}
  9616. />
  9617. )}
  9618. {/* Bulk action confirmation modals */}
  9619. {bulkConfirmAction === 'stop' && (
  9620. <ConfirmModal
  9621. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9622. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9623. confirmText={t('printers.bulk.confirm.stopButton')}
  9624. variant="danger"
  9625. isLoading={bulkActionPending}
  9626. onConfirm={() => executeBulkAction('stop')}
  9627. onCancel={() => setBulkConfirmAction(null)}
  9628. />
  9629. )}
  9630. {bulkConfirmAction === 'pause' && (
  9631. <ConfirmModal
  9632. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9633. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9634. confirmText={t('printers.bulk.confirm.pauseButton')}
  9635. isLoading={bulkActionPending}
  9636. onConfirm={() => executeBulkAction('pause')}
  9637. onCancel={() => setBulkConfirmAction(null)}
  9638. />
  9639. )}
  9640. {bulkConfirmAction === 'clearPlate' && (
  9641. <ConfirmModal
  9642. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9643. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9644. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9645. isLoading={bulkActionPending}
  9646. onConfirm={() => executeBulkAction('clearPlate')}
  9647. onCancel={() => setBulkConfirmAction(null)}
  9648. />
  9649. )}
  9650. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9651. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9652. <EmbeddedCameraViewer
  9653. key={camera.id}
  9654. printerId={camera.id}
  9655. printerName={camera.name}
  9656. viewerIndex={index}
  9657. onClose={() => setEmbeddedCameraPrinters(prev => {
  9658. const next = new Map(prev);
  9659. next.delete(camera.id);
  9660. return next;
  9661. })}
  9662. />
  9663. ))}
  9664. </div>
  9665. );
  9666. }