PrintersPage.tsx 497 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { mapModelCode } from '../utils/printerModel';
  5. import { formatPrintName } from '../utils/printName';
  6. import { isBedSlinger } from '../utils/bedSlinger';
  7. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  8. import {
  9. openCameraWindow,
  10. readStoredCameraViewMode,
  11. storeCameraViewMode,
  12. type CameraViewMode,
  13. } from '../utils/camera';
  14. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  15. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  16. import {
  17. isExternalSpoolHidden,
  18. setExternalSpoolHidden as persistExternalSpoolHidden,
  19. } from '../utils/printerCardPrefs';
  20. import {
  21. BED_TEMP_DEFAULTS,
  22. CHAMBER_TEMP_DEFAULTS,
  23. FAN_SPEED_DEFAULTS,
  24. NOZZLE_TEMP_DEFAULTS,
  25. buildPresetOptions,
  26. parsePresetTriple,
  27. } from '../utils/temperatureFanPresets';
  28. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  29. // covers header + filament select + temp slider + duration + rotate-tray
  30. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  31. // earlier); under-estimating leaves the popover clipped off the bottom (the
  32. // original bug at #1447).
  33. const DRYING_POPOVER_WIDTH = 240;
  34. // Height in "now" mode plus the tallest start-mode control; a conservative
  35. // over-estimate just flips the popover above the trigger sooner.
  36. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  37. // Delay presets for the "After delay" drying start mode, in minutes.
  38. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  39. // Every printer card reads the same fleet-wide scheduled-drying list.
  40. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  41. // Why a due run has not started yet: every waiting_reason the scheduler can
  42. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  43. // for ..." with no hint why nothing is happening.
  44. const WAITING_REASON_KEYS: Record<string, string> = {
  45. ams_power_required: 'printers.drying.powerRequired',
  46. ams_retract_filament: 'printers.drying.retractFilament',
  47. ams_blocked: 'printers.drying.cannotDryNow',
  48. ams_not_found: 'printers.drying.waitingAmsNotFound',
  49. printer_offline: 'printers.drying.waitingOffline',
  50. printer_busy: 'printers.drying.waitingPrinterBusy',
  51. already_drying: 'printers.drying.waitingAlreadyDrying',
  52. interrupted: 'printers.drying.waitingInterrupted',
  53. };
  54. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  55. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  56. }
  57. // Why a scheduled drying failed, by the code the scheduler stores. A row with
  58. // no code (failed before codes existed) or an unknown one shows the backend's
  59. // English error_message instead.
  60. const FAILED_REASON_KEYS: Record<string, string> = {
  61. screen_only: 'printers.drying.screenOnly',
  62. unsupported: 'printers.drying.notSupported',
  63. did_not_start: 'printers.drying.scheduleFailedDidNotStart',
  64. };
  65. function failedReasonKey(code: string | null | undefined): string | undefined {
  66. return code ? FAILED_REASON_KEYS[code] : undefined;
  67. }
  68. // Which cannot-dry code to name when the firmware reports several at once.
  69. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  70. // button's tooltip and a scheduled row's waiting reason describe one blocked
  71. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  72. // left at the outlet, and both need the user to go and do something. The rest
  73. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  74. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  75. const codes = (reasons ?? []).map(r => Number(r));
  76. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  77. if (codes.includes(3)) return 'printers.drying.retractFilament';
  78. return 'printers.drying.cannotDryNow';
  79. }
  80. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  81. import { useTranslation } from 'react-i18next';
  82. import { useTheme } from '../contexts/ThemeContext';
  83. import { useAuth } from '../contexts/AuthContext';
  84. import {
  85. Plus,
  86. Link,
  87. Unlink,
  88. Signal,
  89. Clock,
  90. MoreVertical,
  91. Trash2,
  92. RefreshCw,
  93. RotateCw,
  94. Box,
  95. HardDrive,
  96. AlertTriangle,
  97. AlertCircle,
  98. Terminal,
  99. Power,
  100. Zap,
  101. Wrench,
  102. ChevronDown,
  103. Eye,
  104. EyeOff,
  105. Filter,
  106. Pencil,
  107. ArrowLeft,
  108. ArrowRight,
  109. ArrowUp,
  110. ArrowDown,
  111. Layers,
  112. Video,
  113. Search,
  114. Loader2,
  115. Square,
  116. Pause,
  117. Play,
  118. X,
  119. Fan,
  120. Wind,
  121. AirVent,
  122. Download,
  123. ScanSearch,
  124. CheckCircle,
  125. CheckSquare,
  126. XCircle,
  127. User,
  128. Home,
  129. Printer as PrinterIcon,
  130. Info,
  131. Cable,
  132. Flame,
  133. Hourglass,
  134. Repeat,
  135. Snowflake,
  136. Gauge,
  137. DoorOpen,
  138. DoorClosed,
  139. Move,
  140. LogIn,
  141. LogOut,
  142. MoreHorizontal,
  143. SlidersHorizontal,
  144. Stethoscope,
  145. ScanEye,
  146. LineChart as LineChartIcon,
  147. LayoutGrid,
  148. MonitorPlay,
  149. ExternalLink,
  150. PictureInPicture2,
  151. ThumbsUp,
  152. ThumbsDown,
  153. } from 'lucide-react';
  154. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  155. // Aliased: lucide-react already exports a `Link` icon into this module.
  156. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  157. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  158. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  159. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  160. import { Card, CardContent } from '../components/Card';
  161. import { Button } from '../components/Button';
  162. import { ConfirmModal } from '../components/ConfirmModal';
  163. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  164. import { FileManagerModal } from '../components/FileManagerModal';
  165. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  166. import { CameraWall } from '../components/CameraWall';
  167. import { DEFAULT_CAM_WALL_TILE_SIZE } from '../components/camWallTileSize';
  168. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  169. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  170. import { HMSErrorModal, filterKnownHMSErrors, isSevereHMSError } from '../components/HMSErrorModal';
  171. import { AiDetectionModal } from '../components/AiDetectionModal';
  172. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  173. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  174. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  175. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  176. import { AmsBackupModal } from '../components/AmsBackupModal';
  177. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  178. import type { HeaterSensorKind } from '../api/client';
  179. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  180. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  181. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  182. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  183. import { useToast } from '../contexts/ToastContext';
  184. import { ChamberLight } from '../components/icons/ChamberLight';
  185. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  186. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  187. import { FileUploadModal } from '../components/FileUploadModal';
  188. import { PrintModal } from '../components/PrintModal';
  189. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  190. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  191. import { getAmsLabel, getEmptySlotKind, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  192. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  193. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  194. import { Collapsible } from '../components/Collapsible';
  195. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  196. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  197. import { NumberInput } from '../components/NumberInput';
  198. // The status filter's options, and the only values it may hold. One list so a
  199. // saved filter cannot be validated against a set the dropdown has since moved
  200. // on from (#2833). Labels stay literal so they remain greppable.
  201. const STATUS_FILTER_OPTIONS = [
  202. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  203. { value: 'printing', labelKey: 'printers.status.printing' },
  204. { value: 'paused', labelKey: 'printers.status.paused' },
  205. { value: 'idle', labelKey: 'printers.status.idle' },
  206. { value: 'finished', labelKey: 'printers.status.finished' },
  207. { value: 'error', labelKey: 'printers.status.error' },
  208. { value: 'offline', labelKey: 'printers.status.offline' },
  209. ] as const;
  210. function isKnownStatusFilter(value: string | null): boolean {
  211. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  212. }
  213. export interface SpoolmanSlotAssignmentRow {
  214. printer_id: number;
  215. ams_id: number;
  216. tray_id: number;
  217. spoolman_spool_id: number;
  218. }
  219. // Color names resolve via getColorName() which reads the backend color_catalog
  220. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  221. // Format K value with 3 decimal places, default to 0.020 if null
  222. function formatKValue(k: number | null | undefined): string {
  223. const value = k ?? 0.020;
  224. return value.toFixed(3);
  225. }
  226. // K-profile value shown on the slot card itself (#2532) rather than only inside
  227. // the hover popup, the way BambuStudio shows it per slot.
  228. //
  229. // `k` arrives already gated on the slot being loaded; falsy means the printer
  230. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  231. // missing value, which is captioned inside the hover card but would read as a
  232. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  233. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  234. // reported 0 makes that expression evaluate to the number 0, and React renders
  235. // numbers, putting a bare "0" under the material name.
  236. //
  237. // `reserve` holds the row's height open on the slots without a value whenever
  238. // some other slot on the same card has one, so every fill bar stays on one line.
  239. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  240. const { t } = useTranslation();
  241. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  242. if (!k) {
  243. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  244. }
  245. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  246. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  247. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  248. // family per browser and so measured differently in Safari.
  249. return (
  250. <div className={className} title={t('ams.kFactor')}>
  251. {t('ams.kFactorShort')} {formatKValue(k)}
  252. </div>
  253. );
  254. }
  255. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  256. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  257. const { mode } = useTheme();
  258. const { t } = useTranslation();
  259. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  260. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  261. return (
  262. <span
  263. 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"
  264. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  265. title={side === 'L' ? t('common.left') : t('common.right')}
  266. >
  267. {side}
  268. </span>
  269. );
  270. }
  271. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  272. // deliberately a different colour, because it means something different: this
  273. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  274. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  275. const { mode } = useTheme();
  276. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  277. return (
  278. <span
  279. 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"
  280. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  281. title={title}
  282. >
  283. {FTS_INLET_SIDE[inlet]}
  284. </span>
  285. );
  286. }
  287. /**
  288. * Which side indicator, if any, belongs on an AMS card header.
  289. *
  290. * Three sources, in descending authority:
  291. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  292. * through the switch, so the inlet is the only meaningful label.
  293. * 2. A real extruder id from ams_extruder_map.
  294. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  295. * never reported a map. This one is only a guess, and it is suppressed
  296. * when a switch is installed: with an FTS every unit reports extruder
  297. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  298. * nothing but their unit numbers.
  299. */
  300. function amsSideBadge(
  301. amsId: number,
  302. amsExtruderMap: Record<string, number>,
  303. amsSwitchInlet: Record<string, 'A' | 'B'>,
  304. ftsInstalled: boolean
  305. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  306. const inlet = amsSwitchInlet[String(amsId)];
  307. if (inlet) return { kind: 'inlet', inlet };
  308. const mapped = amsExtruderMap[String(amsId)];
  309. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  310. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  311. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  312. return null;
  313. }
  314. // Expand nozzle type codes to material names
  315. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  316. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  317. function nozzleTypeName(type: string, t: (key: string) => string): string {
  318. if (!type) return '';
  319. // Full text names (from main nozzle info)
  320. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  321. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  322. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  323. // 4-char codes (e.g. "HS01"): last 2 digits = material
  324. if (type.length >= 4) {
  325. const material = type.slice(2, 4);
  326. if (material === '00') return t('printers.nozzleStainlessSteel');
  327. if (material === '01') return t('printers.nozzleHardenedSteel');
  328. if (material === '05') return t('printers.nozzleTungstenCarbide');
  329. }
  330. // 2-digit numeric codes
  331. if (type === '00') return t('printers.nozzleStainlessSteel');
  332. if (type === '01') return t('printers.nozzleHardenedSteel');
  333. if (type === '05') return t('printers.nozzleTungstenCarbide');
  334. // 2-char alpha codes: H prefix = hardened steel
  335. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  336. return type;
  337. }
  338. // Parse flow type from nozzle type code
  339. // HH = high flow, HS = standard/normal
  340. function nozzleFlowName(type: string, t: (key: string) => string): string {
  341. if (!type) return '';
  342. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  343. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  344. return '';
  345. }
  346. // Per-slot hover card for nozzle rack
  347. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  348. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  349. slot: import('../api/client').NozzleRackSlot;
  350. index: number;
  351. activeStatus?: boolean;
  352. filamentName?: string;
  353. children: React.ReactNode;
  354. }) {
  355. const { t } = useTranslation();
  356. const [isVisible, setIsVisible] = useState(false);
  357. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  358. const triggerRef = useRef<HTMLDivElement>(null);
  359. const cardRef = useRef<HTMLDivElement>(null);
  360. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  361. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  362. const isMounted = slot.stat === 1;
  363. useEffect(() => {
  364. if (isVisible && triggerRef.current && cardRef.current) {
  365. const triggerRect = triggerRef.current.getBoundingClientRect();
  366. const cardHeight = cardRef.current.offsetHeight;
  367. const headerHeight = 56;
  368. const spaceAbove = triggerRect.top - headerHeight;
  369. const spaceBelow = window.innerHeight - triggerRect.bottom;
  370. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  371. setPosition('bottom');
  372. } else {
  373. setPosition('top');
  374. }
  375. }
  376. }, [isVisible]);
  377. const handleMouseEnter = () => {
  378. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  379. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  380. };
  381. const handleMouseLeave = () => {
  382. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  383. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  384. };
  385. useEffect(() => {
  386. return () => {
  387. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  388. };
  389. }, []);
  390. const filamentCss = parseFilamentColor(slot.filament_color);
  391. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  392. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  393. return (
  394. <div
  395. ref={triggerRef}
  396. className="relative"
  397. onMouseEnter={handleMouseEnter}
  398. onMouseLeave={handleMouseLeave}
  399. >
  400. {children}
  401. {isVisible && (
  402. <div
  403. ref={cardRef}
  404. className={`
  405. absolute left-1/2 -translate-x-1/2 z-50
  406. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  407. animate-in fade-in-0 zoom-in-95 duration-150
  408. `}
  409. style={{ maxWidth: 'calc(100vw - 24px)' }}
  410. >
  411. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  412. {isEmpty ? (
  413. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  414. Slot {index + 1} — Empty
  415. </div>
  416. ) : (
  417. <div className="p-2.5 space-y-1.5">
  418. {/* Diameter */}
  419. <div className="flex items-center justify-between">
  420. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  421. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  422. </div>
  423. {/* Type */}
  424. {typeFull && (
  425. <div className="flex items-center justify-between">
  426. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  427. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  428. </div>
  429. )}
  430. {/* Flow (hide if empty) */}
  431. {flowFull && (
  432. <div className="flex items-center justify-between">
  433. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  434. <span className="text-xs text-white font-semibold">{flowFull}</span>
  435. </div>
  436. )}
  437. {/* Status badge */}
  438. <div className="flex items-center justify-between">
  439. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  440. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  441. activeStatus || isMounted
  442. ? 'bg-green-900/50 text-green-400'
  443. : 'bg-bambu-dark-tertiary text-bambu-gray'
  444. }`}>
  445. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  446. </span>
  447. </div>
  448. {/* Wear (hide if null) */}
  449. {slot.wear != null && (
  450. <div className="flex items-center justify-between">
  451. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  452. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  453. </div>
  454. )}
  455. {/* Max Temp (hide if 0) */}
  456. {slot.max_temp > 0 && (
  457. <div className="flex items-center justify-between">
  458. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  459. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  460. </div>
  461. )}
  462. {/* Serial (hide if empty) */}
  463. {slot.serial_number && (
  464. <div className="flex items-center justify-between">
  465. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  466. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  467. </div>
  468. )}
  469. {/* Filament: material type + color swatch (hide if no color) */}
  470. {(filamentCss || slot.filament_type) && (
  471. <div className="flex items-center justify-between">
  472. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  473. <div className="flex items-center gap-1">
  474. {filamentCss && (
  475. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  476. )}
  477. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  478. </div>
  479. </div>
  480. )}
  481. </div>
  482. )}
  483. </div>
  484. {/* Arrow pointer */}
  485. <div
  486. className={`
  487. absolute left-1/2 -translate-x-1/2 w-0 h-0
  488. border-l-[6px] border-l-transparent
  489. border-r-[6px] border-r-transparent
  490. ${position === 'top'
  491. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  492. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  493. `}
  494. />
  495. </div>
  496. )}
  497. </div>
  498. );
  499. }
  500. // Dual-nozzle hover card showing L and R nozzle details side by side
  501. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  502. leftSlot?: import('../api/client').NozzleRackSlot;
  503. rightSlot?: import('../api/client').NozzleRackSlot;
  504. activeNozzle: 'L' | 'R';
  505. filamentInfo?: Record<string, { name: string; k: number | null }>;
  506. children: React.ReactNode;
  507. }) {
  508. const { t } = useTranslation();
  509. const [isVisible, setIsVisible] = useState(false);
  510. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  511. const triggerRef = useRef<HTMLDivElement>(null);
  512. const cardRef = useRef<HTMLDivElement>(null);
  513. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  514. useEffect(() => {
  515. if (isVisible && triggerRef.current && cardRef.current) {
  516. const triggerRect = triggerRef.current.getBoundingClientRect();
  517. const cardHeight = cardRef.current.offsetHeight;
  518. const headerHeight = 56;
  519. const spaceAbove = triggerRect.top - headerHeight;
  520. const spaceBelow = window.innerHeight - triggerRect.bottom;
  521. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  522. setPosition('bottom');
  523. } else {
  524. setPosition('top');
  525. }
  526. }
  527. }, [isVisible]);
  528. const handleMouseEnter = () => {
  529. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  530. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  531. };
  532. const handleMouseLeave = () => {
  533. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  534. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  535. };
  536. useEffect(() => {
  537. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  538. }, []);
  539. if (!leftSlot && !rightSlot) return <>{children}</>;
  540. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  541. const isActive = activeNozzle === side;
  542. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  543. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  544. const filamentCss = parseFilamentColor(slot.filament_color);
  545. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  546. return (
  547. <div className="flex-1 space-y-1.5">
  548. <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'}`}>
  549. {side === 'L' ? t('common.left') : t('common.right')}
  550. </div>
  551. {slot.nozzle_diameter && (
  552. <div className="flex items-center justify-between">
  553. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  554. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  555. </div>
  556. )}
  557. {typeFull && (
  558. <div className="flex items-center justify-between">
  559. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  560. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  561. </div>
  562. )}
  563. {flowFull && (
  564. <div className="flex items-center justify-between">
  565. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  566. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  567. </div>
  568. )}
  569. <div className="flex items-center justify-between">
  570. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  571. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  572. isActive
  573. ? 'bg-green-900/50 text-green-400'
  574. : 'bg-bambu-dark-tertiary text-bambu-gray'
  575. }`}>
  576. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  577. </span>
  578. </div>
  579. {slot.wear != null && (
  580. <div className="flex items-center justify-between">
  581. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  582. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  583. </div>
  584. )}
  585. {/* Serial and max temp only available on the right (removable) nozzle */}
  586. {side === 'R' && slot.max_temp > 0 && (
  587. <div className="flex items-center justify-between">
  588. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  589. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  590. </div>
  591. )}
  592. {side === 'R' && slot.serial_number && (
  593. <div className="flex items-center justify-between">
  594. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  595. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  596. </div>
  597. )}
  598. {(filamentCss || slot.filament_type || slot.filament_id) && (
  599. <div className="flex items-center justify-between">
  600. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  601. <div className="flex items-center gap-1">
  602. {filamentCss && (
  603. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  604. )}
  605. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  606. {filamentName || slot.filament_type || slot.filament_id || ''}
  607. </span>
  608. </div>
  609. </div>
  610. )}
  611. </div>
  612. );
  613. };
  614. return (
  615. <div
  616. ref={triggerRef}
  617. className="relative flex-1"
  618. onMouseEnter={handleMouseEnter}
  619. onMouseLeave={handleMouseLeave}
  620. >
  621. {children}
  622. {isVisible && (
  623. <div
  624. ref={cardRef}
  625. className={`
  626. absolute left-1/2 -translate-x-1/2 z-50
  627. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  628. animate-in fade-in-0 zoom-in-95 duration-150
  629. `}
  630. style={{ maxWidth: 'calc(100vw - 24px)' }}
  631. >
  632. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  633. <div className="p-2.5 flex gap-3">
  634. {leftSlot && renderColumn(leftSlot, 'L')}
  635. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  636. {rightSlot && renderColumn(rightSlot, 'R')}
  637. </div>
  638. </div>
  639. {/* Arrow pointer */}
  640. <div
  641. className={`
  642. absolute left-1/2 -translate-x-1/2 w-0 h-0
  643. border-l-[6px] border-l-transparent
  644. border-r-[6px] border-r-transparent
  645. ${position === 'top'
  646. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  647. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  648. `}
  649. />
  650. </div>
  651. )}
  652. </div>
  653. );
  654. }
  655. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  656. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  657. const { t } = useTranslation();
  658. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  659. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  660. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  661. // base — computing it from min(present IDs) shifts everything left when slot 16
  662. // is the one currently mounted (#943).
  663. const rackNozzles = slots.filter(s => s.id >= 2);
  664. const RACK_SIZE = 6;
  665. const RACK_BASE_ID = 16;
  666. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  667. { length: RACK_SIZE },
  668. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  669. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  670. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  671. },
  672. );
  673. return (
  674. // Sized to its contents rather than growing: the six chips are a fixed
  675. // width at any one card size, so extra width would be dead space taken
  676. // from the temperature cards beside it — which are flex-1 with a 0 basis
  677. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  678. // stays enabled so the card still gives way on a narrow printer card
  679. // instead of overflowing.
  680. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  681. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  682. <div className="flex gap-[3px] justify-center">
  683. {rackSlots.map((slot, i) => {
  684. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  685. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  686. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  687. return (
  688. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  689. <div className="flex flex-col items-center gap-0.5">
  690. <div
  691. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  692. isEmpty
  693. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  694. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  695. }`}
  696. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  697. >
  698. <span
  699. data-rack-diameter
  700. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  701. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  702. >
  703. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  704. </span>
  705. </div>
  706. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  707. acted on without counting chips. Sits below the chip rather
  708. than inside it: the chip is barely wider than its own
  709. diameter text and already carries that over a
  710. filament-coloured background. */}
  711. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  712. {i + 1}
  713. </span>
  714. </div>
  715. </NozzleSlotHoverCard>
  716. );
  717. })}
  718. </div>
  719. </div>
  720. );
  721. }
  722. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  723. function WaterDropEmpty({ className }: { className?: string }) {
  724. return (
  725. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  726. <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"/>
  727. </svg>
  728. );
  729. }
  730. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  731. function WaterDropHalf({ className }: { className?: string }) {
  732. return (
  733. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  734. <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"/>
  735. <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"/>
  736. </svg>
  737. );
  738. }
  739. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  740. function WaterDropFull({ className }: { className?: string }) {
  741. return (
  742. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  743. <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"/>
  744. <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"/>
  745. </svg>
  746. );
  747. }
  748. // Thermometer SVG - empty outline
  749. function ThermometerEmpty({ className }: { className?: string }) {
  750. return (
  751. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  752. <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"/>
  753. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  754. </svg>
  755. );
  756. }
  757. // Thermometer SVG - half filled (gold - same as humidity fair)
  758. function ThermometerHalf({ className }: { className?: string }) {
  759. return (
  760. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  761. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  762. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  763. <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"/>
  764. </svg>
  765. );
  766. }
  767. // Thermometer SVG - fully filled (red - same as humidity bad)
  768. function ThermometerFull({ className }: { className?: string }) {
  769. return (
  770. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  771. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  772. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  773. <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"/>
  774. </svg>
  775. );
  776. }
  777. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  778. // Added for visual parity with the thermometer icons on the dual-nozzle card
  779. // that previously had no icon at all (#1115, design by @m4rtini2).
  780. function NozzleIcon({ className }: { className?: string }) {
  781. return (
  782. <svg
  783. className={className}
  784. viewBox="0 0 24 24"
  785. fill="none"
  786. xmlns="http://www.w3.org/2000/svg"
  787. stroke="currentColor"
  788. strokeWidth="1.5"
  789. strokeLinecap="round"
  790. strokeLinejoin="round"
  791. >
  792. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  793. <rect x="6" y="11.5" width="12.1" height="3.7" />
  794. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  795. </svg>
  796. );
  797. }
  798. // Heater thermometer icon - filled when heating, outline when off
  799. interface HeaterThermometerProps {
  800. className?: string;
  801. color: string; // The color class (e.g., "text-orange-400")
  802. isHeating: boolean;
  803. }
  804. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  805. // Extract the actual color from Tailwind class for SVG fill
  806. const colorMap: Record<string, string> = {
  807. 'text-orange-400': '#fb923c',
  808. 'text-blue-400': '#60a5fa',
  809. 'text-green-400': '#4ade80',
  810. };
  811. const fillColor = colorMap[color] || '#888';
  812. // Glow style when heating
  813. const glowStyle = isHeating ? {
  814. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  815. } : {};
  816. if (isHeating) {
  817. // Filled thermometer with glow - heater is ON
  818. return (
  819. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  820. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  821. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  822. <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"/>
  823. </svg>
  824. );
  825. }
  826. // Empty thermometer - heater is OFF
  827. return (
  828. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  829. <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"/>
  830. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  831. </svg>
  832. );
  833. }
  834. // AMS Filament Backup tri-state indicator + toggle.
  835. // state=true → ON, click to disable
  836. // state=false → OFF, click opens modal
  837. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  838. interface AmsBackupBadgeProps {
  839. state: boolean | null;
  840. onClick: () => void;
  841. }
  842. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  843. const { t } = useTranslation();
  844. const known = state !== null;
  845. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  846. let title: string;
  847. if (state === true) {
  848. className += known
  849. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  850. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  851. title = t('printers.amsBackup.titleOn');
  852. } else if (state === false) {
  853. className += known
  854. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  855. : 'bg-bambu-dark text-bambu-gray cursor-default';
  856. title = t('printers.amsBackup.titleOff');
  857. } else {
  858. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  859. title = t('printers.amsBackup.titleUnknown');
  860. }
  861. return (
  862. <button
  863. type="button"
  864. disabled={!known}
  865. onClick={() => known && onClick()}
  866. className={className}
  867. title={title}
  868. aria-label={title}
  869. >
  870. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  871. </button>
  872. );
  873. }
  874. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  875. // like AmsBackupBadge so the two sit together in the section header, but
  876. // pinned to the right-hand end of the rule: this is a view preference for the
  877. // row, not a property of the printer.
  878. interface ExternalSpoolToggleProps {
  879. hidden: boolean;
  880. onClick: () => void;
  881. }
  882. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  883. const { t } = useTranslation();
  884. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  885. return (
  886. <button
  887. type="button"
  888. onClick={onClick}
  889. aria-pressed={hidden}
  890. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  891. hidden
  892. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  893. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  894. }`}
  895. title={title}
  896. aria-label={title}
  897. >
  898. {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)]" />}
  899. </button>
  900. );
  901. }
  902. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  903. // Reference: https://github.com/theicedmango/bambu-humidity
  904. interface HumidityIndicatorProps {
  905. humidity: number | string;
  906. goodThreshold?: number; // <= this is green
  907. fairThreshold?: number; // <= this is orange, > is red
  908. onClick?: () => void;
  909. compact?: boolean; // Smaller version for grid layout
  910. }
  911. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  912. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  913. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  914. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  915. // Status thresholds (configurable via settings)
  916. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  917. let textColor: string;
  918. let statusText: string;
  919. if (isNaN(humidityValue)) {
  920. textColor = '#C3C2C1';
  921. statusText = 'Unknown';
  922. } else if (humidityValue <= good) {
  923. textColor = '#22a352'; // Green - Good
  924. statusText = 'Good';
  925. } else if (humidityValue <= fair) {
  926. textColor = '#d4a017'; // Gold - Fair
  927. statusText = 'Fair';
  928. } else {
  929. textColor = '#c62828'; // Red - Bad
  930. statusText = 'Bad';
  931. }
  932. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  933. let DropComponent: React.FC<{ className?: string }>;
  934. if (isNaN(humidityValue)) {
  935. DropComponent = WaterDropEmpty;
  936. } else if (humidityValue <= good) {
  937. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  938. } else if (humidityValue <= fair) {
  939. DropComponent = WaterDropHalf; // Fair - half filled
  940. } else {
  941. DropComponent = WaterDropFull; // Bad - full (too humid)
  942. }
  943. return (
  944. <button
  945. type="button"
  946. onClick={onClick}
  947. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  948. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  949. >
  950. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  951. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  952. </button>
  953. );
  954. }
  955. // Temperature indicator with dynamic icon and coloring
  956. interface TemperatureIndicatorProps {
  957. temp: number;
  958. goodThreshold?: number; // <= this is blue
  959. fairThreshold?: number; // <= this is orange, > is red
  960. onClick?: () => void;
  961. compact?: boolean; // Smaller version for grid layout
  962. }
  963. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  964. // Ensure thresholds are numbers
  965. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  966. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  967. let textColor: string;
  968. let statusText: string;
  969. let ThermoComponent: React.FC<{ className?: string }>;
  970. if (temp <= good) {
  971. textColor = '#22a352'; // Green - good (same as humidity)
  972. statusText = 'Good';
  973. ThermoComponent = ThermometerEmpty;
  974. } else if (temp <= fair) {
  975. textColor = '#d4a017'; // Gold - fair (same as humidity)
  976. statusText = 'Fair';
  977. ThermoComponent = ThermometerHalf;
  978. } else {
  979. textColor = '#c62828'; // Red - bad (same as humidity)
  980. statusText = 'Bad';
  981. ThermoComponent = ThermometerFull;
  982. }
  983. return (
  984. <button
  985. type="button"
  986. onClick={onClick}
  987. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  988. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  989. >
  990. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  991. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  992. </button>
  993. );
  994. }
  995. // How long to wait for an AMS to report a live drying cycle after the printer
  996. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  997. // within a couple of seconds; 30s covers the slowest observed push cadence
  998. // without leaving the user waiting on a verdict.
  999. const DRY_START_CONFIRM_MS = 30_000;
  1000. export function CoverImage({
  1001. url,
  1002. printName,
  1003. className = 'w-20 h-20',
  1004. radiusClass = 'rounded-lg',
  1005. }: {
  1006. url: string | null;
  1007. printName?: string;
  1008. className?: string;
  1009. radiusClass?: string;
  1010. }) {
  1011. const { t } = useTranslation();
  1012. const [loaded, setLoaded] = useState(false);
  1013. const [error, setError] = useState(false);
  1014. const [showOverlay, setShowOverlay] = useState(false);
  1015. const imgRef = useRef<HTMLImageElement>(null);
  1016. // Cache-bust the image URL when the print name changes so the browser
  1017. // fetches the new cover instead of serving the stale cached image.
  1018. const cacheBustedUrl = useMemo(() => {
  1019. if (!url) return null;
  1020. const sep = url.includes('?') ? '&' : '?';
  1021. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1022. }, [url, printName]);
  1023. // Re-evaluate load state when the image URL changes, and ask the element
  1024. // whether it is already showing something rather than assuming it is not.
  1025. //
  1026. // `onLoad` used to be the only thing that could set `loaded`, and this
  1027. // effect reset it to false unconditionally. That is right when the URL
  1028. // really changes, but it also runs on mount — and the two are not the same
  1029. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1030. // constant for the duration of a print, so navigating away from the
  1031. // printers page and back re-mounts with a byte-identical src that the
  1032. // browser serves from its in-memory cache. The `load` event for a cache hit
  1033. // and React's passive-effect flush are both plain tasks with no ordering
  1034. // between them, so when `load` won, this effect ran afterwards and undid
  1035. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1036. // sat there until a full reload. Nothing recovered it, because the URL
  1037. // never changes again during the print and so this effect never re-runs.
  1038. //
  1039. // Being a race, it reproduced every time for #2826's reporter and not at
  1040. // all here, which is also why the network panel showed no request: there
  1041. // was no request to show.
  1042. //
  1043. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1044. // which of the two ran first. It is also correct for the case the reporter
  1045. // proposed (a `load` that fires before React's handler is live), so the
  1046. // fix stands whichever mechanism is really at work.
  1047. useEffect(() => {
  1048. setError(false);
  1049. const el = imgRef.current;
  1050. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1051. }, [cacheBustedUrl]);
  1052. return (
  1053. <>
  1054. <div
  1055. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1056. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1057. >
  1058. {cacheBustedUrl && !error ? (
  1059. <>
  1060. <img
  1061. ref={imgRef}
  1062. src={cacheBustedUrl}
  1063. alt={t('printers.printPreview')}
  1064. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1065. onLoad={() => setLoaded(true)}
  1066. onError={() => setError(true)}
  1067. />
  1068. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1069. </>
  1070. ) : (
  1071. <Box className="w-8 h-8 text-bambu-gray" />
  1072. )}
  1073. </div>
  1074. {/* Cover Image Overlay */}
  1075. {showOverlay && cacheBustedUrl && (
  1076. <div
  1077. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1078. onClick={() => setShowOverlay(false)}
  1079. >
  1080. <div className="relative max-w-2xl max-h-full">
  1081. <img
  1082. src={cacheBustedUrl}
  1083. alt={t('printers.printPreview')}
  1084. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1085. />
  1086. {printName && (
  1087. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1088. )}
  1089. </div>
  1090. </div>
  1091. )}
  1092. </>
  1093. );
  1094. }
  1095. interface PrinterMaintenanceInfo {
  1096. due_count: number;
  1097. warning_count: number;
  1098. total_print_hours: number;
  1099. }
  1100. // Status summary bar component - uses queryClient to read cached statuses
  1101. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1102. const { t } = useTranslation();
  1103. const queryClient = useQueryClient();
  1104. // Subscribe to query cache changes to re-render when status updates
  1105. // Throttled to prevent rapid re-renders from causing tab crashes
  1106. const [cacheTick, setCacheTick] = useState(0);
  1107. useEffect(() => {
  1108. let pending = false;
  1109. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1110. if (!pending) {
  1111. pending = true;
  1112. requestAnimationFrame(() => {
  1113. setCacheTick(t => t + 1);
  1114. pending = false;
  1115. });
  1116. }
  1117. });
  1118. return () => unsubscribe();
  1119. }, [queryClient]);
  1120. const { counts, nextFinish } = useMemo(() => {
  1121. let printing = 0;
  1122. let paused = 0;
  1123. let finished = 0;
  1124. let idle = 0;
  1125. let offline = 0;
  1126. let loading = 0;
  1127. let error = 0;
  1128. let nextPrinterName: string | null = null;
  1129. let nextRemainingMin: number | null = null;
  1130. let nextProgress: number = 0;
  1131. printers?.forEach((printer) => {
  1132. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1133. if (status === undefined) {
  1134. // Status not yet loaded - don't count as offline yet
  1135. loading++;
  1136. } else if (!status.connected) {
  1137. offline++;
  1138. } else {
  1139. // Count printers with active HMS errors as problems
  1140. const knownHmsCount =
  1141. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1142. if (knownHmsCount > 0) {
  1143. error++;
  1144. }
  1145. switch (status.state) {
  1146. case 'RUNNING':
  1147. printing++;
  1148. if (status.remaining_time != null && status.remaining_time > 0) {
  1149. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1150. nextRemainingMin = status.remaining_time;
  1151. nextPrinterName = printer.name;
  1152. nextProgress = status.progress || 0;
  1153. }
  1154. }
  1155. break;
  1156. case 'PAUSE':
  1157. paused++;
  1158. break;
  1159. case 'FINISH':
  1160. finished++;
  1161. break;
  1162. case 'FAILED':
  1163. // FAILED is the printer's terminal gcode_state after a print stops —
  1164. // including user cancellations, where there's no actual fault. Only
  1165. // count it as a "problem" when an HMS error is also active; otherwise
  1166. // it's just a print that ended unsuccessfully and the plate needs
  1167. // clearing (same as FINISH from the operator's perspective).
  1168. if (knownHmsCount > 0) {
  1169. // Already counted above
  1170. } else {
  1171. finished++;
  1172. }
  1173. break;
  1174. default:
  1175. idle++;
  1176. break;
  1177. }
  1178. }
  1179. });
  1180. return {
  1181. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1182. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1183. };
  1184. // eslint-disable-next-line react-hooks/exhaustive-deps
  1185. }, [printers, queryClient, cacheTick]);
  1186. if (!printers?.length) return null;
  1187. const badges: { count: number; dot: string; label: string }[] = [
  1188. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1189. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1190. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1191. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1192. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1193. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1194. ];
  1195. return (
  1196. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1197. {badges.map(({ count, dot, label }) => count > 0 && (
  1198. <div key={label} className="flex items-center gap-1.5">
  1199. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1200. <span className="text-bambu-gray">
  1201. <span className="text-white font-medium">{count}</span> {label}
  1202. </span>
  1203. </div>
  1204. ))}
  1205. {nextFinish && (
  1206. <>
  1207. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1208. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1209. <div className="flex items-center gap-2">
  1210. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1211. <span className="text-white font-medium">{nextFinish.name}</span>
  1212. </div>
  1213. <div className="flex items-center gap-2 w-full sm:w-auto">
  1214. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1215. <div
  1216. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1217. style={{ width: `${nextFinish.progress}%` }}
  1218. />
  1219. </div>
  1220. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1221. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1222. </div>
  1223. </div>
  1224. </>
  1225. )}
  1226. </div>
  1227. );
  1228. }
  1229. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1230. type ViewMode = 'expanded' | 'compact';
  1231. type ToolbarDropdownOption<T extends string> = {
  1232. value: T;
  1233. label: string;
  1234. };
  1235. function ToolbarDropdown<T extends string>({
  1236. value,
  1237. options,
  1238. onChange,
  1239. fullWidth = false,
  1240. }: {
  1241. value: T;
  1242. options: ToolbarDropdownOption<T>[];
  1243. onChange: (value: T) => void;
  1244. fullWidth?: boolean;
  1245. }) {
  1246. const [isOpen, setIsOpen] = useState(false);
  1247. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1248. return (
  1249. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1250. <button
  1251. type="button"
  1252. onClick={() => setIsOpen(open => !open)}
  1253. 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'}`}
  1254. >
  1255. <span className="truncate">{selectedOption?.label}</span>
  1256. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1257. </button>
  1258. {isOpen && (
  1259. <>
  1260. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1261. <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">
  1262. {options.map(option => (
  1263. <button
  1264. key={option.value}
  1265. type="button"
  1266. onClick={() => {
  1267. onChange(option.value);
  1268. setIsOpen(false);
  1269. }}
  1270. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1271. option.value === value ? 'text-bambu-green' : 'text-white'
  1272. }`}
  1273. >
  1274. {option.label}
  1275. </button>
  1276. ))}
  1277. </div>
  1278. </>
  1279. )}
  1280. </div>
  1281. );
  1282. }
  1283. function ToolbarMenu({
  1284. label,
  1285. icon,
  1286. children,
  1287. }: {
  1288. label: string;
  1289. icon: React.ReactNode;
  1290. children: React.ReactNode;
  1291. }) {
  1292. const [isOpen, setIsOpen] = useState(false);
  1293. return (
  1294. <div className="relative">
  1295. <button
  1296. type="button"
  1297. onClick={() => setIsOpen(open => !open)}
  1298. 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"
  1299. aria-label={label}
  1300. title={label}
  1301. >
  1302. {icon}
  1303. </button>
  1304. {isOpen && (
  1305. <>
  1306. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1307. <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">
  1308. {children}
  1309. </div>
  1310. </>
  1311. )}
  1312. </div>
  1313. );
  1314. }
  1315. function IndicatorControlPopover({
  1316. title,
  1317. options = [],
  1318. unit,
  1319. customMin,
  1320. customMax,
  1321. customStep = 1,
  1322. widthClass = 'w-[240px]',
  1323. popoverWidth = 240,
  1324. popoverHeight = 280,
  1325. isPending,
  1326. onClose,
  1327. onSubmit,
  1328. children,
  1329. }: {
  1330. title: string;
  1331. options?: Array<{ label: string; value: number }>;
  1332. unit?: string;
  1333. customMin?: number;
  1334. customMax?: number;
  1335. customStep?: number;
  1336. widthClass?: string;
  1337. popoverWidth?: number;
  1338. popoverHeight?: number;
  1339. isPending?: boolean;
  1340. onClose: () => void;
  1341. onSubmit?: (value: number) => void;
  1342. children?: React.ReactNode;
  1343. }) {
  1344. const anchorRef = useRef<HTMLSpanElement>(null);
  1345. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1346. const [customValue, setCustomValue] = useState('');
  1347. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1348. // can position via fixed coords. Portaling to document.body escapes
  1349. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1350. // own contexts and would otherwise cover the popover even at z-[60].
  1351. useLayoutEffect(() => {
  1352. const trigger = anchorRef.current?.parentElement;
  1353. if (!trigger) return;
  1354. const measure = () => {
  1355. const rect = trigger.getBoundingClientRect();
  1356. setCoords(computePopoverPosition({
  1357. triggerRect: rect,
  1358. popoverWidth,
  1359. estimatedHeight: popoverHeight,
  1360. horizontalAlign: 'center',
  1361. }));
  1362. };
  1363. measure();
  1364. window.addEventListener('resize', measure);
  1365. window.addEventListener('scroll', measure, true);
  1366. return () => {
  1367. window.removeEventListener('resize', measure);
  1368. window.removeEventListener('scroll', measure, true);
  1369. };
  1370. }, [popoverWidth, popoverHeight]);
  1371. const showCustomInput = unit !== undefined;
  1372. const submitCustom = () => {
  1373. const value = Number(customValue);
  1374. if (!Number.isFinite(value)) return;
  1375. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1376. onSubmit?.(Math.round(bounded));
  1377. };
  1378. return (
  1379. <>
  1380. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1381. {createPortal(
  1382. <>
  1383. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1384. <div
  1385. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1386. style={{
  1387. top: coords?.top ?? -9999,
  1388. left: coords?.left ?? -9999,
  1389. visibility: coords ? 'visible' : 'hidden',
  1390. }}
  1391. onClick={e => e.stopPropagation()}
  1392. >
  1393. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1394. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1395. {options.length > 0 && (
  1396. <div className="px-3 py-2.5">
  1397. <div className="grid grid-cols-2 gap-1.5">
  1398. {options.map(option => (
  1399. <button
  1400. key={`${option.label}-${option.value}`}
  1401. type="button"
  1402. disabled={isPending}
  1403. onClick={() => onSubmit?.(option.value)}
  1404. 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"
  1405. >
  1406. {option.label}
  1407. </button>
  1408. ))}
  1409. </div>
  1410. </div>
  1411. )}
  1412. {children}
  1413. {showCustomInput && (
  1414. <>
  1415. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1416. <form
  1417. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1418. onSubmit={(e) => {
  1419. e.preventDefault();
  1420. submitCustom();
  1421. }}
  1422. >
  1423. <input
  1424. type="number"
  1425. min={customMin}
  1426. max={customMax}
  1427. step={customStep}
  1428. value={customValue}
  1429. onChange={e => setCustomValue(e.target.value)}
  1430. placeholder="Custom"
  1431. 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"
  1432. />
  1433. <button
  1434. type="submit"
  1435. disabled={isPending || customValue.trim() === ''}
  1436. 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"
  1437. >
  1438. Set
  1439. </button>
  1440. </form>
  1441. </>
  1442. )}
  1443. </div>
  1444. </>,
  1445. document.body
  1446. )}
  1447. </>
  1448. );
  1449. }
  1450. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1451. function NozzleTemperatureControlBox({
  1452. label,
  1453. current,
  1454. target,
  1455. isActive,
  1456. isPending,
  1457. onSubmit,
  1458. options = NOZZLE_TEMPERATURE_OPTIONS,
  1459. }: {
  1460. label: string;
  1461. current?: number;
  1462. target?: number;
  1463. isActive: boolean;
  1464. isPending?: boolean;
  1465. onSubmit: (value: number) => void;
  1466. options?: Array<{ label: string; value: number }>;
  1467. }) {
  1468. const [customValue, setCustomValue] = useState('');
  1469. const submitCustom = () => {
  1470. const value = Number(customValue);
  1471. if (!Number.isFinite(value)) return;
  1472. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1473. };
  1474. return (
  1475. <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'}`}>
  1476. <div className="mb-1.5 flex items-center justify-between gap-2">
  1477. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1478. <span className="text-[10px] text-bambu-gray">
  1479. {Math.round(current ?? 0)}°C
  1480. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1481. </span>
  1482. </div>
  1483. <div className="grid grid-cols-2 gap-1">
  1484. {options.map(option => (
  1485. <button
  1486. key={`${label}-${option.value}`}
  1487. type="button"
  1488. disabled={isPending}
  1489. onClick={() => onSubmit(option.value)}
  1490. 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"
  1491. >
  1492. {option.label}
  1493. </button>
  1494. ))}
  1495. </div>
  1496. <form
  1497. className="mt-1.5 flex gap-1"
  1498. onSubmit={(e) => {
  1499. e.preventDefault();
  1500. submitCustom();
  1501. }}
  1502. >
  1503. <input
  1504. type="number"
  1505. min={0}
  1506. max={320}
  1507. step={1}
  1508. value={customValue}
  1509. onChange={e => setCustomValue(e.target.value)}
  1510. placeholder="Custom"
  1511. 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"
  1512. />
  1513. <button
  1514. type="submit"
  1515. disabled={isPending || customValue.trim() === ''}
  1516. 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"
  1517. >
  1518. Set
  1519. </button>
  1520. </form>
  1521. </div>
  1522. );
  1523. }
  1524. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1525. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1526. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1527. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1528. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1529. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1530. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1531. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1532. };
  1533. /** Classify a printer into one of the UI status buckets. */
  1534. function classifyPrinterStatus(
  1535. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1536. ): PrinterState {
  1537. if (!status?.connected) return 'offline';
  1538. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1539. if (hmsErrors.length > 0) return 'error';
  1540. switch (status.state) {
  1541. case 'RUNNING': return 'printing';
  1542. case 'PAUSE': return 'paused';
  1543. case 'FINISH': return 'finished';
  1544. // FAILED without an active HMS error is the printer's terminal state after
  1545. // any unsuccessful end — including user-cancellations. Treat the same as
  1546. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1547. // HMS code is actually attached (handled by the early-return above).
  1548. case 'FAILED': return 'finished';
  1549. default: return 'idle';
  1550. }
  1551. }
  1552. /**
  1553. * Get human-readable status display text for a printer.
  1554. * Uses stg_cur_name for detailed calibration/preparation stages,
  1555. * otherwise formats the gcode_state nicely.
  1556. */
  1557. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1558. // If we have a specific stage name (calibration, heating, etc.), use it
  1559. if (stg_cur_name) {
  1560. return stg_cur_name;
  1561. }
  1562. // Format the gcode_state nicely
  1563. switch (state) {
  1564. case 'RUNNING':
  1565. return 'Printing';
  1566. case 'PAUSE':
  1567. return 'Paused';
  1568. case 'FINISH':
  1569. return 'Finished';
  1570. case 'FAILED':
  1571. return 'Failed';
  1572. case 'IDLE':
  1573. return 'Idle';
  1574. default:
  1575. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1576. }
  1577. }
  1578. // Bambu models that ship with an enclosure chamber fan (firmware field
  1579. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1580. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1581. // widget is hidden in fanItems instead of rendered greyed-out.
  1582. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1583. 'X1C',
  1584. 'X1',
  1585. 'X1E',
  1586. 'X2D',
  1587. 'P1S',
  1588. 'P2S',
  1589. 'H2D',
  1590. 'H2D Pro',
  1591. 'H2C',
  1592. 'H2S',
  1593. ]);
  1594. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1595. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1596. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1597. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1598. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1599. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1600. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1601. 'P2S',
  1602. 'X2D',
  1603. ]);
  1604. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1605. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1606. // • User-defined friendly name (editable, protected by printers:update)
  1607. // • AMS serial number
  1608. // • AMS firmware version
  1609. export function AmsNameHoverCard({
  1610. ams,
  1611. printerId,
  1612. label,
  1613. amsLabels,
  1614. canEdit,
  1615. onSaved,
  1616. children,
  1617. }: {
  1618. ams: import('../api/client').AMSUnit;
  1619. printerId: number;
  1620. label: string; // auto-generated label, e.g. "AMS-A"
  1621. amsLabels?: Record<number, string>;
  1622. canEdit: boolean;
  1623. onSaved: () => void;
  1624. children: React.ReactNode;
  1625. }) {
  1626. const { t } = useTranslation();
  1627. const [isVisible, setIsVisible] = useState(false);
  1628. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1629. const [editValue, setEditValue] = useState('');
  1630. const [isSaving, setIsSaving] = useState(false);
  1631. const [saveError, setSaveError] = useState<string | null>(null);
  1632. const [isInputFocused, setIsInputFocused] = useState(false);
  1633. const triggerRef = useRef<HTMLDivElement>(null);
  1634. const cardRef = useRef<HTMLDivElement>(null);
  1635. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1636. useEffect(() => {
  1637. if (isVisible) {
  1638. setEditValue(amsLabels?.[ams.id] ?? '');
  1639. setSaveError(null);
  1640. requestAnimationFrame(() => {
  1641. if (triggerRef.current && cardRef.current) {
  1642. const rect = triggerRef.current.getBoundingClientRect();
  1643. const spaceAbove = rect.top - 56;
  1644. const spaceBelow = window.innerHeight - rect.bottom;
  1645. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1646. }
  1647. });
  1648. }
  1649. }, [isVisible, amsLabels, ams.id]);
  1650. const handleMouseEnter = () => {
  1651. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1652. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1653. };
  1654. const handleMouseLeave = () => {
  1655. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1656. if (!isInputFocused) {
  1657. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1658. }
  1659. };
  1660. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1661. const handleSave = async () => {
  1662. if (!canEdit) return;
  1663. setIsSaving(true);
  1664. setSaveError(null);
  1665. try {
  1666. const trimmed = editValue.trim();
  1667. if (trimmed) {
  1668. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1669. } else {
  1670. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1671. }
  1672. onSaved();
  1673. setIsVisible(false);
  1674. } catch (err) {
  1675. setSaveError(err instanceof Error ? err.message : String(err));
  1676. } finally {
  1677. setIsSaving(false);
  1678. }
  1679. };
  1680. const handleClear = async () => {
  1681. if (!canEdit) return;
  1682. setIsSaving(true);
  1683. setSaveError(null);
  1684. try {
  1685. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1686. onSaved();
  1687. setIsVisible(false);
  1688. } catch (err) {
  1689. setSaveError(err instanceof Error ? err.message : String(err));
  1690. } finally {
  1691. setIsSaving(false);
  1692. }
  1693. };
  1694. return (
  1695. <div
  1696. ref={triggerRef}
  1697. className="relative inline-block"
  1698. onMouseEnter={handleMouseEnter}
  1699. onMouseLeave={handleMouseLeave}
  1700. >
  1701. {children}
  1702. {isVisible && (
  1703. <div
  1704. ref={cardRef}
  1705. className={`
  1706. absolute left-0 z-50
  1707. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1708. animate-in fade-in-0 zoom-in-95 duration-150
  1709. `}
  1710. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1711. onMouseEnter={handleMouseEnter}
  1712. onMouseLeave={handleMouseLeave}
  1713. >
  1714. <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">
  1715. {/* AMS auto-label */}
  1716. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1717. {/* Serial number */}
  1718. <div className="flex items-center justify-between gap-2">
  1719. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1720. {t('printers.amsPopup.serialNumber')}
  1721. </span>
  1722. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1723. </div>
  1724. {/* Firmware version */}
  1725. <div className="flex items-center justify-between gap-2">
  1726. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1727. {t('printers.amsPopup.firmwareVersion')}
  1728. </span>
  1729. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1730. </div>
  1731. {/* Friendly name editor */}
  1732. <div className="space-y-1">
  1733. <div className="flex items-center gap-2">
  1734. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1735. {t('printers.amsPopup.friendlyName')}
  1736. </span>
  1737. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1738. </div>
  1739. <input
  1740. type="text"
  1741. value={editValue}
  1742. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1743. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1744. onFocus={() => setIsInputFocused(true)}
  1745. onBlur={() => {
  1746. setIsInputFocused(false);
  1747. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1748. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1749. }}
  1750. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1751. disabled={!canEdit}
  1752. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1753. 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"
  1754. maxLength={100}
  1755. />
  1756. {canEdit && (
  1757. <div className="space-y-1">
  1758. {saveError && (
  1759. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1760. )}
  1761. <div className="flex gap-1 justify-end">
  1762. <button
  1763. onClick={handleSave}
  1764. disabled={isSaving}
  1765. 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"
  1766. >
  1767. {t('printers.amsPopup.save')}
  1768. </button>
  1769. {amsLabels?.[ams.id] && (
  1770. <button
  1771. onClick={handleClear}
  1772. disabled={isSaving}
  1773. 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"
  1774. >
  1775. {t('printers.amsPopup.clear')}
  1776. </button>
  1777. )}
  1778. </div>
  1779. </div>
  1780. )}
  1781. </div>
  1782. </div>
  1783. </div>
  1784. )}
  1785. </div>
  1786. );
  1787. }
  1788. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1789. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1790. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1791. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1792. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1793. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1794. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1795. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1796. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1797. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1798. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1799. };
  1800. // How much the printer card's body type and icons grow at each card size
  1801. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1802. // 1.0 and an existing install looks identical until the user picks L or XL --
  1803. // the same control the request asked to have this follow.
  1804. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1805. // The scaled sizes, handed to the card subtree as custom properties. Every
  1806. // converted class names its old fixed value as the fallback, so anything that
  1807. // renders outside a card root -- the portalled temperature popover -- keeps
  1808. // exactly the size it has today.
  1809. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1810. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1811. // Rounded to a tenth so the values stay readable in devtools.
  1812. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1813. return {
  1814. '--pc-t8': px(8),
  1815. '--pc-t9': px(9),
  1816. '--pc-t10': px(10),
  1817. '--pc-t11': px(11),
  1818. '--pc-i2': px(8),
  1819. '--pc-i25': px(10),
  1820. '--pc-i3': px(12),
  1821. '--pc-i35': px(14),
  1822. '--pc-i4': px(16),
  1823. '--pc-i5': px(20),
  1824. '--pc-i7': px(28),
  1825. } as React.CSSProperties;
  1826. }
  1827. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1828. const { t } = useTranslation();
  1829. const queryClient = useQueryClient();
  1830. const { showToast } = useToast();
  1831. // One fleet-wide query shared by every card, not one per card: the list is
  1832. // nearly always empty and a 20-printer fleet would otherwise make 20
  1833. // requests every 30s. React Query dedupes on the key.
  1834. const { data: scheduled = [] } = useQuery({
  1835. queryKey: SCHEDULED_DRYINGS_KEY,
  1836. queryFn: () => api.listScheduledDryings(),
  1837. refetchInterval: 30_000,
  1838. });
  1839. // The live AMS status reports a starting cycle well before the next poll;
  1840. // refetch so a just-dispatched schedule doesn't linger as pending.
  1841. useEffect(() => {
  1842. if (dryingActive) {
  1843. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1844. }
  1845. }, [dryingActive, queryClient]);
  1846. const cancelMutation = useMutation({
  1847. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1848. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1849. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1850. });
  1851. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1852. // old firmware on a printer that was offline at schedule time), and without
  1853. // this the run just vanishes with only the backend log saying why.
  1854. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1855. if (rows.length === 0) return null;
  1856. return (
  1857. <div className="mt-2 space-y-1">
  1858. {rows.map(s => {
  1859. const failed = s.status === 'failed';
  1860. const reasonKey = waitingReasonKey(s.waiting_reason);
  1861. const failedKey = failedReasonKey(s.error_code);
  1862. return (
  1863. <div
  1864. key={s.id}
  1865. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1866. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1867. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1868. }`}
  1869. >
  1870. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1871. {failed ? (
  1872. t('printers.drying.scheduleFailedReason', {
  1873. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1874. })
  1875. ) : (
  1876. <>
  1877. {s.start_after
  1878. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1879. : t('printers.drying.scheduledAsap')}
  1880. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1881. </>
  1882. )}
  1883. </span>
  1884. <button
  1885. onClick={() => cancelMutation.mutate(s.id)}
  1886. disabled={cancelMutation.isPending}
  1887. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1888. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1889. >
  1890. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1891. </button>
  1892. </div>
  1893. );
  1894. })}
  1895. </div>
  1896. );
  1897. }
  1898. function PrinterCard({
  1899. printer,
  1900. hideIfDisconnected,
  1901. maintenanceInfo,
  1902. viewMode = 'expanded',
  1903. cardSize = 2,
  1904. amsThresholds,
  1905. spoolmanEnabled = false,
  1906. linkedSpools,
  1907. spoolmanUrl,
  1908. spoolmanSyncMode,
  1909. onGetAssignment,
  1910. onUnassignSpool,
  1911. spoolmanSpools,
  1912. spoolmanSlotAssignments,
  1913. spoolmanLoading = false,
  1914. onUnassignSpoolmanSpool,
  1915. timeFormat = 'system',
  1916. cameraViewMode = 'window',
  1917. onOpenEmbeddedCamera,
  1918. onSelectCameraViewMode,
  1919. checkPrinterFirmware = true,
  1920. dryingPresets = DRYING_PRESETS,
  1921. requirePlateClear = false,
  1922. selectionMode = false,
  1923. isSelected = false,
  1924. onToggleSelect,
  1925. onOpenCompactCard,
  1926. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1927. bedTempPresets = BED_TEMP_DEFAULTS,
  1928. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1929. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1930. aiDetectionEnabled = false,
  1931. aiDetection,
  1932. aiLastError = null,
  1933. }: {
  1934. printer: Printer;
  1935. hideIfDisconnected?: boolean;
  1936. maintenanceInfo?: PrinterMaintenanceInfo;
  1937. viewMode?: ViewMode;
  1938. cardSize?: number;
  1939. amsThresholds?: {
  1940. humidityGood: number;
  1941. humidityFair: number;
  1942. tempGood: number;
  1943. tempFair: number;
  1944. };
  1945. spoolmanEnabled?: boolean;
  1946. hasUnlinkedSpools?: boolean;
  1947. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1948. spoolmanUrl?: string | null;
  1949. spoolmanSyncMode?: string | null;
  1950. spoolAssignments?: SpoolAssignment[];
  1951. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1952. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1953. spoolmanSpools?: InventorySpool[];
  1954. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1955. spoolmanLoading?: boolean;
  1956. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1957. timeFormat?: 'system' | '12h' | '24h';
  1958. cameraViewMode?: CameraViewMode;
  1959. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1960. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  1961. checkPrinterFirmware?: boolean;
  1962. dryingPresets?: Record<string, DryingPreset>;
  1963. requirePlateClear?: boolean;
  1964. selectionMode?: boolean;
  1965. isSelected?: boolean;
  1966. onToggleSelect?: (id: number) => void;
  1967. onOpenCompactCard?: (id: number) => void;
  1968. nozzleTempPresets?: readonly [number, number, number];
  1969. bedTempPresets?: readonly [number, number, number];
  1970. chamberTempPresets?: readonly [number, number, number];
  1971. fanSpeedPresets?: readonly [number, number, number];
  1972. aiDetectionEnabled?: boolean;
  1973. aiDetection?: AiDetection;
  1974. aiLastError?: string | null;
  1975. }) {
  1976. const { t } = useTranslation();
  1977. const queryClient = useQueryClient();
  1978. const navigate = useNavigate();
  1979. const { showToast } = useToast();
  1980. const { hasPermission, canModify } = useAuth();
  1981. const [showMenu, setShowMenu] = useState(false);
  1982. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1983. const [deleteArchives, setDeleteArchives] = useState(true);
  1984. const [showEditModal, setShowEditModal] = useState(false);
  1985. const [showFileManager, setShowFileManager] = useState(false);
  1986. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1987. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1988. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1989. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1990. const [showHMSModal, setShowHMSModal] = useState(false);
  1991. // #1546: AI failure detection modal — opens from the AI badge.
  1992. const [showAiModal, setShowAiModal] = useState(false);
  1993. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1994. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1995. // External spool visibility (#1782) — browser-local, per printer. Read once
  1996. // per card; the toggle that writes it is the only thing that changes it.
  1997. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  1998. isExternalSpoolHidden(printer.id),
  1999. );
  2000. const toggleExternalSpool = useCallback(() => {
  2001. setExternalSpoolHidden((prev) => {
  2002. const next = !prev;
  2003. persistExternalSpoolHidden(printer.id, next);
  2004. return next;
  2005. });
  2006. }, [printer.id]);
  2007. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2008. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2009. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2010. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2011. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2012. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2013. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2014. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2015. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2016. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2017. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2018. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2019. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2020. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2021. // AMS drying popover state: which AMS unit has the popover open
  2022. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2023. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2024. const [dryingFilament, setDryingFilament] = useState('PLA');
  2025. const [dryingTemp, setDryingTemp] = useState(50);
  2026. const [dryingDuration, setDryingDuration] = useState(4);
  2027. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2028. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2029. // go through scheduleDryingMutation.
  2030. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2031. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2032. const [dryingStartAt, setDryingStartAt] = useState('');
  2033. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2034. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2035. // Reset every field the popover owns, including the start mode. Leaving the
  2036. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2037. // the next open, by then in the past, and the POST rejected it.
  2038. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2039. const firstTray = ams.tray.find(t => t.tray_type);
  2040. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2041. // Only reachable if a custom preset set dropped PLA itself.
  2042. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2043. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2044. setDryingFilament(filType);
  2045. setDryingTemp(preset[moduleType] || preset.n3f);
  2046. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2047. setDryingRotateTray(false);
  2048. setDryingStartMode('now');
  2049. setDryingDelayMinutes(120);
  2050. setDryingStartAt('');
  2051. setDryingPopoverModuleType(ams.module_type);
  2052. setDryingPopoverAmsId(ams.id);
  2053. setDryingPopoverAnchor(trigger);
  2054. }, [dryingPresets]);
  2055. // Re-measure on resize/scroll so the popover and its arrow track the
  2056. // flame button, like IndicatorControlPopover.
  2057. useLayoutEffect(() => {
  2058. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2059. const measure = () => {
  2060. setDryingPopoverPos(computePopoverPosition({
  2061. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2062. popoverWidth: DRYING_POPOVER_WIDTH,
  2063. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2064. horizontalAlign: 'center',
  2065. }));
  2066. };
  2067. measure();
  2068. window.addEventListener('resize', measure);
  2069. window.addEventListener('scroll', measure, true);
  2070. return () => {
  2071. window.removeEventListener('resize', measure);
  2072. window.removeEventListener('scroll', measure, true);
  2073. };
  2074. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2075. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2076. // Whether the click hitting the backdrop is the one that dismissed the
  2077. // native datetime picker (see the backdrop's onMouseDown).
  2078. const dryingBackdropSkipCloseRef = useRef(false);
  2079. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2080. // an object rather than a bare id so restarting drying on the SAME unit produces
  2081. // a new identity and rearms the timeout below.
  2082. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2083. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2084. const [isDropUploading, setIsDropUploading] = useState(false);
  2085. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2086. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2087. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2088. // inside the card would have to open upward into the card body; anchored to
  2089. // the viewport it escapes the card and the grid's scroll container both.
  2090. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2091. const dragCounterRef = useRef(0);
  2092. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2093. amsId: number;
  2094. amsLabel: string;
  2095. mode: 'humidity' | 'temperature';
  2096. } | null>(null);
  2097. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2098. initialKind: HeaterSensorKind;
  2099. availableKinds: HeaterSensorKind[];
  2100. } | null>(null);
  2101. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2102. tagUid: string;
  2103. trayUuid: string;
  2104. printerId: number;
  2105. amsId: number;
  2106. trayId: number;
  2107. } | null>(null);
  2108. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2109. printerId: number;
  2110. amsId: number;
  2111. trayId: number;
  2112. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2113. } | null>(null);
  2114. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2115. amsId: number;
  2116. trayId: number;
  2117. trayCount: number;
  2118. trayType?: string;
  2119. trayColor?: string;
  2120. traySubBrands?: string;
  2121. trayInfoIdx?: string;
  2122. extruderId?: number;
  2123. caliIdx?: number | null;
  2124. savedPresetId?: string;
  2125. } | null>(null);
  2126. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2127. const [plateCheckResult, setPlateCheckResult] = useState<{
  2128. is_empty: boolean;
  2129. confidence: number;
  2130. difference_percent: number;
  2131. message: string;
  2132. debug_image_url?: string;
  2133. needs_calibration: boolean;
  2134. light_warning?: boolean;
  2135. reference_count?: number;
  2136. max_references?: number;
  2137. roi?: { x: number; y: number; w: number; h: number };
  2138. } | null>(null);
  2139. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2140. const [isCalibrating, setIsCalibrating] = useState(false);
  2141. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2142. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2143. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2144. const { data: status } = useQuery({
  2145. queryKey: ['printerStatus', printer.id],
  2146. queryFn: () => api.getPrinterStatus(printer.id),
  2147. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2148. });
  2149. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2150. const { data: firmwareInfo } = useQuery({
  2151. queryKey: ['firmwareUpdate', printer.id],
  2152. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2153. staleTime: 5 * 60 * 1000,
  2154. refetchInterval: 5 * 60 * 1000,
  2155. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2156. });
  2157. // Collect unique tray_info_idx values for cloud filament info lookup
  2158. const trayInfoIds = useMemo(() => {
  2159. const ids = new Set<string>();
  2160. if (status?.ams) {
  2161. for (const ams of status.ams) {
  2162. for (const tray of ams.tray || []) {
  2163. if (tray.tray_info_idx) {
  2164. ids.add(tray.tray_info_idx);
  2165. }
  2166. }
  2167. }
  2168. }
  2169. for (const vt of status?.vt_tray ?? []) {
  2170. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2171. }
  2172. if (status?.nozzle_rack) {
  2173. for (const slot of status.nozzle_rack) {
  2174. if (slot.filament_id) {
  2175. ids.add(slot.filament_id);
  2176. }
  2177. }
  2178. }
  2179. return Array.from(ids);
  2180. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2181. // Collect loaded filament types for queue widget filtering
  2182. const loadedFilamentTypes = useMemo(() => {
  2183. const types = new Set<string>();
  2184. if (status?.ams) {
  2185. for (const ams of status.ams) {
  2186. for (const tray of ams.tray || []) {
  2187. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2188. }
  2189. }
  2190. }
  2191. for (const vt of status?.vt_tray ?? []) {
  2192. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2193. }
  2194. return types;
  2195. }, [status?.ams, status?.vt_tray]);
  2196. // Collect loaded filament type+color pairs for queue widget override matching
  2197. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2198. const loadedFilaments = useMemo(() => {
  2199. const filaments = new Set<string>();
  2200. if (status?.ams) {
  2201. for (const ams of status.ams) {
  2202. for (const tray of ams.tray || []) {
  2203. if (tray.tray_type && tray.tray_color) {
  2204. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2205. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2206. }
  2207. }
  2208. }
  2209. }
  2210. for (const vt of status?.vt_tray ?? []) {
  2211. if (vt.tray_type && vt.tray_color) {
  2212. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2213. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2214. }
  2215. }
  2216. return filaments;
  2217. }, [status?.ams, status?.vt_tray]);
  2218. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2219. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2220. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2221. const loadedVariants = useMemo(() => {
  2222. const variants = new Set<string>();
  2223. if (status?.ams) {
  2224. for (const ams of status.ams) {
  2225. for (const tray of ams.tray || []) {
  2226. if (tray.tray_type && tray.tray_color) {
  2227. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2228. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2229. }
  2230. }
  2231. }
  2232. }
  2233. for (const vt of status?.vt_tray ?? []) {
  2234. if (vt.tray_type && vt.tray_color) {
  2235. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2236. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2237. }
  2238. }
  2239. return variants;
  2240. }, [status?.ams, status?.vt_tray]);
  2241. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2242. const { data: filamentInfo } = useQuery({
  2243. queryKey: ['filamentInfo', trayInfoIds],
  2244. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2245. enabled: trayInfoIds.length > 0,
  2246. staleTime: 5 * 60 * 1000, // 5 minutes
  2247. });
  2248. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2249. const { data: slotPresets } = useQuery({
  2250. queryKey: ['slotPresets', printer.id],
  2251. queryFn: () => api.getSlotPresets(printer.id),
  2252. staleTime: 2 * 60 * 1000, // 2 minutes
  2253. });
  2254. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2255. // Only queried when there's a running print backed by an archive; shared
  2256. // React Query cache with the Queue / Archives pages keeps it cheap.
  2257. const activeArchiveId =
  2258. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2259. const { data: activeArchivePlates } = useQuery({
  2260. queryKey: ['archive-plates', activeArchiveId],
  2261. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2262. enabled: activeArchiveId != null,
  2263. staleTime: 5 * 60 * 1000,
  2264. });
  2265. const activePlateLabel = (() => {
  2266. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2267. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2268. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2269. })();
  2270. // Fetch user-defined AMS friendly names from the database
  2271. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2272. queryKey: ['amsLabels', printer.id],
  2273. queryFn: () => api.getAmsLabels(printer.id),
  2274. staleTime: 5 * 60 * 1000, // 5 minutes
  2275. });
  2276. // Cache WiFi signal to prevent it disappearing on updates
  2277. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2278. useEffect(() => {
  2279. if (status?.wifi_signal != null) {
  2280. setCachedWifiSignal(status.wifi_signal);
  2281. }
  2282. }, [status?.wifi_signal]);
  2283. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2284. // Cache connected state to prevent flicker when status briefly becomes undefined
  2285. const cachedConnected = useRef<boolean | undefined>(undefined);
  2286. useEffect(() => {
  2287. if (status?.connected !== undefined) {
  2288. cachedConnected.current = status.connected;
  2289. }
  2290. }, [status?.connected]);
  2291. const isConnected = status?.connected ?? cachedConnected.current;
  2292. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2293. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2294. useEffect(() => {
  2295. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2296. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2297. }
  2298. }, [status?.ams_extruder_map]);
  2299. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2300. ? status.ams_extruder_map
  2301. : cachedAmsExtruderMap.current;
  2302. // Same caching for the Filament Track Switch inlet bindings, for the same
  2303. // reason: a partial MQTT frame briefly empties the map and the badges would
  2304. // otherwise blink out.
  2305. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2306. useEffect(() => {
  2307. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2308. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2309. }
  2310. }, [status?.ams_switch_inlet]);
  2311. const ftsInstalled = status?.fila_switch?.installed === true;
  2312. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2313. ? status.ams_switch_inlet
  2314. : cachedAmsSwitchInlet.current;
  2315. // Cache AMS data to prevent it disappearing on idle/offline printers
  2316. const cachedAmsData = useRef<AMSUnit[]>([]);
  2317. useEffect(() => {
  2318. if (status?.ams && status.ams.length > 0) {
  2319. cachedAmsData.current = status.ams;
  2320. }
  2321. }, [status?.ams]);
  2322. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2323. // #2532: the K-profile line only exists on slots the printer has actually
  2324. // calibrated. The AMS units and the external-spool group are flex siblings in
  2325. // one row, so on a card that shows a value anywhere, the slots without one
  2326. // reserve the same height -- otherwise their fill bars sit a line above their
  2327. // neighbours'. A card with no calibrated slot at all is unaffected.
  2328. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2329. || (status?.vt_tray ?? []).some(tray => tray.k);
  2330. // Confirm a drying cycle actually started (#2533). Firmware answers
  2331. // ams_filament_drying with result=success even when it then silently declines,
  2332. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2333. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2334. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2335. // means the printer took the command and dropped it.
  2336. useEffect(() => {
  2337. if (!dryStartWatch) return;
  2338. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2339. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2340. }, [dryStartWatch, amsData]);
  2341. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2342. // otherwise rearm the timeout on every frame, so it would never elapse.
  2343. useEffect(() => {
  2344. if (!dryStartWatch) return;
  2345. const timer = setTimeout(() => {
  2346. setDryStartWatch(null);
  2347. showToast(t('printers.drying.toastNotStarted'), 'error');
  2348. }, DRY_START_CONFIRM_MS);
  2349. return () => clearTimeout(timer);
  2350. }, [dryStartWatch, showToast, t]);
  2351. // Cache tray_now to prevent flickering when undefined values come in
  2352. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2353. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2354. const cachedTrayNow = useRef<number | undefined>(undefined);
  2355. const currentTrayNow = status?.tray_now;
  2356. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2357. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2358. cachedTrayNow.current = currentTrayNow;
  2359. } else if (currentTrayNow === 255) {
  2360. cachedTrayNow.current = undefined;
  2361. }
  2362. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2363. ? currentTrayNow
  2364. : cachedTrayNow.current;
  2365. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2366. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2367. // expectedTray = the slot the firmware now expects filament in
  2368. // previousTray = the slot that ran out
  2369. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2370. // so these are often different — the graphic highlights the expected one.
  2371. const expectedTray = status?.expected_tray ?? null;
  2372. const previousTray = status?.previous_tray ?? null;
  2373. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2374. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2375. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2376. if (globalId === null) return null;
  2377. if (globalId === 254) return t('printers.expectedSlot.external');
  2378. if (globalId >= 128 && globalId <= 135) {
  2379. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2380. }
  2381. const amsId = Math.floor(globalId / 4);
  2382. const slot = globalId % 4;
  2383. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2384. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2385. };
  2386. const runoutGuidance = status?.state === 'PAUSE'
  2387. ? {
  2388. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2389. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2390. }
  2391. : null;
  2392. // Fetch smart plug for this printer
  2393. const { data: smartPlug } = useQuery({
  2394. queryKey: ['smartPlugByPrinter', printer.id],
  2395. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2396. });
  2397. // Fetch script plugs for this printer (for multi-device control)
  2398. const { data: scriptPlugs } = useQuery({
  2399. queryKey: ['scriptPlugsByPrinter', printer.id],
  2400. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2401. });
  2402. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2403. const { data: plugStatus } = useQuery({
  2404. queryKey: ['smartPlugStatus', smartPlug?.id],
  2405. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2406. enabled: !!smartPlug,
  2407. refetchInterval: 10000, // 10 seconds for real-time power display
  2408. });
  2409. // Fetch queue count for this printer
  2410. const { data: queueItems } = useQuery({
  2411. queryKey: ['queue', printer.id, 'pending'],
  2412. queryFn: () => api.getQueue(printer.id, 'pending'),
  2413. });
  2414. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2415. // so the badge only shows on printers that can actually run the queued jobs.
  2416. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2417. const queueCount = useMemo(() => {
  2418. if (!queueItems?.length) return 0;
  2419. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2420. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2421. // Fetch currently printing queue item to show who started it (Issue #206)
  2422. const { data: printingQueueItems } = useQuery({
  2423. queryKey: ['queue', printer.id, 'printing'],
  2424. queryFn: () => api.getQueue(printer.id, 'printing'),
  2425. enabled: status?.state === 'RUNNING',
  2426. });
  2427. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2428. const { data: reprintUser } = useQuery({
  2429. queryKey: ['currentPrintUser', printer.id],
  2430. queryFn: () => api.getCurrentPrintUser(printer.id),
  2431. enabled: status?.state === 'RUNNING',
  2432. });
  2433. // Combine both sources: queue item user takes precedence, then reprint user
  2434. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2435. // Fetch last completed print for this printer
  2436. const { data: lastPrints } = useQuery({
  2437. queryKey: ['archives', printer.id, 'last'],
  2438. queryFn: () => api.getArchives(printer.id, 1, 0),
  2439. enabled: status?.connected && status?.state !== 'RUNNING',
  2440. });
  2441. const lastPrint = lastPrints?.[0];
  2442. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2443. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2444. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2445. // gate is up and the just-finished print asked for a verdict, offer
  2446. // Good/Reject right where the operator releases the plate. Releasing the
  2447. // plate without answering stays possible — the two are orthogonal (though
  2448. // the confirm_default_good_on_plate_clear setting can couple them).
  2449. // Only offered to whoever may record it: the PATCH checks archives:update
  2450. // against the archive's owner, so for anyone else the pair could only fail.
  2451. const pendingConfirmArchive =
  2452. lastPrint &&
  2453. lastPrint.status === 'completed' &&
  2454. lastPrint.confirm_requested &&
  2455. lastPrint.user_verdict == null &&
  2456. canModify('archives', 'update', lastPrint.created_by_id)
  2457. ? lastPrint
  2458. : null;
  2459. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2460. // Auto Power Off the printer is powered down exactly when the operator clears the
  2461. // plate. Hiding the control there left no way to release the gate (#2864).
  2462. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2463. const activePrintName = status?.current_print && isPrintingOrPaused
  2464. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2465. : null;
  2466. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2467. useEffect(() => {
  2468. if (activePrintName) {
  2469. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2470. } else if (!needsPlateClear) {
  2471. setRetainedPrintJob(null);
  2472. }
  2473. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2474. const plateStatus = (() => {
  2475. // Connected-only because the pill's only render site sits inside the live-status
  2476. // panel. For a powered-down printer the plate-clear button itself carries the
  2477. // state — see the standalone slot below the status block (#2864).
  2478. if (!requirePlateClear || !status?.connected) return null;
  2479. if (isPrintingOrPaused) {
  2480. return {
  2481. label: t('printers.plateStatus.inUse'),
  2482. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2483. };
  2484. }
  2485. if (status.awaiting_plate_clear) {
  2486. return {
  2487. label: t('printers.plateStatus.notCleared'),
  2488. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2489. };
  2490. }
  2491. return {
  2492. label: t('printers.plateStatus.cleared'),
  2493. className: 'bg-status-ok/20 text-status-ok',
  2494. };
  2495. })();
  2496. const plateStatusPill = plateStatus ? (
  2497. <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}`}>
  2498. {plateStatus.label}
  2499. </span>
  2500. ) : null;
  2501. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2502. const shouldHide = hideIfDisconnected && isConnected === false;
  2503. const deleteMutation = useMutation({
  2504. mutationFn: (options: { deleteArchives: boolean }) =>
  2505. api.deletePrinter(printer.id, options.deleteArchives),
  2506. onSuccess: () => {
  2507. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2508. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2509. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2510. },
  2511. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2512. });
  2513. const connectMutation = useMutation({
  2514. mutationFn: () => api.connectPrinter(printer.id),
  2515. onSuccess: () => {
  2516. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2517. },
  2518. });
  2519. const forceRefreshMutation = useMutation({
  2520. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2521. onSuccess: () => {
  2522. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2523. showToast(t('printers.forceRefreshSuccess'), 'success');
  2524. },
  2525. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2526. });
  2527. const unlinkSpoolMutation = useMutation({
  2528. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2529. onSuccess: (result) => {
  2530. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2531. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2532. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2533. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2534. },
  2535. onError: (error: Error) => {
  2536. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2537. },
  2538. });
  2539. // AMS drying mutations
  2540. const startDryingMutation = useMutation({
  2541. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2542. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2543. onSuccess: (_data, { amsId }) => {
  2544. setDryingPopoverAmsId(null);
  2545. setDryStartWatch({ amsId });
  2546. // "Command sent", not "drying started" — at this point the printer has only
  2547. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2548. // the cycle is genuinely live; the watcher below covers the case where it
  2549. // never appears.
  2550. showToast(t('printers.drying.toastCommandSent'), 'success');
  2551. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2552. },
  2553. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2554. });
  2555. // Scheduled (delayed / at-time) drying runs (#2638)
  2556. const scheduleDryingMutation = useMutation({
  2557. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2558. api.createScheduledDrying({
  2559. printer_id: printer.id,
  2560. ams_id: params.amsId,
  2561. temp: params.temp,
  2562. duration_hours: params.duration,
  2563. filament: params.filament,
  2564. rotate_tray: params.rotateTray,
  2565. start_after: params.startAfter,
  2566. }),
  2567. onSuccess: () => {
  2568. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2569. setDryingPopoverAmsId(null);
  2570. },
  2571. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2572. });
  2573. const stopDryingMutation = useMutation({
  2574. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2575. onSuccess: () => {
  2576. setDryStartWatch(null);
  2577. showToast(t('printers.drying.toastStopped'), 'success');
  2578. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2579. },
  2580. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2581. });
  2582. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2583. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2584. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2585. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2586. // showing the old backup state until the user reopens it.
  2587. const setAmsBackupMutation = useMutation({
  2588. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2589. onSuccess: (_data, enabled) => {
  2590. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2591. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2592. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2593. },
  2594. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2595. });
  2596. // Smart plug control mutations
  2597. const powerControlMutation = useMutation({
  2598. mutationFn: (action: 'on' | 'off') =>
  2599. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2600. onSuccess: () => {
  2601. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2602. },
  2603. });
  2604. const toggleAutoOffMutation = useMutation({
  2605. mutationFn: (enabled: boolean) =>
  2606. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2607. onSuccess: () => {
  2608. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2609. // Also invalidate the smart-plugs list to keep Settings page in sync
  2610. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2611. },
  2612. });
  2613. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2614. const runScriptMutation = useMutation({
  2615. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2616. onSuccess: () => {
  2617. showToast(t('printers.toast.scriptTriggered'));
  2618. },
  2619. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2620. });
  2621. // Print control mutations
  2622. const stopPrintMutation = useMutation({
  2623. mutationFn: () => api.stopPrint(printer.id),
  2624. onSuccess: () => {
  2625. showToast(t('printers.toast.printStopped'));
  2626. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2627. },
  2628. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2629. });
  2630. const pausePrintMutation = useMutation({
  2631. mutationFn: () => api.pausePrint(printer.id),
  2632. onSuccess: () => {
  2633. showToast(t('printers.toast.printPaused'));
  2634. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2635. },
  2636. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2637. });
  2638. const resumePrintMutation = useMutation({
  2639. mutationFn: () => api.resumePrint(printer.id),
  2640. onSuccess: () => {
  2641. showToast(t('printers.toast.printResumed'));
  2642. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2643. },
  2644. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2645. });
  2646. const clearPlateMutation = useMutation({
  2647. mutationFn: () => api.clearPlate(printer.id),
  2648. onSuccess: () => {
  2649. showToast(t('queue.clearPlateSuccess'));
  2650. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2651. old ? { ...old, awaiting_plate_clear: false } : old
  2652. );
  2653. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2654. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2655. },
  2656. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2657. });
  2658. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2659. // reject goes through the dialog for the optional reason + reprint.
  2660. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2661. // Only "good" is answered on the card. A reject wants a reason and possibly
  2662. // a reprint, so that button opens the dialog instead — and the parameter
  2663. // says as much, rather than accepting a verdict this path cannot send and
  2664. // then reporting it as good.
  2665. const cardVerdictMutation = useMutation({
  2666. mutationFn: (verdict: 'good') =>
  2667. api.updateArchive(pendingConfirmArchive!.id, {
  2668. user_verdict: verdict,
  2669. user_verdict_source: 'printer_card',
  2670. }),
  2671. onSuccess: () => {
  2672. showToast(t('confirmOutcome.savedGood'), 'success');
  2673. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2674. },
  2675. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2676. });
  2677. // Rendered from two places: inside the live-status block for a connected printer,
  2678. // and standalone below it for a powered-down one, whose status block isn't rendered
  2679. // at all (#2864). Shared so the two can't drift apart.
  2680. const expandedClearPlateButton = (
  2681. <>
  2682. {pendingConfirmArchive && (
  2683. <div className="mt-2 flex items-center gap-1.5">
  2684. <span
  2685. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2686. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2687. >
  2688. {t('confirmOutcome.cardPrompt')}
  2689. </span>
  2690. <button
  2691. type="button"
  2692. onClick={() => setShowConfirmOutcome(true)}
  2693. disabled={cardVerdictMutation.isPending}
  2694. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2695. title={t('confirmOutcome.reject')}
  2696. >
  2697. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2698. </button>
  2699. <button
  2700. type="button"
  2701. onClick={() => cardVerdictMutation.mutate('good')}
  2702. disabled={cardVerdictMutation.isPending}
  2703. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2704. title={t('confirmOutcome.good')}
  2705. >
  2706. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2707. </button>
  2708. </div>
  2709. )}
  2710. <button
  2711. type="button"
  2712. onClick={() => clearPlateMutation.mutate()}
  2713. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2714. 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"
  2715. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2716. >
  2717. {clearPlateMutation.isPending ? (
  2718. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2719. ) : (
  2720. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2721. )}
  2722. {t('printers.plateStatus.markCleared')}
  2723. </button>
  2724. {showConfirmOutcome && pendingConfirmArchive && (
  2725. <ConfirmOutcomeDialog
  2726. archiveId={pendingConfirmArchive.id}
  2727. onClose={() => setShowConfirmOutcome(false)}
  2728. />
  2729. )}
  2730. </>
  2731. );
  2732. const nozzleTemperatureMutation = useMutation({
  2733. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2734. api.setNozzleTemperature(printer.id, target, nozzle),
  2735. onSuccess: (result) => {
  2736. setStatusControlMenu(null);
  2737. showToast(result.message);
  2738. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2739. },
  2740. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2741. });
  2742. const bedTemperatureMutation = useMutation({
  2743. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2744. onSuccess: (result) => {
  2745. setStatusControlMenu(null);
  2746. showToast(result.message);
  2747. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2748. },
  2749. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2750. });
  2751. const chamberTemperatureMutation = useMutation({
  2752. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2753. onSuccess: (result) => {
  2754. setStatusControlMenu(null);
  2755. showToast(result.message);
  2756. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2757. },
  2758. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2759. });
  2760. const fanSpeedMutation = useMutation({
  2761. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2762. api.setFanSpeed(printer.id, fan, speed),
  2763. onMutate: async ({ fan, speed }) => {
  2764. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2765. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2766. const fanField = {
  2767. part: 'cooling_fan_speed',
  2768. aux: 'big_fan1_speed',
  2769. aux2: 'left_aux_fan_speed',
  2770. chamber: 'big_fan2_speed',
  2771. }[fan];
  2772. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2773. old ? { ...old, [fanField]: speed } : old
  2774. );
  2775. return { previousStatus };
  2776. },
  2777. onSuccess: (result) => {
  2778. setStatusControlMenu(null);
  2779. showToast(result.message);
  2780. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2781. },
  2782. onError: (error: Error, _variables, context) => {
  2783. if (context?.previousStatus) {
  2784. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2785. }
  2786. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2787. },
  2788. });
  2789. const selectExtruderMutation = useMutation({
  2790. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2791. onMutate: async (extruder) => {
  2792. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2793. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2794. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2795. old ? { ...old, active_extruder: extruder } : old
  2796. );
  2797. return { previousStatus };
  2798. },
  2799. onSuccess: (result) => {
  2800. setStatusControlMenu(null);
  2801. showToast(result.message);
  2802. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2803. },
  2804. onError: (error: Error, _extruder, context) => {
  2805. if (context?.previousStatus) {
  2806. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2807. }
  2808. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2809. },
  2810. });
  2811. // Chamber light mutation with optimistic update
  2812. const chamberLightMutation = useMutation({
  2813. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2814. onMutate: async (on) => {
  2815. // Cancel any outgoing refetches
  2816. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2817. // Snapshot the previous value
  2818. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2819. // Optimistically update
  2820. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2821. ...old,
  2822. chamber_light: on,
  2823. }));
  2824. return { previousStatus };
  2825. },
  2826. onSuccess: (_, on) => {
  2827. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2828. },
  2829. onError: (error: Error, _, context) => {
  2830. // Rollback on error
  2831. if (context?.previousStatus) {
  2832. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2833. }
  2834. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2835. },
  2836. });
  2837. // Print speed mutation with optimistic update
  2838. const printSpeedMutation = useMutation({
  2839. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2840. onMutate: async (mode) => {
  2841. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2842. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2843. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2844. ...old,
  2845. speed_level: mode,
  2846. }));
  2847. return { previousStatus };
  2848. },
  2849. onError: (error: Error, _, context) => {
  2850. if (context?.previousStatus) {
  2851. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2852. }
  2853. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2854. },
  2855. });
  2856. const airductMutation = useMutation({
  2857. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2858. onMutate: async (mode) => {
  2859. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2860. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2861. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2862. ...old,
  2863. airduct_mode: mode === 'cooling' ? 0 : 1,
  2864. }));
  2865. return { previousStatus };
  2866. },
  2867. onError: (error: Error, _, context) => {
  2868. if (context?.previousStatus) {
  2869. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2870. }
  2871. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2872. },
  2873. });
  2874. const bedJogMutation = useMutation({
  2875. mutationFn: ({ distance }: { distance: number }) =>
  2876. api.bedJog(printer.id, distance),
  2877. onError: (error: Error) =>
  2878. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2879. });
  2880. const xyJogMutation = useMutation({
  2881. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2882. api.xyJog(printer.id, x, y),
  2883. onError: (error: Error) =>
  2884. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2885. });
  2886. const extruderJogMutation = useMutation({
  2887. mutationFn: (distance: number) =>
  2888. api.extruderJog(printer.id, distance),
  2889. onError: (error: Error) =>
  2890. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2891. });
  2892. const homeAxesMutation = useMutation({
  2893. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2894. onSuccess: () => {
  2895. showToast(t('printers.bedJog.homingStarted'));
  2896. },
  2897. onError: (error: Error) =>
  2898. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2899. });
  2900. // Plate detection setting mutation
  2901. const plateDetectionMutation = useMutation({
  2902. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2903. onSuccess: () => {
  2904. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2905. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2906. },
  2907. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2908. });
  2909. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2910. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2911. // metrics, and the print picker — so flipping this flag puts the printer
  2912. // out of service across every consumer in one place. Used from the
  2913. // overflow menu and EditPrinterModal.
  2914. const maintenanceMutation = useMutation({
  2915. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2916. onSuccess: (_data, isActive) => {
  2917. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2918. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2919. showToast(
  2920. isActive
  2921. ? t('printers.maintenance.toastExited', { name: printer.name })
  2922. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2923. 'success',
  2924. );
  2925. },
  2926. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2927. });
  2928. // Confirm before entering maintenance on a printing printer (entering mode
  2929. // disconnects MQTT, which stops progress tracking + completion notifications
  2930. // for the in-flight job).
  2931. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2932. const handleEnterMaintenance = () => {
  2933. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2934. setConfirmMaintenanceEnter(true);
  2935. } else {
  2936. maintenanceMutation.mutate(false);
  2937. }
  2938. };
  2939. // Query for printable objects (for skip functionality)
  2940. // Fetch when printing with 2+ objects OR when modal is open
  2941. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2942. const { data: objectsData } = useQuery({
  2943. queryKey: ['printableObjects', printer.id],
  2944. queryFn: () => api.getPrintableObjects(printer.id),
  2945. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2946. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2947. });
  2948. // State for tracking which AMS slot is being refreshed
  2949. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2950. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2951. const seenBusyStateRef = useRef<boolean>(false);
  2952. // Fallback timeout ref
  2953. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2954. // Minimum display time passed
  2955. const minTimePassedRef = useRef<boolean>(false);
  2956. // AMS slot refresh mutation
  2957. const refreshAmsSlotMutation = useMutation({
  2958. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2959. api.refreshAmsSlot(printer.id, amsId, slotId),
  2960. onMutate: ({ amsId, slotId }) => {
  2961. // Clear any existing timeout
  2962. if (refreshTimeoutRef.current) {
  2963. clearTimeout(refreshTimeoutRef.current);
  2964. }
  2965. // Reset state
  2966. seenBusyStateRef.current = false;
  2967. minTimePassedRef.current = false;
  2968. setRefreshingSlot({ amsId, slotId });
  2969. // Minimum display time (2 seconds)
  2970. setTimeout(() => {
  2971. minTimePassedRef.current = true;
  2972. }, 2000);
  2973. // Fallback timeout (30 seconds max)
  2974. refreshTimeoutRef.current = setTimeout(() => {
  2975. setRefreshingSlot(null);
  2976. }, 30000);
  2977. },
  2978. onSuccess: (data) => {
  2979. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2980. },
  2981. onError: (error: Error) => {
  2982. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2983. if (refreshTimeoutRef.current) {
  2984. clearTimeout(refreshTimeoutRef.current);
  2985. }
  2986. setRefreshingSlot(null);
  2987. },
  2988. });
  2989. // AMS load/unload mutations (#891)
  2990. const loadAmsTrayMutation = useMutation({
  2991. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  2992. api.loadAmsTray(printer.id, trayId, extruderId),
  2993. onSuccess: (data) => {
  2994. setFeedDirectionRequest(null);
  2995. showToast(data.message || t('printers.toast.loadInitiated'));
  2996. },
  2997. onError: (error: Error) => {
  2998. setFeedDirectionRequest(null);
  2999. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3000. },
  3001. });
  3002. const unloadAmsMutation = useMutation({
  3003. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3004. onSuccess: (data) => {
  3005. showToast(data.message || t('printers.toast.unloadInitiated'));
  3006. },
  3007. onError: (error: Error) => {
  3008. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3009. },
  3010. });
  3011. // Pending "which hotend?" question, non-null only while the dialog is open.
  3012. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3013. // load command has to name one — see FeedDirectionModal.
  3014. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3015. trayId: number;
  3016. amsId: number;
  3017. slotId: number;
  3018. slotLabel: string;
  3019. } | null>(null);
  3020. // Whether a load from this printer has to ask which hotend to feed.
  3021. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3022. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3023. // The external holder needs no question: its two tray ids name the side
  3024. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3025. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3026. // external spool, because it would occupy an extruder channel permanently.
  3027. //
  3028. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3029. // carries does not address an HT unit, so the load is refused whatever the
  3030. // answer. Asking first would only put a dialog in front of the same error.
  3031. const isExternal = amsId === 255;
  3032. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3033. loadAmsTrayMutation.mutate({ trayId });
  3034. return;
  3035. }
  3036. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3037. // front rather than sending a command the firmware will drop. BambuStudio
  3038. // shows the same message and returns without publishing anything.
  3039. if (!status?.fila_switch?.ready) {
  3040. showToast(t('printers.ams.switchNotReady'), 'warning');
  3041. return;
  3042. }
  3043. setFeedDirectionRequest({
  3044. trayId,
  3045. amsId,
  3046. slotId,
  3047. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3048. });
  3049. };
  3050. // Plate references state
  3051. const [plateReferences, setPlateReferences] = useState<{
  3052. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3053. max_references: number;
  3054. } | null>(null);
  3055. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3056. // Fetch plate references
  3057. const fetchPlateReferences = async () => {
  3058. try {
  3059. const data = await api.getPlateReferences(printer.id);
  3060. setPlateReferences(data);
  3061. } catch {
  3062. // Ignore errors - references will show as empty
  3063. }
  3064. };
  3065. // Toggle plate detection enabled/disabled
  3066. const handleTogglePlateDetection = () => {
  3067. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3068. };
  3069. // Open plate detection management modal (for calibration/references)
  3070. const handleOpenPlateManagement = async () => {
  3071. setIsCheckingPlate(true);
  3072. setPlateCheckResult(null);
  3073. // Auto-turn on light if it's off
  3074. const lightWasOff = status?.chamber_light === false;
  3075. setPlateCheckLightWasOff(lightWasOff);
  3076. if (lightWasOff) {
  3077. await api.setChamberLight(printer.id, true);
  3078. // Wait for light to physically turn on and camera to adjust exposure
  3079. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3080. await new Promise(resolve => setTimeout(resolve, 2500));
  3081. }
  3082. try {
  3083. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3084. setPlateCheckResult(result);
  3085. fetchPlateReferences();
  3086. } catch (error) {
  3087. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3088. // Restore light if check failed
  3089. if (lightWasOff) {
  3090. await api.setChamberLight(printer.id, false);
  3091. setPlateCheckLightWasOff(false);
  3092. }
  3093. } finally {
  3094. setIsCheckingPlate(false);
  3095. }
  3096. };
  3097. // Close plate check modal and restore light state
  3098. const closePlateCheckModal = useCallback(async () => {
  3099. setPlateCheckResult(null);
  3100. // Restore light to original state if we turned it on
  3101. if (plateCheckLightWasOff) {
  3102. await api.setChamberLight(printer.id, false);
  3103. setPlateCheckLightWasOff(false);
  3104. }
  3105. }, [plateCheckLightWasOff, printer.id]);
  3106. // Calibrate plate detection handler
  3107. const handleCalibratePlate = async (label?: string) => {
  3108. setIsCalibrating(true);
  3109. try {
  3110. const result = await api.calibratePlateDetection(printer.id, { label });
  3111. if (result.success) {
  3112. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3113. // Refresh references and re-check
  3114. fetchPlateReferences();
  3115. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3116. setPlateCheckResult(checkResult);
  3117. } else {
  3118. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3119. }
  3120. } catch (error) {
  3121. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3122. } finally {
  3123. setIsCalibrating(false);
  3124. }
  3125. };
  3126. // Update reference label
  3127. const handleUpdateRefLabel = async (index: number, label: string) => {
  3128. try {
  3129. await api.updatePlateReferenceLabel(printer.id, index, label);
  3130. setEditingRefLabel(null);
  3131. fetchPlateReferences();
  3132. } catch (error) {
  3133. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3134. }
  3135. };
  3136. // Delete reference
  3137. const handleDeleteRef = async (index: number) => {
  3138. try {
  3139. await api.deletePlateReference(printer.id, index);
  3140. showToast(t('printers.toast.referenceDeleted'), 'success');
  3141. fetchPlateReferences();
  3142. // Re-check to update counts
  3143. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3144. setPlateCheckResult(checkResult);
  3145. } catch (error) {
  3146. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3147. }
  3148. };
  3149. // Save ROI settings
  3150. const handleSaveRoi = async () => {
  3151. if (!editingRoi) return;
  3152. setIsSavingRoi(true);
  3153. try {
  3154. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3155. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3156. setEditingRoi(null);
  3157. // Re-check to see new ROI in action
  3158. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3159. setPlateCheckResult(checkResult);
  3160. } catch (error) {
  3161. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3162. } finally {
  3163. setIsSavingRoi(false);
  3164. }
  3165. };
  3166. // Close plate check modal on Escape key
  3167. useEffect(() => {
  3168. const handleEscape = (e: KeyboardEvent) => {
  3169. if (e.key === 'Escape' && plateCheckResult) {
  3170. closePlateCheckModal();
  3171. }
  3172. };
  3173. window.addEventListener('keydown', handleEscape);
  3174. return () => window.removeEventListener('keydown', handleEscape);
  3175. }, [plateCheckResult, closePlateCheckModal]);
  3176. // Watch ams_status_main to detect when RFID read completes
  3177. // ams_status_main: 0=idle, 2=rfid_identifying
  3178. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3179. useEffect(() => {
  3180. if (!refreshingSlot) return;
  3181. const amsStatus = status?.ams_status_main ?? 0;
  3182. // Track when we see non-idle state (printer is working)
  3183. if (amsStatus !== 0) {
  3184. seenBusyStateRef.current = true;
  3185. // Cancel any deferred clear since we're back to busy
  3186. if (deferredClearRef.current) {
  3187. clearTimeout(deferredClearRef.current);
  3188. deferredClearRef.current = null;
  3189. }
  3190. }
  3191. // When we've seen busy and now idle, clear (with min time check)
  3192. if (seenBusyStateRef.current && amsStatus === 0) {
  3193. if (minTimePassedRef.current) {
  3194. // Min time passed - clear now
  3195. if (refreshTimeoutRef.current) {
  3196. clearTimeout(refreshTimeoutRef.current);
  3197. }
  3198. setRefreshingSlot(null);
  3199. } else {
  3200. // Schedule clear after min time (2 seconds from start)
  3201. if (!deferredClearRef.current) {
  3202. deferredClearRef.current = setTimeout(() => {
  3203. if (refreshTimeoutRef.current) {
  3204. clearTimeout(refreshTimeoutRef.current);
  3205. }
  3206. setRefreshingSlot(null);
  3207. }, 2000);
  3208. }
  3209. }
  3210. }
  3211. return () => {
  3212. if (deferredClearRef.current) {
  3213. clearTimeout(deferredClearRef.current);
  3214. }
  3215. };
  3216. }, [status?.ams_status_main, refreshingSlot]);
  3217. useEffect(() => {
  3218. if (!showMenu) return;
  3219. const handleClickOutside = (event: MouseEvent) => {
  3220. const target = event.target as Node;
  3221. if (!printerActionsMenuRef.current?.contains(target)) {
  3222. setShowMenu(false);
  3223. }
  3224. };
  3225. document.addEventListener('mousedown', handleClickOutside);
  3226. return () => document.removeEventListener('mousedown', handleClickOutside);
  3227. }, [showMenu]);
  3228. if (shouldHide) {
  3229. return null;
  3230. }
  3231. // Size-based styling helpers
  3232. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3233. // width, its thumbnail and the printer name, but every label inside the
  3234. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3235. // S one -- the disparity was worst exactly where someone asking for more
  3236. // room ends up. These custom properties carry the scaled sizes into the
  3237. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3238. // unless they reach for a size that is already asking for more space.
  3239. // Plain computation rather than useMemo: this sits after the card's early
  3240. // returns, where a hook would break the rules-of-hooks ordering, and
  3241. // building ten strings per render costs nothing.
  3242. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3243. const getImageSize = () => {
  3244. switch (cardSize) {
  3245. case 1: return 'w-10 h-10';
  3246. case 2: return 'w-14 h-14';
  3247. case 3: return 'w-16 h-16';
  3248. case 4: return 'w-20 h-20';
  3249. default: return 'w-14 h-14';
  3250. }
  3251. };
  3252. const getTitleSize = () => {
  3253. switch (cardSize) {
  3254. case 1: return 'text-base truncate';
  3255. case 2: return 'text-lg';
  3256. case 3: return 'text-xl';
  3257. case 4: return 'text-2xl';
  3258. default: return 'text-lg';
  3259. }
  3260. };
  3261. const getSpacing = () => {
  3262. switch (cardSize) {
  3263. case 1: return 'mb-2';
  3264. case 2: return 'mb-4';
  3265. case 3: return 'mb-5';
  3266. case 4: return 'mb-6';
  3267. default: return 'mb-4';
  3268. }
  3269. };
  3270. // A dropped file always becomes a queue item, so a printer that is busy,
  3271. // offline or mid-drying is no reason to refuse the drop — it only means the
  3272. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3273. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3274. // what this would have done for them.
  3275. //
  3276. // What remains is what the flow actually performs: upload the file, then
  3277. // create a queue item. It never touches printers:control, which is what this
  3278. // used to check — so someone holding that but neither of these had the file
  3279. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3280. // button below has always checked this pair.
  3281. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3282. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3283. // and the modal's own "will start later" toast cannot disagree.
  3284. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3285. const handleCardDragEnter = (e: React.DragEvent) => {
  3286. e.preventDefault();
  3287. dragCounterRef.current++;
  3288. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3289. };
  3290. const handleCardDragOver = (e: React.DragEvent) => {
  3291. e.preventDefault();
  3292. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3293. };
  3294. const handleCardDragLeave = (e: React.DragEvent) => {
  3295. e.preventDefault();
  3296. dragCounterRef.current--;
  3297. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3298. };
  3299. const handleCardDrop = async (e: React.DragEvent) => {
  3300. e.preventDefault();
  3301. dragCounterRef.current = 0;
  3302. setIsDraggingFile(false);
  3303. if (!canDrop) return;
  3304. const droppedFiles = Array.from(e.dataTransfer.files);
  3305. const file = droppedFiles[0];
  3306. if (!file) return;
  3307. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3308. const lower = file.name.toLowerCase();
  3309. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3310. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3311. return;
  3312. }
  3313. setIsDropUploading(true);
  3314. try {
  3315. const result = await api.uploadLibraryFile(file, null);
  3316. // Check printer compatibility if sliced_for_model is available in metadata
  3317. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3318. const printerModel = mapModelCode(printer.model);
  3319. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3320. await api.deleteLibraryFile(result.id).catch(() => {});
  3321. showToast(
  3322. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3323. 'error'
  3324. );
  3325. return;
  3326. }
  3327. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3328. } catch {
  3329. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3330. } finally {
  3331. setIsDropUploading(false);
  3332. }
  3333. };
  3334. const handleCardClick = (e: React.MouseEvent) => {
  3335. if (viewMode !== 'compact' || selectionMode) return;
  3336. const target = e.target as HTMLElement;
  3337. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3338. onOpenCompactCard?.(printer.id);
  3339. };
  3340. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3341. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3342. // Opening a camera in a given mode, without touching which mode is remembered
  3343. // -- the split button's two halves want the same action but disagree about
  3344. // whether the choice was deliberate enough to keep.
  3345. const openCameraIn = (mode: CameraViewMode) => {
  3346. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3347. onOpenEmbeddedCamera(printer.id, printer.name);
  3348. } else {
  3349. openCameraWindow(printer.id);
  3350. }
  3351. };
  3352. // Picking a mode both opens the camera that way and makes it the mode the
  3353. // plain icon uses from now on. A menu that only changed a preference would
  3354. // leave the user with a second click to do the thing they already asked for.
  3355. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3356. [
  3357. {
  3358. mode: 'window' as const,
  3359. icon: <ExternalLink className="w-4 h-4" />,
  3360. label: t('settings.newWindow'),
  3361. title: t('settings.cameraWindowDescription'),
  3362. },
  3363. {
  3364. mode: 'embedded' as const,
  3365. icon: <PictureInPicture2 className="w-4 h-4" />,
  3366. label: t('settings.embeddedOverlay'),
  3367. title: t('settings.cameraOverlayDescription'),
  3368. },
  3369. ]
  3370. ).map(({ mode, icon, label, title }) => ({
  3371. icon,
  3372. // The remembered mode is marked in the label itself: the icon slot already
  3373. // carries the mode's own icon, and a separate tick column would push both
  3374. // entries out of line with every other card menu.
  3375. label: mode === cameraViewMode ? `${label} ✓` : label,
  3376. title,
  3377. onClick: () => {
  3378. onSelectCameraViewMode?.(mode);
  3379. openCameraIn(mode);
  3380. },
  3381. }));
  3382. const renderAmsSlotActions = ({
  3383. amsId,
  3384. slotId,
  3385. loadTrayId,
  3386. isRefreshing,
  3387. includeRfid = true,
  3388. }: {
  3389. amsId: number;
  3390. slotId: number;
  3391. loadTrayId: number;
  3392. isRefreshing?: boolean;
  3393. includeRfid?: boolean;
  3394. }) => {
  3395. const printerBusy = status?.state === 'RUNNING';
  3396. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3397. // ams*4+slot, so the id this menu carries does not name it to the load and
  3398. // unload endpoints — they reject it. Sending no slot falls back to the
  3399. // printer-wide unload, which is what this menu did for every slot before
  3400. // the per-slot form existed. Load has never worked on an HT slot for the
  3401. // same addressing reason; fixing that is a separate change.
  3402. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3403. return (
  3404. <>
  3405. {includeRfid && (
  3406. <button
  3407. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3408. hasPermission('printers:ams_rfid')
  3409. ? 'text-white hover:bg-bambu-dark-tertiary'
  3410. : 'text-bambu-gray/50 cursor-not-allowed'
  3411. }`}
  3412. onClick={(e) => {
  3413. e.stopPropagation();
  3414. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3415. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3416. }}
  3417. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3418. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3419. >
  3420. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3421. {t('printers.rfid.reread')}
  3422. </button>
  3423. )}
  3424. <button
  3425. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3426. hasPermission('printers:control')
  3427. ? 'text-white hover:bg-bambu-dark-tertiary'
  3428. : 'text-bambu-gray/50 cursor-not-allowed'
  3429. }`}
  3430. onClick={(e) => {
  3431. e.stopPropagation();
  3432. if (printerBusy || !hasPermission('printers:control')) return;
  3433. startAmsLoad(amsId, slotId, loadTrayId);
  3434. }}
  3435. disabled={printerBusy || !hasPermission('printers:control')}
  3436. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3437. >
  3438. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3439. {t('printers.ams.load')}
  3440. </button>
  3441. <button
  3442. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3443. hasPermission('printers:control')
  3444. ? 'text-white hover:bg-bambu-dark-tertiary'
  3445. : 'text-bambu-gray/50 cursor-not-allowed'
  3446. }`}
  3447. onClick={(e) => {
  3448. e.stopPropagation();
  3449. if (printerBusy || !hasPermission('printers:control')) return;
  3450. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3451. }}
  3452. disabled={printerBusy || !hasPermission('printers:control')}
  3453. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3454. >
  3455. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3456. {t('printers.ams.unload')}
  3457. </button>
  3458. </>
  3459. );
  3460. };
  3461. const printerActionsMenu = (
  3462. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3463. <Button
  3464. variant="secondary"
  3465. size="sm"
  3466. onClick={() => setShowMenu(!showMenu)}
  3467. title={t('common.more', 'More')}
  3468. className={footerIconButtonClass}
  3469. >
  3470. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3471. </Button>
  3472. {showMenu && (
  3473. <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">
  3474. <button
  3475. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3476. hasPermission('printers:update')
  3477. ? 'hover:bg-bambu-dark-tertiary'
  3478. : 'opacity-50 cursor-not-allowed'
  3479. }`}
  3480. onClick={() => {
  3481. if (!hasPermission('printers:update')) return;
  3482. setShowEditModal(true);
  3483. setShowMenu(false);
  3484. }}
  3485. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3486. >
  3487. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3488. {t('common.edit')}
  3489. </button>
  3490. <button
  3491. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3492. onClick={() => {
  3493. setShowPrinterInfo(true);
  3494. setShowMenu(false);
  3495. }}
  3496. >
  3497. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3498. {t('printers.printerInformation')}
  3499. </button>
  3500. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3501. <button
  3502. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3503. hasPermission('printers:update')
  3504. ? 'hover:bg-bambu-dark-tertiary'
  3505. : 'opacity-50 cursor-not-allowed'
  3506. }`}
  3507. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3508. onClick={() => {
  3509. if (!hasPermission('printers:update')) return;
  3510. setShowMenu(false);
  3511. if (printer.is_active !== false) {
  3512. handleEnterMaintenance();
  3513. } else {
  3514. maintenanceMutation.mutate(true);
  3515. }
  3516. }}
  3517. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3518. >
  3519. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3520. {printer.is_active !== false
  3521. ? t('printers.maintenance.menuEnter')
  3522. : t('printers.maintenance.menuExit')}
  3523. </button>
  3524. <button
  3525. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3526. onClick={() => {
  3527. connectMutation.mutate();
  3528. setShowMenu(false);
  3529. }}
  3530. >
  3531. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3532. {t('printers.reconnect')}
  3533. </button>
  3534. <button
  3535. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3536. disabled={forceRefreshMutation.isPending}
  3537. onClick={() => {
  3538. forceRefreshMutation.mutate();
  3539. setShowMenu(false);
  3540. }}
  3541. >
  3542. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3543. {t('printers.forceRefresh')}
  3544. </button>
  3545. <button
  3546. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3547. onClick={() => {
  3548. setShowMQTTDebug(true);
  3549. setShowMenu(false);
  3550. }}
  3551. >
  3552. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3553. {t('printers.mqttDebug')}
  3554. </button>
  3555. <button
  3556. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3557. onClick={() => {
  3558. setShowDiagnostic(true);
  3559. setShowMenu(false);
  3560. }}
  3561. >
  3562. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3563. {t('diagnostic.runButton')}
  3564. </button>
  3565. <button
  3566. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3567. hasPermission('printers:delete')
  3568. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3569. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3570. }`}
  3571. onClick={() => {
  3572. if (!hasPermission('printers:delete')) return;
  3573. setShowDeleteConfirm(true);
  3574. setShowMenu(false);
  3575. }}
  3576. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3577. >
  3578. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3579. {t('common.delete')}
  3580. </button>
  3581. </div>
  3582. )}
  3583. </div>
  3584. );
  3585. return (
  3586. <Card
  3587. id={`printer-card-${printer.id}`}
  3588. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3589. style={cardScaleStyle}
  3590. onClick={handleCardClick}
  3591. onDragEnter={handleCardDragEnter}
  3592. onDragOver={handleCardDragOver}
  3593. onDragLeave={handleCardDragLeave}
  3594. onDrop={handleCardDrop}
  3595. >
  3596. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3597. {selectionMode && (
  3598. <div
  3599. className="absolute inset-0 z-20 flex items-start p-2"
  3600. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3601. >
  3602. {isSelected ? (
  3603. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3604. ) : (
  3605. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3606. )}
  3607. </div>
  3608. )}
  3609. {/* Drop zone overlay */}
  3610. {(isDraggingFile || isDropUploading) && (
  3611. <div
  3612. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3613. isDropUploading
  3614. ? 'bg-bambu-green/10 border-bambu-green/50'
  3615. : canDrop
  3616. ? 'bg-bambu-green/10 border-bambu-green'
  3617. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3618. }`}
  3619. >
  3620. <div className="text-center">
  3621. {isDropUploading ? (
  3622. <>
  3623. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3624. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3625. </>
  3626. ) : canDrop ? (
  3627. <>
  3628. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3629. <p className="text-sm font-medium text-bambu-green">
  3630. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3631. </p>
  3632. </>
  3633. ) : (
  3634. <>
  3635. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3636. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3637. {!hasPermission('library:upload')
  3638. ? t('fileManager.noPermissionUpload')
  3639. : t('fileManager.noPermissionAddToQueue')}
  3640. </p>
  3641. </>
  3642. )}
  3643. </div>
  3644. </div>
  3645. )}
  3646. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3647. {/* Header */}
  3648. <div className={getSpacing()}>
  3649. {/* Top row: Image, Name, Menu */}
  3650. <div className="flex items-start justify-between gap-2">
  3651. <div className="flex items-center gap-3 min-w-0 flex-1">
  3652. {/* Printer Model Image */}
  3653. <img
  3654. src={getPrinterImage(printer.model)}
  3655. alt={printer.model || t('common.printer')}
  3656. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3657. />
  3658. <div className="min-w-0 flex-1">
  3659. <div className="flex items-center justify-between gap-2">
  3660. <div className="flex min-w-0 items-center gap-2">
  3661. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3662. {/* Connection indicator dot for compact mode */}
  3663. {viewMode === 'compact' && (() => {
  3664. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3665. const hasSevere = hmsErrors.some(isSevereHMSError);
  3666. const hasWarning = hmsErrors.length > 0;
  3667. const pipColor = !status?.connected
  3668. ? 'bg-status-error'
  3669. : hasSevere
  3670. ? 'bg-status-error'
  3671. : hasWarning
  3672. ? 'bg-status-warning'
  3673. : 'bg-status-ok';
  3674. const pipTitle = !status?.connected
  3675. ? t('printers.connection.offline')
  3676. : hasWarning
  3677. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3678. : t('printers.connection.connected');
  3679. return (
  3680. <div
  3681. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3682. title={pipTitle}
  3683. />
  3684. );
  3685. })()}
  3686. </div>
  3687. {viewMode === 'compact' && showClearPlateButton && (
  3688. <button
  3689. type="button"
  3690. onClick={() => clearPlateMutation.mutate()}
  3691. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3692. aria-label={t('printers.plateStatus.markCleared')}
  3693. 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"
  3694. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3695. >
  3696. {clearPlateMutation.isPending ? (
  3697. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3698. ) : (
  3699. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3700. )}
  3701. </button>
  3702. )}
  3703. </div>
  3704. <p className="text-sm text-bambu-gray">
  3705. {printer.model || 'Unknown Model'}
  3706. {/* Nozzle Info - only in expanded. Every fitted size, not
  3707. just nozzles[0]: the array is indexed by extruder, so on a
  3708. dual-nozzle machine with two sizes fitted showing the
  3709. first entry alone named one hotend and implied it was the
  3710. whole printer. Deduplicated, so the usual matching pair
  3711. still reads as a single "0.4mm". */}
  3712. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3713. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3714. • {installedNozzleDiameters(status).join(' / ')}mm
  3715. </span>
  3716. )}
  3717. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3718. <span className="ml-2 text-bambu-gray">
  3719. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3720. {Math.round(maintenanceInfo.total_print_hours)}h
  3721. </span>
  3722. )}
  3723. </p>
  3724. </div>
  3725. </div>
  3726. </div>
  3727. {/* Badges row - only in expanded mode */}
  3728. {viewMode === 'expanded' && (
  3729. <div className="mt-2">
  3730. <div className="flex flex-wrap items-center gap-2">
  3731. {/* Connection status badge (or Maintenance pill when out of service).
  3732. Defensive: only swap when is_active is EXPLICITLY false. An
  3733. undefined / missing field defaults to "active" so the regular
  3734. pill renders — matches the backend default and prevents test
  3735. fixtures (or stale clients) from accidentally tripping the
  3736. maintenance UI. */}
  3737. {printer.is_active === false ? (
  3738. <span
  3739. 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"
  3740. title={t('printers.maintenance.subtitle')}
  3741. >
  3742. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3743. {t('printers.maintenance.pillLabel')}
  3744. </span>
  3745. ) : (
  3746. <span
  3747. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3748. status?.connected
  3749. ? 'bg-status-ok/20 text-status-ok'
  3750. : 'bg-status-error/20 text-status-error'
  3751. }`}
  3752. >
  3753. {status?.connected ? (
  3754. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3755. ) : (
  3756. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3757. )}
  3758. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3759. </span>
  3760. )}
  3761. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3762. {printer.is_active !== false && !status?.connected && (
  3763. <button
  3764. onClick={() => setShowDiagnostic(true)}
  3765. 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"
  3766. title={t('diagnostic.runButton')}
  3767. >
  3768. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3769. {t('diagnostic.runButton')}
  3770. </button>
  3771. )}
  3772. {/* Network connection indicator */}
  3773. {status?.connected && status?.wired_network && (
  3774. <span
  3775. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3776. title={t('printers.connection.ethernet', 'Ethernet')}
  3777. >
  3778. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3779. {t('printers.connection.ethernet', 'Ethernet')}
  3780. </span>
  3781. )}
  3782. {/* WiFi signal indicator */}
  3783. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3784. <span
  3785. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3786. wifiSignal >= -50
  3787. ? 'bg-status-ok/20 text-status-ok'
  3788. : wifiSignal >= -60
  3789. ? 'bg-status-ok/20 text-status-ok'
  3790. : wifiSignal >= -70
  3791. ? 'bg-status-warning/20 text-status-warning'
  3792. : wifiSignal >= -80
  3793. ? 'bg-orange-500/20 text-orange-600'
  3794. : 'bg-status-error/20 text-status-error'
  3795. }`}
  3796. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3797. >
  3798. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3799. {wifiSignal}dBm
  3800. </span>
  3801. )}
  3802. {/* HMS Status Indicator */}
  3803. {status?.connected && (() => {
  3804. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3805. return (
  3806. <button
  3807. onClick={() => setShowHMSModal(true)}
  3808. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3809. knownErrors.length > 0
  3810. ? knownErrors.some(isSevereHMSError)
  3811. ? 'bg-status-error/20 text-status-error'
  3812. : 'bg-status-warning/20 text-status-warning'
  3813. : 'bg-status-ok/20 text-status-ok'
  3814. }`}
  3815. title={t('printers.clickToViewHmsErrors')}
  3816. >
  3817. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3818. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3819. </button>
  3820. );
  3821. })()}
  3822. {/* AI failure detection badge (#1546) — always shown while detection
  3823. is enabled for this printer, like the other health badges. Gray
  3824. "Idle" outside a monitored print, class-colored during one. */}
  3825. {aiDetectionEnabled && (() => {
  3826. const cls = aiDetectionClass(aiDetection);
  3827. const colorClass =
  3828. cls === 'failure'
  3829. ? 'bg-status-error/20 text-status-error'
  3830. : cls === 'warning'
  3831. ? 'bg-status-warning/20 text-status-warning'
  3832. : cls === 'safe'
  3833. ? 'bg-status-ok/20 text-status-ok'
  3834. : cls === 'error'
  3835. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3836. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3837. // 'error' and 'unknown' have no score to quote — saying
  3838. // "Safe (0.000)" for a print nothing is looking at is the
  3839. // whole of #2952.
  3840. const title =
  3841. cls === 'error'
  3842. ? t('printers.aiDetection.tooltipError', {
  3843. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3844. })
  3845. : cls === 'unknown'
  3846. ? t('printers.aiDetection.tooltipUnknown')
  3847. : aiDetection
  3848. ? t('printers.aiDetection.tooltip', {
  3849. status: t(`printers.aiDetection.${cls}`),
  3850. score: aiDetection.score.toFixed(3),
  3851. })
  3852. : t('printers.aiDetection.tooltipIdle');
  3853. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3854. return (
  3855. <button
  3856. onClick={() => setShowAiModal(true)}
  3857. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3858. title={title}
  3859. >
  3860. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3861. {t(`printers.aiDetection.${cls}`)}
  3862. </button>
  3863. );
  3864. })()}
  3865. {/* Maintenance Status Indicator */}
  3866. {maintenanceInfo && (
  3867. <button
  3868. onClick={() => navigate('/maintenance')}
  3869. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3870. maintenanceInfo.due_count > 0
  3871. ? 'bg-status-error/20 text-status-error'
  3872. : maintenanceInfo.warning_count > 0
  3873. ? 'bg-status-warning/20 text-status-warning'
  3874. : 'bg-status-ok/20 text-status-ok'
  3875. }`}
  3876. title={
  3877. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3878. ? `${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`
  3879. : t('printers.maintenanceUpToDate')
  3880. }
  3881. >
  3882. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3883. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3884. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3885. : 'OK'}
  3886. </button>
  3887. )}
  3888. {/* Queue Count Badge */}
  3889. {queueCount > 0 && (
  3890. <button
  3891. onClick={() => navigate('/queue')}
  3892. 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"
  3893. title={t('printers.queue.inQueue', { count: queueCount })}
  3894. >
  3895. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3896. {queueCount}
  3897. </button>
  3898. )}
  3899. {/* Firmware Version Badge */}
  3900. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3901. <button
  3902. onClick={() => setShowFirmwareModal(true)}
  3903. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3904. firmwareInfo.update_available
  3905. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3906. : 'bg-status-ok/20 text-status-ok'
  3907. }`}
  3908. title={
  3909. firmwareInfo.update_available
  3910. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3911. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3912. }
  3913. >
  3914. {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)]" />}
  3915. {firmwareInfo.current_version}
  3916. </button>
  3917. ) : status?.firmware_version ? (
  3918. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3919. {status.firmware_version}
  3920. </span>
  3921. ) : null}
  3922. {/* Enclosure Door Badge — models with an actual door sensor.
  3923. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3924. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3925. <span
  3926. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3927. status.door_open
  3928. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3929. : 'bg-status-ok/20 text-status-ok'
  3930. }`}
  3931. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3932. >
  3933. {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)]" />}
  3934. </span>
  3935. )}
  3936. </div>
  3937. </div>
  3938. )}
  3939. </div>
  3940. {/* Delete Confirmation */}
  3941. {showDeleteConfirm && (
  3942. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3943. <Card className="w-full max-w-md mx-4">
  3944. <CardContent>
  3945. <div className="flex items-start gap-3 mb-4">
  3946. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3947. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3948. </div>
  3949. <div>
  3950. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3951. <p className="text-sm text-bambu-gray mt-1">
  3952. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3953. </p>
  3954. </div>
  3955. </div>
  3956. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3957. <label className="flex items-start gap-3 cursor-pointer">
  3958. <input
  3959. type="checkbox"
  3960. checked={deleteArchives}
  3961. onChange={(e) => setDeleteArchives(e.target.checked)}
  3962. 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"
  3963. />
  3964. <div>
  3965. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3966. <p className="text-xs text-bambu-gray mt-0.5">
  3967. {deleteArchives
  3968. ? t('printers.confirm.deleteArchivesNote')
  3969. : t('printers.confirm.keepArchivesNote')}
  3970. </p>
  3971. </div>
  3972. </label>
  3973. </div>
  3974. <div className="flex justify-end gap-2">
  3975. <Button
  3976. variant="secondary"
  3977. onClick={() => {
  3978. setShowDeleteConfirm(false);
  3979. setDeleteArchives(true);
  3980. }}
  3981. >
  3982. {t('common.cancel')}
  3983. </Button>
  3984. <Button
  3985. variant="danger"
  3986. onClick={() => {
  3987. deleteMutation.mutate({ deleteArchives });
  3988. setShowDeleteConfirm(false);
  3989. setDeleteArchives(true);
  3990. }}
  3991. >
  3992. Delete
  3993. </Button>
  3994. </div>
  3995. </CardContent>
  3996. </Card>
  3997. </div>
  3998. )}
  3999. {/* Status — see the equivalent defensive `=== false` check on the
  4000. header pill above for why this is not `!printer.is_active`. */}
  4001. {printer.is_active === false ? (
  4002. // Maintenance mode (#1476) — replaces the cover/progress container
  4003. // so the card keeps the same height. Renders for both compact and
  4004. // expanded view modes so the printer stays visible but plainly
  4005. // out-of-service.
  4006. <>
  4007. {viewMode === 'compact' ? (
  4008. <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">
  4009. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4010. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4011. {t('printers.maintenance.pillLabel')}
  4012. </span>
  4013. </div>
  4014. ) : (
  4015. <>
  4016. <div className="flex items-center gap-2 mb-2">
  4017. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4018. {t('printers.status.title', 'Status')}
  4019. </span>
  4020. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4021. </div>
  4022. <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">
  4023. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4024. <div className="flex-1 min-w-0">
  4025. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4026. {t('printers.maintenance.title')}
  4027. </p>
  4028. <p className="text-xs text-bambu-gray mt-0.5">
  4029. {t('printers.maintenance.subtitle')}
  4030. </p>
  4031. </div>
  4032. <Button
  4033. variant="secondary"
  4034. size="sm"
  4035. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4036. onClick={() => maintenanceMutation.mutate(true)}
  4037. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4038. >
  4039. {t('printers.maintenance.exitButton')}
  4040. </Button>
  4041. </div>
  4042. </>
  4043. )}
  4044. </>
  4045. ) : status?.connected && (
  4046. <>
  4047. {/* Compact: Simple status bar */}
  4048. {viewMode === 'compact' ? (
  4049. (() => {
  4050. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4051. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4052. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4053. ? Math.max(0, Math.min(100, status.progress || 0))
  4054. : showClearPlateButton
  4055. ? 100
  4056. : hasProblem
  4057. ? 100
  4058. : 0;
  4059. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4060. const compactProgressClass = hasProblem
  4061. ? 'bg-status-error'
  4062. : status.state === 'PAUSE'
  4063. ? 'bg-status-warning'
  4064. : 'bg-bambu-green';
  4065. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4066. const hasCompactLayers =
  4067. isActiveCompactPrint &&
  4068. status.layer_num != null &&
  4069. status.total_layers != null &&
  4070. status.total_layers > 0;
  4071. return (
  4072. <>
  4073. <div className="relative mt-2 flex items-center gap-2">
  4074. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4075. <div
  4076. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4077. style={{ width: `${compactProgress}%` }}
  4078. />
  4079. </div>
  4080. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4081. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4082. </span>
  4083. </div>
  4084. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4085. enough to answer "which printer finishes first", which is what a
  4086. wall-mounted fleet view is for. One line of the metrics the
  4087. expanded card already renders, using the same formatters and the
  4088. same ETA styling so S and M read alike. The row keeps its height
  4089. when idle so cards don't shift as prints start and stop. */}
  4090. <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">
  4091. {hasCompactEta && (
  4092. <>
  4093. <span className="flex shrink-0 items-center gap-1">
  4094. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4095. {formatDuration(status.remaining_time! * 60)}
  4096. </span>
  4097. <span
  4098. className="shrink-0 font-medium text-bambu-green"
  4099. title={t('printers.estimatedCompletion')}
  4100. >
  4101. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4102. </span>
  4103. </>
  4104. )}
  4105. {hasCompactLayers && (
  4106. <span className="flex min-w-0 items-center gap-1 truncate">
  4107. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4108. {status.layer_num}/{status.total_layers}
  4109. </span>
  4110. )}
  4111. </div>
  4112. </>
  4113. );
  4114. })()
  4115. ) : (
  4116. /* Expanded: Full status section */
  4117. <>
  4118. <div className="flex items-center gap-2 mb-2">
  4119. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4120. {t('printers.status.title', 'Status')}
  4121. </span>
  4122. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4123. </div>
  4124. {/* Current Print or Idle Placeholder */}
  4125. {(() => {
  4126. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4127. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4128. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4129. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4130. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4131. // A running print always has at least one object, so a count of
  4132. // zero means "not loaded", not "nothing to skip" — after a
  4133. // restart mid-print the list is empty until something rebuilds
  4134. // it. Treating that as nothing-to-skip disabled the only
  4135. // control that opens the modal, and the modal's own fetch is
  4136. // what rebuilds the list, so the print could never get it back.
  4137. // Exactly one object is the real nothing-to-skip case.
  4138. const objectCount = status.printable_objects_count ?? 0;
  4139. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4140. return (
  4141. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4142. <button
  4143. onClick={() => setShowSkipObjectsModal(true)}
  4144. disabled={!canSkipObjects}
  4145. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4146. canSkipObjects
  4147. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4148. : 'text-bambu-gray/30 cursor-not-allowed'
  4149. }`}
  4150. title={
  4151. !hasPermission('printers:control')
  4152. ? t('printers.permission.noControl')
  4153. : !isActivePrint
  4154. ? t('printers.skipObjects.onlyWhilePrinting')
  4155. : objectCount === 1
  4156. ? t('printers.skipObjects.requiresMultiple')
  4157. : t('printers.skipObjects.tooltip')
  4158. }
  4159. >
  4160. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4161. {objectsData && objectsData.skipped_count > 0 && (
  4162. <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">
  4163. {objectsData.skipped_count}
  4164. </span>
  4165. )}
  4166. </button>
  4167. <div className="flex items-stretch gap-2">
  4168. <CoverImage
  4169. url={coverUrl}
  4170. printName={printName || undefined}
  4171. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4172. />
  4173. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4174. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4175. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4176. {plateStatusPill}
  4177. </div>
  4178. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4179. {printName || t('printers.noActiveJob', 'No active job')}
  4180. </p>
  4181. <div className="flex h-3 items-center gap-2 text-sm">
  4182. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4183. <div
  4184. 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`}
  4185. style={{ width: `${progress}%` }}
  4186. />
  4187. </div>
  4188. <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>
  4189. </div>
  4190. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4191. {isActivePrint ? (
  4192. <>
  4193. {status.remaining_time != null && status.remaining_time > 0 && (
  4194. <>
  4195. <span className="flex items-center gap-1">
  4196. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4197. {formatDuration(status.remaining_time * 60)}
  4198. </span>
  4199. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4200. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4201. </span>
  4202. </>
  4203. )}
  4204. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4205. <span className="flex items-center gap-1">
  4206. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4207. {status.layer_num}/{status.total_layers}
  4208. </span>
  4209. )}
  4210. {currentPrintUser && (
  4211. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4212. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4213. {currentPrintUser}
  4214. </span>
  4215. )}
  4216. </>
  4217. ) : lastPrint ? (
  4218. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4219. Last: {lastPrint.print_name || lastPrint.filename}
  4220. {lastPrint.completed_at && (
  4221. <span className="ml-1 text-bambu-gray/60">
  4222. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4223. </span>
  4224. )}
  4225. </p>
  4226. ) : (
  4227. <span>{t('printers.readyToPrint')}</span>
  4228. )}
  4229. </div>
  4230. </div>
  4231. </div>
  4232. <PrinterQueueWidget
  4233. printerId={printer.id}
  4234. printerModel={printer.model}
  4235. loadedFilamentTypes={loadedFilamentTypes}
  4236. loadedFilaments={loadedFilaments}
  4237. loadedVariants={loadedVariants}
  4238. variant="panelExtension"
  4239. />
  4240. </div>
  4241. );
  4242. })()}
  4243. </>
  4244. )}
  4245. {/* Temperatures */}
  4246. {status.temperatures && viewMode === 'expanded' && (() => {
  4247. // Use actual heater states from MQTT stream
  4248. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4249. const bedHeating = status.temperatures.bed_heating || false;
  4250. const chamberHeating = status.temperatures.chamber_heating || false;
  4251. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4252. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4253. const kinds: HeaterSensorKind[] = ['nozzle'];
  4254. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4255. kinds.push('bed');
  4256. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4257. return kinds;
  4258. })();
  4259. // active_extruder: 0=right, 1=left
  4260. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4261. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4262. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4263. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4264. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4265. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4266. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4267. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4268. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4269. 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 ${
  4270. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4271. }`;
  4272. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4273. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4274. // the widget there is at best dead UI and at worst suggests a
  4275. // control that does nothing. Mirrors the enclosure-door badge
  4276. // gate above.
  4277. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4278. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4279. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4280. // show it only when the printer actually reports it (airduct part id 3,
  4281. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4282. // have a built-in chamber fan that's always present, so they keep the
  4283. // existing model-list gate and the "Chamber Fan" label.
  4284. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4285. const chamberFanLabel = isExhaustModel
  4286. ? t('printers.fans.exhaust')
  4287. : t('printers.fans.chamber');
  4288. // Composed rather than either/or so both lists stay live for
  4289. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4290. // where that fan is an add-on kit — actually report it. Written
  4291. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4292. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4293. // which reads as if removing them were safe.
  4294. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4295. const fanItems: {
  4296. key: string;
  4297. label: string;
  4298. value: number;
  4299. Icon: typeof Fan;
  4300. activeClass: string;
  4301. }[] = [
  4302. {
  4303. key: 'part',
  4304. label: t('printers.fans.partCooling'),
  4305. value: status.cooling_fan_speed ?? 0,
  4306. Icon: Fan,
  4307. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4308. },
  4309. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4310. // Only reported (non-null) when the firmware lists airduct part
  4311. // id 10, i.e. when the fan is physically installed. Placed
  4312. // before the right-hand auxiliary fan so the two aux badges read
  4313. // left-to-right in the same order as the physical hardware.
  4314. ...(status.left_aux_fan_speed != null
  4315. ? [
  4316. {
  4317. key: 'aux2',
  4318. label: t('printers.fans.leftAuxiliary'),
  4319. value: status.left_aux_fan_speed,
  4320. Icon: Wind,
  4321. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4322. },
  4323. ]
  4324. : []),
  4325. {
  4326. key: 'aux',
  4327. label: t('printers.fans.auxiliary'),
  4328. value: status.big_fan1_speed ?? 0,
  4329. Icon: Wind,
  4330. activeClass: 'text-blue-600 dark:text-blue-400',
  4331. },
  4332. ...(showChamberFan
  4333. ? [
  4334. {
  4335. key: 'chamber',
  4336. label: chamberFanLabel,
  4337. value: status.big_fan2_speed ?? 0,
  4338. Icon: AirVent,
  4339. activeClass: 'text-green-600 dark:text-green-400',
  4340. },
  4341. ]
  4342. : []),
  4343. ];
  4344. return (
  4345. <>
  4346. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4347. {/* Nozzle temp - combined for dual nozzle */}
  4348. <div
  4349. className={statusControlClass}
  4350. title={statusControlTitle}
  4351. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4352. >
  4353. <button
  4354. type="button"
  4355. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4356. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4357. onClick={(e) => {
  4358. e.stopPropagation();
  4359. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4360. }}
  4361. >
  4362. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4363. </button>
  4364. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4365. {status.temperatures.nozzle_2 !== undefined ? (
  4366. <>
  4367. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4368. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4369. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4370. </p>
  4371. </>
  4372. ) : singleNozzleSlot ? (
  4373. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4374. <div className="cursor-default">
  4375. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4376. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4377. {Math.round(status.temperatures.nozzle || 0)}°C
  4378. </p>
  4379. </div>
  4380. </NozzleSlotHoverCard>
  4381. ) : (
  4382. <>
  4383. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4384. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4385. {Math.round(status.temperatures.nozzle || 0)}°C
  4386. </p>
  4387. </>
  4388. )}
  4389. {statusControlMenu === 'nozzle-temp' && (
  4390. isDualNozzle ? (
  4391. <IndicatorControlPopover
  4392. title="Set Nozzle Temperatures"
  4393. widthClass="w-[300px]"
  4394. popoverWidth={300}
  4395. popoverHeight={260}
  4396. isPending={nozzleTemperatureMutation.isPending}
  4397. onClose={() => setStatusControlMenu(null)}
  4398. >
  4399. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4400. <NozzleTemperatureControlBox
  4401. label="Left Temp"
  4402. current={status.temperatures.nozzle}
  4403. target={status.temperatures.nozzle_target}
  4404. isActive={activeNozzle === 'L'}
  4405. isPending={nozzleTemperatureMutation.isPending}
  4406. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4407. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4408. />
  4409. <NozzleTemperatureControlBox
  4410. label="Right Temp"
  4411. current={status.temperatures.nozzle_2}
  4412. target={status.temperatures.nozzle_2_target}
  4413. isActive={activeNozzle === 'R'}
  4414. isPending={nozzleTemperatureMutation.isPending}
  4415. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4416. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4417. />
  4418. </div>
  4419. </IndicatorControlPopover>
  4420. ) : (
  4421. <IndicatorControlPopover
  4422. title="Set Nozzle Temperature"
  4423. unit="°C"
  4424. customMin={0}
  4425. customMax={320}
  4426. isPending={nozzleTemperatureMutation.isPending}
  4427. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4428. onClose={() => setStatusControlMenu(null)}
  4429. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4430. />
  4431. )
  4432. )}
  4433. </div>
  4434. <div
  4435. className={statusControlClass}
  4436. title={statusControlTitle}
  4437. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4438. >
  4439. <button
  4440. type="button"
  4441. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4442. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4443. onClick={(e) => {
  4444. e.stopPropagation();
  4445. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4446. }}
  4447. >
  4448. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4449. </button>
  4450. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4451. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4452. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4453. {Math.round(status.temperatures.bed || 0)}°C
  4454. </p>
  4455. {statusControlMenu === 'bed-temp' && (
  4456. <IndicatorControlPopover
  4457. title="Set Bed Temperature"
  4458. unit="°C"
  4459. customMin={0}
  4460. customMax={140}
  4461. isPending={bedTemperatureMutation.isPending}
  4462. options={buildPresetOptions(bedTempPresets, 'C')}
  4463. onClose={() => setStatusControlMenu(null)}
  4464. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4465. />
  4466. )}
  4467. </div>
  4468. {status.temperatures.chamber !== undefined && (() => {
  4469. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4470. // but can't act on M141, so we keep the card read-only there.
  4471. const hasChamberHeater = status.supports_chamber_heater === true;
  4472. return (
  4473. <div
  4474. className={hasChamberHeater
  4475. ? statusControlClass
  4476. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4477. title={hasChamberHeater ? statusControlTitle : undefined}
  4478. onClick={hasChamberHeater
  4479. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4480. : undefined}
  4481. >
  4482. <button
  4483. type="button"
  4484. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4485. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4486. onClick={(e) => {
  4487. e.stopPropagation();
  4488. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4489. }}
  4490. >
  4491. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4492. </button>
  4493. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4494. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4495. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4496. {Math.round(status.temperatures.chamber || 0)}°C
  4497. </p>
  4498. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4499. <IndicatorControlPopover
  4500. title="Set Chamber Temperature"
  4501. unit="°C"
  4502. customMin={0}
  4503. customMax={MAX_CHAMBER_TEMP_C}
  4504. isPending={chamberTemperatureMutation.isPending}
  4505. options={buildPresetOptions(chamberTempPresets, 'C')}
  4506. onClose={() => setStatusControlMenu(null)}
  4507. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4508. />
  4509. )}
  4510. </div>
  4511. );
  4512. })()}
  4513. {/* Active nozzle indicator for dual-nozzle printers */}
  4514. {isDualNozzle && (
  4515. <DualNozzleHoverCard
  4516. leftSlot={leftNozzleSlot}
  4517. rightSlot={rightNozzleSlot}
  4518. activeNozzle={activeNozzle}
  4519. filamentInfo={filamentInfo}
  4520. >
  4521. <div
  4522. 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 ${
  4523. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4524. }`}
  4525. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4526. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4527. >
  4528. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4529. <div className="flex items-center gap-2">
  4530. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4531. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4532. </span>
  4533. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4534. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4535. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4536. </span>
  4537. </div>
  4538. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4539. {statusControlMenu === 'nozzle-select' && (
  4540. <IndicatorControlPopover
  4541. title="Set Nozzle Selection"
  4542. widthClass="w-[300px]"
  4543. popoverWidth={300}
  4544. popoverHeight={140}
  4545. isPending={selectExtruderMutation.isPending}
  4546. options={[
  4547. { label: 'Left', value: 1 },
  4548. { label: 'Right', value: 0 },
  4549. ]}
  4550. onClose={() => setStatusControlMenu(null)}
  4551. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4552. />
  4553. )}
  4554. </div>
  4555. </DualNozzleHoverCard>
  4556. )}
  4557. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4558. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4559. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4560. )}
  4561. </div>
  4562. <div className="mt-2 flex items-center gap-1.5">
  4563. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4564. const active = value > 0;
  4565. return (
  4566. <div
  4567. key={key}
  4568. 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 ${
  4569. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4570. }`}
  4571. title={canUseStatusControls ? label : statusControlTitle}
  4572. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4573. >
  4574. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4575. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4576. {value}%
  4577. </span>
  4578. {statusControlMenu === `fan-${key}` && (
  4579. <IndicatorControlPopover
  4580. title={`Set ${label} Speed`}
  4581. unit="%"
  4582. customMin={0}
  4583. customMax={100}
  4584. isPending={fanSpeedMutation.isPending}
  4585. options={buildPresetOptions(fanSpeedPresets, '%')}
  4586. onClose={() => setStatusControlMenu(null)}
  4587. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4588. />
  4589. )}
  4590. </div>
  4591. );
  4592. })}
  4593. </div>
  4594. </>
  4595. );
  4596. })()}
  4597. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4598. {/* Controls */}
  4599. {viewMode === 'expanded' && (() => {
  4600. // Determine print state for control buttons
  4601. const isRunning = status.state === 'RUNNING';
  4602. const isPaused = status.state === 'PAUSE';
  4603. const isPrinting = isRunning || isPaused;
  4604. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4605. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4606. 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';
  4607. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4608. return (
  4609. <div className="mt-3">
  4610. {/* Section Header */}
  4611. <div className="flex items-center gap-2 mb-2">
  4612. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4613. {t('printers.controls')}
  4614. </span>
  4615. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4616. </div>
  4617. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4618. {/* Left: Secondary controls */}
  4619. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4620. <button
  4621. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4622. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4623. className={`${iconControlClass} ${
  4624. status.chamber_light
  4625. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4626. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4627. }`}
  4628. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4629. >
  4630. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4631. </button>
  4632. {/* Airduct Mode (P2S / X2D / H2*) */}
  4633. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4634. const isHeating = status.airduct_mode === 1;
  4635. const Icon = isHeating ? Flame : Snowflake;
  4636. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4637. 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';
  4638. return (
  4639. <div className="relative">
  4640. <button
  4641. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4642. disabled={!hasPermission('printers:control')}
  4643. className={`${iconControlClass} ${bg}`}
  4644. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4645. >
  4646. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4647. </button>
  4648. {showAirductMenu === printer.id && (
  4649. <>
  4650. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4651. <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]">
  4652. {([
  4653. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4654. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4655. ] as const).map(({ mode, label, modeId }) => (
  4656. <button
  4657. key={mode}
  4658. onClick={() => {
  4659. airductMutation.mutate(mode);
  4660. setShowAirductMenu(null);
  4661. }}
  4662. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4663. status.airduct_mode === modeId
  4664. ? 'text-bambu-green bg-bambu-green/10'
  4665. : 'text-white hover:bg-bambu-dark-tertiary'
  4666. }`}
  4667. >
  4668. {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)]" />}
  4669. {label}
  4670. </button>
  4671. ))}
  4672. </div>
  4673. </>
  4674. )}
  4675. </div>
  4676. );
  4677. })()}
  4678. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4679. {(() => {
  4680. const canControl = hasPermission('printers:control');
  4681. const disabled = isPrinting || !canControl;
  4682. 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';
  4683. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4684. // nozzle-bed gap that means the same thing on every printer, so the
  4685. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4686. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4687. // plate toward the nozzle and closes it.
  4688. const zMovesToolhead = isBedSlinger(printer.model);
  4689. const requestZJog = (arrow: 'up' | 'down') => {
  4690. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4691. // No not-homed gate here, and no endstop bypass to gate either:
  4692. // since #2579 the jog is a bare move that never touches M211. That
  4693. // does not make it clamped — the firmware ignores soft endstops on
  4694. // MQTT G-code entirely, which is what the banner above warns about.
  4695. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4696. };
  4697. const requestXyJog = (x: number, y: number) => {
  4698. xyJogMutation.mutate({ x, y });
  4699. };
  4700. const requestExtruderJog = (distance: number) => {
  4701. extruderJogMutation.mutate(distance);
  4702. };
  4703. return (
  4704. <div className="relative">
  4705. <button
  4706. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4707. disabled={disabled}
  4708. className={`${iconControlClass} ${
  4709. disabled
  4710. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4711. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4712. }`}
  4713. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4714. >
  4715. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4716. </button>
  4717. {showBedJogMenu === printer.id && (
  4718. <>
  4719. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4720. <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">
  4721. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4722. {t('printers.bedJog.title')}
  4723. </div>
  4724. <div className="h-px bg-bambu-dark-tertiary" />
  4725. {/* #2579: Bambu firmware does not enforce soft endstops on
  4726. G-code sent over MQTT, so manual moves can drive past the
  4727. travel limits and cause a collision. Not fixable from our
  4728. side — warn prominently. */}
  4729. <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">
  4730. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4731. <span>{t('printers.bedJog.limitWarning')}</span>
  4732. </div>
  4733. <div className="h-px bg-bambu-dark-tertiary" />
  4734. <div className="flex justify-center px-3 py-2.5">
  4735. <div className="flex items-center justify-center gap-3">
  4736. <div className="grid grid-cols-3 gap-1">
  4737. <div />
  4738. <button
  4739. onClick={() => requestXyJog(0, bedJogStep)}
  4740. disabled={xyJogMutation.isPending}
  4741. className={jogButtonClass}
  4742. aria-label="Move Y forward"
  4743. >
  4744. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4745. </button>
  4746. <div />
  4747. <button
  4748. onClick={() => requestXyJog(-bedJogStep, 0)}
  4749. disabled={xyJogMutation.isPending}
  4750. className={jogButtonClass}
  4751. aria-label="Move X left"
  4752. >
  4753. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4754. </button>
  4755. <button
  4756. onClick={() => {
  4757. setShowBedJogMenu(null);
  4758. homeAxesMutation.mutate('all');
  4759. }}
  4760. disabled={homeAxesMutation.isPending}
  4761. className={jogButtonClass}
  4762. aria-label={t('printers.bedJog.homeZ')}
  4763. >
  4764. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4765. </button>
  4766. <button
  4767. onClick={() => requestXyJog(bedJogStep, 0)}
  4768. disabled={xyJogMutation.isPending}
  4769. className={jogButtonClass}
  4770. aria-label="Move X right"
  4771. >
  4772. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4773. </button>
  4774. <div />
  4775. <button
  4776. onClick={() => requestXyJog(0, -bedJogStep)}
  4777. disabled={xyJogMutation.isPending}
  4778. className={jogButtonClass}
  4779. aria-label="Move Y back"
  4780. >
  4781. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4782. </button>
  4783. <div />
  4784. </div>
  4785. <div className="flex flex-col items-center gap-1">
  4786. <button
  4787. onClick={() => requestZJog('up')}
  4788. disabled={bedJogMutation.isPending}
  4789. className={jogButtonClass}
  4790. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4791. >
  4792. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4793. </button>
  4794. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4795. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4796. </div>
  4797. <button
  4798. onClick={() => requestZJog('down')}
  4799. disabled={bedJogMutation.isPending}
  4800. className={jogButtonClass}
  4801. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4802. >
  4803. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4804. </button>
  4805. </div>
  4806. <div className="flex flex-col items-center gap-1">
  4807. <button
  4808. onClick={() => requestExtruderJog(-bedJogStep)}
  4809. disabled={extruderJogMutation.isPending}
  4810. className={jogButtonClass}
  4811. aria-label="Retract filament"
  4812. >
  4813. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4814. </button>
  4815. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4816. <span className="text-sm font-semibold leading-none">E</span>
  4817. </div>
  4818. <button
  4819. onClick={() => requestExtruderJog(bedJogStep)}
  4820. disabled={extruderJogMutation.isPending}
  4821. className={jogButtonClass}
  4822. aria-label="Extrude filament"
  4823. >
  4824. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4825. </button>
  4826. </div>
  4827. </div>
  4828. </div>
  4829. <div className="h-px bg-bambu-dark-tertiary" />
  4830. <div className="px-3 pt-2.5 pb-3">
  4831. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4832. {t('printers.bedJog.step')}
  4833. </div>
  4834. <div className="flex gap-1">
  4835. {[1, 10, 50].map((step) => (
  4836. <button
  4837. key={step}
  4838. onClick={() => setBedJogStep(step)}
  4839. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4840. bedJogStep === step
  4841. ? 'bg-bambu-green/20 text-bambu-green'
  4842. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4843. }`}
  4844. >
  4845. {step}
  4846. </button>
  4847. ))}
  4848. </div>
  4849. </div>
  4850. </div>
  4851. </>
  4852. )}
  4853. </div>
  4854. );
  4855. })()}
  4856. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4857. <button
  4858. onClick={handleTogglePlateDetection}
  4859. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4860. className={`${iconControlClass} rounded-r-none ${
  4861. printer.plate_detection_enabled
  4862. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4863. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4864. }`}
  4865. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4866. >
  4867. {plateDetectionMutation.isPending ? (
  4868. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4869. ) : (
  4870. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4871. )}
  4872. </button>
  4873. <button
  4874. onClick={handleOpenPlateManagement}
  4875. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4876. 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 ${
  4877. printer.plate_detection_enabled
  4878. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4879. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4880. }`}
  4881. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4882. >
  4883. {isCheckingPlate ? (
  4884. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4885. ) : (
  4886. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4887. )}
  4888. </button>
  4889. </div>
  4890. {/* Print Speed */}
  4891. {(() => (
  4892. <div className="relative">
  4893. <button
  4894. data-testid="speed-control"
  4895. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4896. disabled={!isPrinting || !hasPermission('printers:control')}
  4897. className={`${iconControlClass} ${
  4898. isPrinting
  4899. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4900. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4901. }`}
  4902. title={isPrinting ? t('printers.speed.title') : undefined}
  4903. >
  4904. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4905. </button>
  4906. {showSpeedMenu === printer.id && (
  4907. <>
  4908. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4909. <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]">
  4910. {([
  4911. { mode: 1, label: t('printers.speed.silent') },
  4912. { mode: 2, label: t('printers.speed.standard') },
  4913. { mode: 3, label: t('printers.speed.sport') },
  4914. { mode: 4, label: t('printers.speed.ludicrous') },
  4915. ] as const).map(({ mode, label }) => (
  4916. <button
  4917. key={mode}
  4918. onClick={() => {
  4919. printSpeedMutation.mutate(mode);
  4920. setShowSpeedMenu(null);
  4921. }}
  4922. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4923. status.speed_level === mode
  4924. ? 'text-bambu-green bg-bambu-green/10'
  4925. : 'text-white hover:bg-bambu-dark-tertiary'
  4926. }`}
  4927. >
  4928. {label}
  4929. </button>
  4930. ))}
  4931. </div>
  4932. </>
  4933. )}
  4934. </div>
  4935. ))()}
  4936. </div>
  4937. {/* Right: Print Control Buttons */}
  4938. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4939. {/* Pause/Resume button */}
  4940. {(() => {
  4941. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4942. return (
  4943. <button
  4944. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4945. disabled={pauseUnavailable}
  4946. className={`
  4947. ${printControlClass}
  4948. ${pauseUnavailable
  4949. ? unavailablePrintActionClass
  4950. : isPaused
  4951. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4952. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4953. }
  4954. `}
  4955. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4956. >
  4957. {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)]" />}
  4958. {isPaused ? t('printers.resume') : t('printers.pause')}
  4959. </button>
  4960. );
  4961. })()}
  4962. {/* Stop button */}
  4963. {(() => {
  4964. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4965. return (
  4966. <button
  4967. onClick={() => setShowStopConfirm(true)}
  4968. disabled={stopUnavailable}
  4969. className={`
  4970. ${printControlClass}
  4971. ${stopUnavailable
  4972. ? unavailablePrintActionClass
  4973. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4974. }
  4975. `}
  4976. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4977. >
  4978. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4979. {t('printers.stop')}
  4980. </button>
  4981. );
  4982. })()}
  4983. </div>
  4984. </div>
  4985. </div>
  4986. );
  4987. })()}
  4988. {/* AMS Units - 2-Column Grid Layout */}
  4989. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4990. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4991. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4992. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4993. // The external spool can only be hidden while some AMS remains to
  4994. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  4995. // filament section, so the toggle is not offered there and a stored
  4996. // preference from a printer that later lost its AMS cannot blank the
  4997. // row either — both read through canHideExternalSpool.
  4998. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  4999. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5000. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5001. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5002. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5003. // floating point, and that lands verbatim in the DOM.
  5004. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5005. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5006. // already grow to fill the row, so the 3.5rem is a floor they sit
  5007. // well above in practice -- raising it just costs a unit its place
  5008. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5009. // its line, and flex-grow stretches its single slot across the whole
  5010. // card. The AMS-HT's own width does scale, below, because its
  5011. // readings sit beside the slot rather than under it.
  5012. const slotMinWidth = '3.5rem';
  5013. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5014. // The AMS-HT holds a single spool, and its slot is the only thing
  5015. // on that row able to grow -- so it swallowed every spare pixel and
  5016. // shoved the temperature and humidity hard against the card's edge.
  5017. // Capping it at roughly two ordinary slots keeps the readings clear
  5018. // of the edge; the cap scales because the text inside the slot does.
  5019. const htSlotStyle: React.CSSProperties = {
  5020. minWidth: slotMinWidth,
  5021. maxWidth: scaledRem(7.25),
  5022. };
  5023. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5024. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5025. });
  5026. // #1762 (comment 2): while a print is running/paused, overlay a small
  5027. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5028. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5029. // staged to a printer with mismatched filament: the wrong-slot pill
  5030. // is visible the instant printing starts.
  5031. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5032. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5033. ? status.ams_mapping
  5034. : [];
  5035. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5036. const boundedSlotCount = Math.max(1, slotCount);
  5037. const gapCount = Math.max(0, boundedSlotCount - 1);
  5038. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5039. return {
  5040. flex: `1 1 ${minWidth}`,
  5041. minWidth,
  5042. };
  5043. };
  5044. return (
  5045. <div className="mt-3">
  5046. {/* Section Header */}
  5047. <div className="flex items-center gap-2 mb-2">
  5048. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5049. {t('printers.filaments')}
  5050. </span>
  5051. <AmsBackupBadge
  5052. state={status.ams_filament_backup}
  5053. onClick={() => setAmsBackupModalOpen(true)}
  5054. />
  5055. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5056. {/* Offered only when an AMS is present: on a printer that
  5057. feeds from the external spool alone, hiding it would
  5058. empty the row entirely (#1782). */}
  5059. {canHideExternalSpool && (
  5060. <>
  5061. <ExternalSpoolToggle
  5062. hidden={externalSpoolHidden}
  5063. onClick={toggleExternalSpool}
  5064. />
  5065. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5066. </>
  5067. )}
  5068. </div>
  5069. {/* AMS Content */}
  5070. <div className="flex flex-wrap gap-2">
  5071. {/* Regular AMS units */}
  5072. {regularAms.map((ams) => {
  5073. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5074. return (
  5075. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5076. {/* Header: Label + Stats (no icon) */}
  5077. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5078. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5079. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5080. <AmsNameHoverCard
  5081. ams={ams}
  5082. printerId={printer.id}
  5083. label={getAmsLabel(ams.id, ams.tray.length)}
  5084. amsLabels={amsLabels}
  5085. canEdit={hasPermission('printers:update')}
  5086. onSaved={refetchAmsLabels}
  5087. >
  5088. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5089. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5090. </span>
  5091. </AmsNameHoverCard>
  5092. {sideBadge?.kind === 'inlet' ? (
  5093. <InletBadge
  5094. inlet={sideBadge.inlet}
  5095. title={t('printers.amsSwitchInletTooltip', {
  5096. inlet: sideBadge.inlet,
  5097. side: FTS_INLET_SIDE[sideBadge.inlet],
  5098. })}
  5099. />
  5100. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5101. <NozzleBadge side={sideBadge.side} />
  5102. ) : null}
  5103. </div>
  5104. {(ams.humidity != null || ams.temp != null) && (
  5105. <div className="flex shrink-0 items-center gap-1.5">
  5106. {ams.humidity != null && (
  5107. <HumidityIndicator
  5108. humidity={ams.humidity}
  5109. goodThreshold={amsThresholds?.humidityGood}
  5110. fairThreshold={amsThresholds?.humidityFair}
  5111. onClick={() => setAmsHistoryModal({
  5112. amsId: ams.id,
  5113. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5114. mode: 'humidity',
  5115. })}
  5116. compact
  5117. />
  5118. )}
  5119. {ams.temp != null && (
  5120. <div className="mr-1">
  5121. <TemperatureIndicator
  5122. temp={ams.temp}
  5123. goodThreshold={amsThresholds?.tempGood}
  5124. fairThreshold={amsThresholds?.tempFair}
  5125. onClick={() => setAmsHistoryModal({
  5126. amsId: ams.id,
  5127. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5128. mode: 'temperature',
  5129. })}
  5130. compact
  5131. />
  5132. </div>
  5133. )}
  5134. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5135. Screen-only models (P1 series) keep the control but can't
  5136. be commanded: it stays disabled and says why (#2533). */}
  5137. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5138. <button
  5139. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5140. onClick={(e) => {
  5141. if (ams.dry_time > 0) {
  5142. stopDryingMutation.mutate(ams.id);
  5143. } else if (dryingPopoverAmsId === ams.id) {
  5144. setDryingPopoverAmsId(null);
  5145. } else {
  5146. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5147. }
  5148. }}
  5149. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5150. ams.dry_time > 0
  5151. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5152. : status.drying_screen_only || ams.dry_sf_reason?.length
  5153. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5154. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5155. }`}
  5156. 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')}
  5157. >
  5158. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5159. </button>
  5160. )}
  5161. </div>
  5162. )}
  5163. </div>
  5164. {/* Drying status bar. A dry_time whose countdown is not
  5165. ticking, with no active drying phase (a parked command —
  5166. e.g. an H2D mid-print already powering other drying — or
  5167. a paused cycle), is shown as "not running", not as an
  5168. active cycle: the amber badge claiming a running dry
  5169. that the AMS never began is how this was found. */}
  5170. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5171. <div className="flex items-center gap-2 rounded-lg bg-slate-100 dark:bg-slate-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]" title={t('printers.drying.notRunningHint')}>
  5172. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5173. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5174. {ams.dry_filament && (
  5175. <span className="text-slate-500/90 dark:text-slate-400/80">
  5176. {ams.dry_target_temp != null
  5177. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5178. : ams.dry_filament}
  5179. </span>
  5180. )}
  5181. {!status.drying_screen_only && (
  5182. <button
  5183. onClick={() => stopDryingMutation.mutate(ams.id)}
  5184. disabled={stopDryingMutation.isPending}
  5185. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5186. title={t('printers.drying.stop')}
  5187. >
  5188. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5189. </button>
  5190. )}
  5191. </div>
  5192. )}
  5193. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5194. <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)]">
  5195. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5196. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5197. {/* The temperature is only ever known from the target we
  5198. cached when sending the command — the filament can also
  5199. be read off a uniformly loaded unit, so it can outlive
  5200. the temperature (#2759). */}
  5201. {ams.dry_filament && (
  5202. <span className="text-amber-700/80 dark:text-amber-300/70">
  5203. {ams.dry_target_temp != null
  5204. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5205. : ams.dry_filament}
  5206. </span>
  5207. )}
  5208. <span className="text-amber-700/80 dark:text-amber-300/70">
  5209. {t('printers.drying.timeRemaining', {
  5210. time: ams.dry_time >= 60
  5211. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5212. : `${ams.dry_time}m`
  5213. })}
  5214. </span>
  5215. {/* A cycle on a screen-only model was started at the printer
  5216. and can only be stopped there (#2533). */}
  5217. {!status.drying_screen_only && (
  5218. <button
  5219. onClick={() => stopDryingMutation.mutate(ams.id)}
  5220. disabled={stopDryingMutation.isPending}
  5221. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5222. title={t('printers.drying.stop')}
  5223. >
  5224. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5225. </button>
  5226. )}
  5227. </div>
  5228. )}
  5229. {/* Slots grid: 4 columns - always render 4 slots */}
  5230. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5231. {[0, 1, 2, 3].map((slotIdx) => {
  5232. // Find tray data for this slot (may be undefined if data incomplete)
  5233. // Use array index if available, as tray.id may not always be set
  5234. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5235. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5236. const isEmpty = !tray?.tray_type;
  5237. const emptyKind = getEmptySlotKind(tray);
  5238. // Check if this is the currently loaded tray
  5239. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5240. const globalTrayId = ams.id * 4 + slotIdx;
  5241. const isActive = effectiveTrayNow === globalTrayId;
  5242. // Runout guidance (#2587): the slot the paused print now
  5243. // expects filament in, and the slot that ran out.
  5244. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5245. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5246. // Get cloud preset info if available
  5247. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5248. // Get saved slot preset mapping (for user-configured slots)
  5249. const slotPreset = slotPresets?.[globalTrayId];
  5250. // Only trusted while it still describes what the printer reports in the
  5251. // slot: the row survives a spool swap, and the display chain below puts
  5252. // it ahead of the live filament id (see slotPresetDescribesTray).
  5253. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5254. ? slotPreset?.preset_name
  5255. : undefined;
  5256. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5257. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5258. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5259. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5260. // Slot-assigned-only spool fill (no tag link required)
  5261. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5262. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5263. : undefined;
  5264. const slotSpoolForFill = slotAssignmentForFill
  5265. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5266. : undefined;
  5267. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5268. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5269. : null;
  5270. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5271. const inventoryFill = (() => {
  5272. const sp = inventoryAssignment?.spool;
  5273. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5274. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5275. }
  5276. return null;
  5277. })();
  5278. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5279. // (inventory weight_used may be stale or over-counted — #676)
  5280. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5281. ? null : inventoryFill;
  5282. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5283. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5284. : resolvedInventoryFill !== null ? 'inventory' as const
  5285. : hasFillLevel ? 'ams' as const
  5286. : undefined;
  5287. // Build filament data for hover card
  5288. const filamentData = tray?.tray_type ? {
  5289. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5290. // Spoolman spool name wins over cloud lookup so a slot bound to
  5291. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5292. // Design PLA") instead of whatever the printer's filament_id
  5293. // resolves to in the cloud catalog (often "Generic PLA" for
  5294. // P-prefix local presets). Spoolman's filament.name is just the
  5295. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5296. // the hover card shows "Devil Design PLA Basic" rather than the
  5297. // vendor-less form. Strip the "@<printer>..." suffix that
  5298. // BambuStudio appends to user-preset names.
  5299. 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,
  5300. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5301. colorHex: tray.tray_color || null,
  5302. kFactor: formatKValue(tray.k),
  5303. fillLevel: effectiveFill,
  5304. trayUuid: tray.tray_uuid || null,
  5305. tagUid: tray.tag_uid || null,
  5306. fillSource,
  5307. } : null;
  5308. // Check if this specific slot is being refreshed
  5309. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5310. refreshingSlot?.slotId === slotIdx;
  5311. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5312. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5313. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5314. ? `P${activePrintSlotIdx + 1}`
  5315. : null;
  5316. // Slot visual content (goes inside hover card)
  5317. const slotVisual = (
  5318. <div
  5319. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5320. isExpectedSlot
  5321. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5322. : isRanOutSlot
  5323. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5324. : isActive
  5325. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5326. : ''
  5327. }`}
  5328. >
  5329. {isExpectedSlot && (
  5330. <span
  5331. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5332. title={t('printers.expectedSlot.title')}
  5333. 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"
  5334. >
  5335. ↓
  5336. </span>
  5337. )}
  5338. {activePrintSlotLabel && (
  5339. <span
  5340. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5341. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5342. 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"
  5343. >
  5344. {activePrintSlotLabel}
  5345. </span>
  5346. )}
  5347. {/* Filament color circle with 1-based slot number centered inside */}
  5348. <FilamentSlotCircle
  5349. trayColor={tray?.tray_color}
  5350. trayType={tray?.tray_type}
  5351. isEmpty={isEmpty}
  5352. emptyKind={emptyKind}
  5353. slotNumber={slotIdx + 1}
  5354. />
  5355. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5356. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5357. </div>
  5358. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5359. {/* Fill bar */}
  5360. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5361. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5362. <div
  5363. className="h-full rounded-full transition-all"
  5364. style={{
  5365. width: `${effectiveFill}%`,
  5366. backgroundColor: getFillBarColor(effectiveFill),
  5367. }}
  5368. />
  5369. )}
  5370. </div>
  5371. </div>
  5372. );
  5373. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5374. return (
  5375. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5376. {/* Loading overlay during RFID re-read */}
  5377. {isRefreshing && (
  5378. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5379. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5380. </div>
  5381. )}
  5382. {/* Hover card wraps only the visual content */}
  5383. {filamentData ? (
  5384. <FilamentHoverCard
  5385. data={filamentData}
  5386. actions={renderAmsSlotActions({
  5387. amsId: ams.id,
  5388. slotId: slotIdx,
  5389. loadTrayId: ams.id * 4 + slotIdx,
  5390. isRefreshing,
  5391. })}
  5392. spoolman={{
  5393. enabled: spoolmanEnabled,
  5394. // #1457: slot assignment is the user's most explicit action — it must
  5395. // outrank the tag-link, which can be stale when a non-RFID slot's
  5396. // fallback tag is still attached to a previous spool in Spoolman.
  5397. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5398. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5399. spoolmanUrl,
  5400. syncMode: spoolmanSyncMode,
  5401. // Suppress Link button when slot is already occupied by ANY assignment
  5402. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5403. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5404. // still appearing on slots with a local Devil Design PLA assigned.
  5405. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5406. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5407. setLinkSpoolModal({
  5408. tagUid: filamentData.tagUid || linkTag,
  5409. trayUuid: filamentData.trayUuid || '',
  5410. printerId: printer.id,
  5411. amsId: ams.id,
  5412. trayId: slotIdx,
  5413. });
  5414. } : undefined,
  5415. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5416. }}
  5417. inventory={(() => {
  5418. if (spoolmanEnabled) {
  5419. if (spoolmanLoading) return undefined;
  5420. const slotAssignment = slotAssignmentForFill;
  5421. const spoolmanSpool = slotSpoolForFill;
  5422. return {
  5423. assignedSpool: spoolmanSpool ? {
  5424. id: spoolmanSpool.id,
  5425. material: spoolmanSpool.material,
  5426. subtype: spoolmanSpool.subtype,
  5427. brand: spoolmanSpool.brand ?? null,
  5428. color_name: spoolmanSpool.color_name ?? null,
  5429. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5430. // The spool's own swatch (#2967). Spoolman carries the
  5431. // extra stops but has no effect field at all, so those
  5432. // rolls gradient and never shimmer.
  5433. rgba: spoolmanSpool.rgba ?? null,
  5434. extra_colors: spoolmanSpool.extra_colors ?? null,
  5435. effect_type: spoolmanSpool.effect_type ?? null,
  5436. remainingWeightGrams: spoolmanSpool.label_weight
  5437. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5438. : undefined,
  5439. } : null,
  5440. onAssignSpool: () => setAssignSpoolModal({
  5441. printerId: printer.id,
  5442. amsId: ams.id,
  5443. trayId: slotIdx,
  5444. trayInfo: {
  5445. type: tray?.tray_type || filamentData.profile,
  5446. material: tray?.tray_type ?? undefined,
  5447. profile: filamentData.profile,
  5448. color: filamentData.colorHex || '',
  5449. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5450. },
  5451. }),
  5452. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5453. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5454. };
  5455. }
  5456. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5457. return {
  5458. assignedSpool: assignment?.spool ? {
  5459. id: assignment.spool.id,
  5460. material: assignment.spool.material,
  5461. subtype: assignment.spool.subtype,
  5462. brand: assignment.spool.brand,
  5463. color_name: assignment.spool.color_name,
  5464. // The spool's own swatch (#2967).
  5465. rgba: assignment.spool.rgba ?? null,
  5466. extra_colors: assignment.spool.extra_colors ?? null,
  5467. effect_type: assignment.spool.effect_type ?? null,
  5468. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5469. } : null,
  5470. onAssignSpool: () => setAssignSpoolModal({
  5471. printerId: printer.id,
  5472. amsId: ams.id,
  5473. trayId: slotIdx,
  5474. trayInfo: {
  5475. type: tray?.tray_type || filamentData.profile,
  5476. material: tray?.tray_type ?? undefined,
  5477. profile: filamentData.profile,
  5478. color: filamentData.colorHex || '',
  5479. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5480. },
  5481. }),
  5482. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5483. isAssigned: !!assignment || isBambuLabSpool(tray),
  5484. };
  5485. })()}
  5486. configureSlot={{
  5487. enabled: hasPermission('printers:control'),
  5488. onConfigure: () => setConfigureSlotModal({
  5489. amsId: ams.id,
  5490. trayId: slotIdx,
  5491. trayCount: ams.tray.length,
  5492. trayType: tray?.tray_type || undefined,
  5493. trayColor: tray?.tray_color || undefined,
  5494. traySubBrands: tray?.tray_sub_brands || undefined,
  5495. trayInfoIdx: tray?.tray_info_idx || undefined,
  5496. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5497. caliIdx: tray?.cali_idx,
  5498. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5499. }),
  5500. }}
  5501. >
  5502. {slotVisual}
  5503. </FilamentHoverCard>
  5504. ) : (
  5505. <EmptySlotHoverCard
  5506. kind={emptyKind ?? undefined}
  5507. actions={renderAmsSlotActions({
  5508. amsId: ams.id,
  5509. slotId: slotIdx,
  5510. loadTrayId: ams.id * 4 + slotIdx,
  5511. isRefreshing,
  5512. })}
  5513. configureSlot={{
  5514. enabled: hasPermission('printers:control'),
  5515. onConfigure: () => setConfigureSlotModal({
  5516. amsId: ams.id,
  5517. trayId: slotIdx,
  5518. trayCount: ams.tray.length,
  5519. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5520. }),
  5521. }}
  5522. onAssignSpool={() => setAssignSpoolModal({
  5523. printerId: printer.id,
  5524. amsId: ams.id,
  5525. trayId: slotIdx,
  5526. trayInfo: {
  5527. type: '',
  5528. material: undefined,
  5529. profile: '',
  5530. color: '',
  5531. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5532. },
  5533. })}
  5534. >
  5535. {slotVisual}
  5536. </EmptySlotHoverCard>
  5537. )}
  5538. </div>
  5539. );
  5540. })}
  5541. </div>
  5542. </div>
  5543. );
  5544. })}
  5545. {/* HT AMS units */}
  5546. {htAms.map((ams) => {
  5547. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5548. const tray = ams.tray[0];
  5549. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5550. const isEmpty = !tray?.tray_type;
  5551. const emptyKind = getEmptySlotKind(tray);
  5552. // Check if this is the currently loaded tray
  5553. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5554. const isActive = effectiveTrayNow === globalTrayId;
  5555. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5556. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5557. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5558. // Get cloud preset info if available
  5559. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5560. // Get saved slot preset mapping (for user-configured slots)
  5561. const slotPreset = slotPresets?.[globalTrayId];
  5562. // Only trusted while it still describes what the printer reports in the
  5563. // slot: the row survives a spool swap, and the display chain below puts
  5564. // it ahead of the live filament id (see slotPresetDescribesTray).
  5565. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5566. ? slotPreset?.preset_name
  5567. : undefined;
  5568. const htSlotId = tray?.id ?? 0;
  5569. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5570. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5571. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5572. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5573. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5574. const htInventoryFill = (() => {
  5575. const sp = htInventoryAssignment?.spool;
  5576. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5577. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5578. }
  5579. return null;
  5580. })();
  5581. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5582. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5583. ? null : htInventoryFill;
  5584. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5585. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5586. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5587. : undefined;
  5588. const htSlotSpoolForFill = htSlotAssignmentForFill
  5589. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5590. : undefined;
  5591. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5592. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5593. : null;
  5594. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5595. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5596. : htResolvedInventoryFill !== null ? 'inventory' as const
  5597. : hasFillLevel ? 'ams' as const
  5598. : undefined;
  5599. // Build filament data for hover card
  5600. const filamentData = tray?.tray_type ? {
  5601. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5602. 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,
  5603. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5604. colorHex: tray.tray_color || null,
  5605. kFactor: formatKValue(tray.k),
  5606. fillLevel: htEffectiveFill,
  5607. trayUuid: tray.tray_uuid || null,
  5608. tagUid: tray.tag_uid || null,
  5609. fillSource: htFillSource,
  5610. } : null;
  5611. // Check if this specific slot is being refreshed
  5612. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5613. refreshingSlot?.slotId === htSlotId;
  5614. // #1762 (comment 2): active print-slot index for this HT slot.
  5615. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5616. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5617. ? `P${htActivePrintSlotIdx + 1}`
  5618. : null;
  5619. // Slot visual content (goes inside hover card)
  5620. const slotVisual = (
  5621. <div
  5622. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5623. isExpectedSlot
  5624. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5625. : isRanOutSlot
  5626. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5627. : isActive
  5628. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5629. : ''
  5630. }`}
  5631. >
  5632. {isExpectedSlot && (
  5633. <span
  5634. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5635. title={t('printers.expectedSlot.title')}
  5636. 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"
  5637. >
  5638. ↓
  5639. </span>
  5640. )}
  5641. {htActivePrintSlotLabel && (
  5642. <span
  5643. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5644. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5645. 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"
  5646. >
  5647. {htActivePrintSlotLabel}
  5648. </span>
  5649. )}
  5650. {/* Filament color circle with 1-based slot number centered inside */}
  5651. <FilamentSlotCircle
  5652. trayColor={tray?.tray_color}
  5653. trayType={tray?.tray_type}
  5654. isEmpty={isEmpty}
  5655. emptyKind={emptyKind}
  5656. slotNumber={1}
  5657. />
  5658. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5659. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5660. </div>
  5661. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5662. {/* Fill bar */}
  5663. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5664. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5665. <div
  5666. className="h-full rounded-full transition-all"
  5667. style={{
  5668. width: `${htEffectiveFill}%`,
  5669. backgroundColor: getFillBarColor(htEffectiveFill),
  5670. }}
  5671. />
  5672. )}
  5673. </div>
  5674. </div>
  5675. );
  5676. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5677. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5678. // Without this override, the L view squishes HT into a sliver next to the
  5679. // 4-slot AMS neighbors.
  5680. // 11rem holds one slot plus the temperature/humidity
  5681. // column beside it; both grow with the body scale.
  5682. const htCardWidth = scaledRem(11);
  5683. const htCardStyle: React.CSSProperties = {
  5684. flex: `1 1 ${htCardWidth}`,
  5685. minWidth: htCardWidth,
  5686. // An AMS-HT is never wider than a full AMS. Without a
  5687. // ceiling, a unit that wraps onto a line of its own is
  5688. // the only flex item there and grow stretches its single
  5689. // slot across the entire card, leaving the readings
  5690. // stranded at the far edge.
  5691. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5692. };
  5693. return (
  5694. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5695. {/* Row 1: Label + Nozzle + Drying */}
  5696. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5697. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5698. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5699. <AmsNameHoverCard
  5700. ams={ams}
  5701. printerId={printer.id}
  5702. label={getAmsLabel(ams.id, ams.tray.length)}
  5703. amsLabels={amsLabels}
  5704. canEdit={hasPermission('printers:update')}
  5705. onSaved={refetchAmsLabels}
  5706. >
  5707. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5708. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5709. </span>
  5710. </AmsNameHoverCard>
  5711. {sideBadge?.kind === 'inlet' ? (
  5712. <InletBadge
  5713. inlet={sideBadge.inlet}
  5714. title={t('printers.amsSwitchInletTooltip', {
  5715. inlet: sideBadge.inlet,
  5716. side: FTS_INLET_SIDE[sideBadge.inlet],
  5717. })}
  5718. />
  5719. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5720. <NozzleBadge side={sideBadge.side} />
  5721. ) : null}
  5722. </div>
  5723. {/* Drying button for HT AMS */}
  5724. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5725. <div className="relative ml-auto">
  5726. <button
  5727. disabled={status.drying_screen_only}
  5728. onClick={(e) => {
  5729. if (ams.dry_time > 0) {
  5730. stopDryingMutation.mutate(ams.id);
  5731. } else if (dryingPopoverAmsId === ams.id) {
  5732. setDryingPopoverAmsId(null);
  5733. } else {
  5734. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5735. }
  5736. }}
  5737. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5738. ams.dry_time > 0
  5739. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5740. : status.drying_screen_only
  5741. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5742. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5743. }`}
  5744. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5745. >
  5746. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5747. </button>
  5748. </div>
  5749. )}
  5750. </div>
  5751. {/* HT AMS drying status bar. Same not-running split as the
  5752. standard-AMS bar above: a frozen countdown is not a
  5753. running cycle. */}
  5754. {ams.dry_time > 0 && (
  5755. <div className={`flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg px-2 py-1 text-[length:var(--pc-t9,9px)] ${ams.dry_countdown_stalled ? 'bg-slate-100 dark:bg-slate-500/10' : 'bg-amber-50 dark:bg-amber-500/10'}`} title={ams.dry_countdown_stalled ? t('printers.drying.notRunningHint') : undefined}>
  5756. {ams.dry_countdown_stalled
  5757. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5758. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5759. {ams.dry_countdown_stalled && (
  5760. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5761. )}
  5762. {ams.dry_filament && (
  5763. <span className={`${ams.dry_countdown_stalled ? 'text-slate-500/90 dark:text-slate-400/80' : 'text-amber-700/80 dark:text-amber-300/70'} text-[length:var(--pc-t8,8px)] truncate`}>
  5764. {ams.dry_target_temp != null
  5765. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5766. : ams.dry_filament}
  5767. </span>
  5768. )}
  5769. {!ams.dry_countdown_stalled && (
  5770. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5771. {ams.dry_time >= 60
  5772. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5773. : `${ams.dry_time}m`}
  5774. </span>
  5775. )}
  5776. {!status.drying_screen_only && (
  5777. <button
  5778. onClick={() => stopDryingMutation.mutate(ams.id)}
  5779. disabled={stopDryingMutation.isPending}
  5780. 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"
  5781. title={t('printers.drying.stop')}
  5782. >
  5783. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5784. </button>
  5785. )}
  5786. </div>
  5787. )}
  5788. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5789. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5790. {/* Slot wrapper with loading overlay */}
  5791. <div className="relative group flex-1" style={htSlotStyle}>
  5792. {/* Loading overlay during RFID re-read */}
  5793. {isHtRefreshing && (
  5794. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5795. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5796. </div>
  5797. )}
  5798. {/* Hover card wraps only the visual content */}
  5799. {filamentData ? (
  5800. <FilamentHoverCard
  5801. data={filamentData}
  5802. actions={renderAmsSlotActions({
  5803. amsId: ams.id,
  5804. slotId: htSlotId,
  5805. loadTrayId: ams.id * 4 + htSlotId,
  5806. isRefreshing: isHtRefreshing,
  5807. })}
  5808. spoolman={{
  5809. enabled: spoolmanEnabled,
  5810. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5811. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5812. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5813. spoolmanUrl,
  5814. syncMode: spoolmanSyncMode,
  5815. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5816. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5817. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5818. setLinkSpoolModal({
  5819. tagUid: filamentData.tagUid || linkTag,
  5820. trayUuid: filamentData.trayUuid || '',
  5821. printerId: printer.id,
  5822. amsId: ams.id,
  5823. trayId: htSlotId,
  5824. });
  5825. } : undefined,
  5826. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5827. }}
  5828. inventory={(() => {
  5829. if (spoolmanEnabled) {
  5830. if (spoolmanLoading) return undefined;
  5831. const slotAssignment = htSlotAssignmentForFill;
  5832. const spoolmanSpool = htSlotSpoolForFill;
  5833. return {
  5834. assignedSpool: spoolmanSpool ? {
  5835. id: spoolmanSpool.id,
  5836. material: spoolmanSpool.material,
  5837. subtype: spoolmanSpool.subtype,
  5838. brand: spoolmanSpool.brand ?? null,
  5839. color_name: spoolmanSpool.color_name ?? null,
  5840. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5841. // The spool's own swatch (#2967). Spoolman carries the
  5842. // extra stops but has no effect field at all, so those
  5843. // rolls gradient and never shimmer.
  5844. rgba: spoolmanSpool.rgba ?? null,
  5845. extra_colors: spoolmanSpool.extra_colors ?? null,
  5846. effect_type: spoolmanSpool.effect_type ?? null,
  5847. remainingWeightGrams: spoolmanSpool.label_weight
  5848. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5849. : undefined,
  5850. } : null,
  5851. onAssignSpool: () => setAssignSpoolModal({
  5852. printerId: printer.id,
  5853. amsId: ams.id,
  5854. trayId: htSlotId,
  5855. trayInfo: {
  5856. type: tray?.tray_type || filamentData.profile,
  5857. material: tray?.tray_type ?? undefined,
  5858. profile: filamentData.profile,
  5859. color: filamentData.colorHex || '',
  5860. location: getAmsLabel(ams.id, ams.tray.length),
  5861. },
  5862. }),
  5863. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5864. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5865. };
  5866. }
  5867. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5868. return {
  5869. assignedSpool: assignment?.spool ? {
  5870. id: assignment.spool.id,
  5871. material: assignment.spool.material,
  5872. subtype: assignment.spool.subtype,
  5873. brand: assignment.spool.brand,
  5874. color_name: assignment.spool.color_name,
  5875. // The spool's own swatch (#2967).
  5876. rgba: assignment.spool.rgba ?? null,
  5877. extra_colors: assignment.spool.extra_colors ?? null,
  5878. effect_type: assignment.spool.effect_type ?? null,
  5879. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5880. } : null,
  5881. onAssignSpool: () => setAssignSpoolModal({
  5882. printerId: printer.id,
  5883. amsId: ams.id,
  5884. trayId: htSlotId,
  5885. trayInfo: {
  5886. type: tray?.tray_type || filamentData.profile,
  5887. material: tray?.tray_type ?? undefined,
  5888. profile: filamentData.profile,
  5889. color: filamentData.colorHex || '',
  5890. location: getAmsLabel(ams.id, ams.tray.length),
  5891. },
  5892. }),
  5893. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5894. isAssigned: !!assignment || isBambuLabSpool(tray),
  5895. };
  5896. })()}
  5897. configureSlot={{
  5898. enabled: hasPermission('printers:control'),
  5899. onConfigure: () => setConfigureSlotModal({
  5900. amsId: ams.id,
  5901. trayId: htSlotId,
  5902. trayCount: ams.tray.length,
  5903. trayType: tray?.tray_type || undefined,
  5904. trayColor: tray?.tray_color || undefined,
  5905. traySubBrands: tray?.tray_sub_brands || undefined,
  5906. trayInfoIdx: tray?.tray_info_idx || undefined,
  5907. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5908. caliIdx: tray?.cali_idx,
  5909. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5910. }),
  5911. }}
  5912. >
  5913. {slotVisual}
  5914. </FilamentHoverCard>
  5915. ) : (
  5916. <EmptySlotHoverCard
  5917. kind={emptyKind ?? undefined}
  5918. actions={renderAmsSlotActions({
  5919. amsId: ams.id,
  5920. slotId: htSlotId,
  5921. loadTrayId: ams.id * 4 + htSlotId,
  5922. isRefreshing: isHtRefreshing,
  5923. })}
  5924. configureSlot={{
  5925. enabled: hasPermission('printers:control'),
  5926. onConfigure: () => setConfigureSlotModal({
  5927. amsId: ams.id,
  5928. trayId: htSlotId,
  5929. trayCount: ams.tray.length,
  5930. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5931. }),
  5932. }}
  5933. onAssignSpool={() => setAssignSpoolModal({
  5934. printerId: printer.id,
  5935. amsId: ams.id,
  5936. trayId: htSlotId,
  5937. trayInfo: {
  5938. type: '',
  5939. material: undefined,
  5940. profile: '',
  5941. color: '',
  5942. location: getAmsLabel(ams.id, ams.tray.length),
  5943. },
  5944. })}
  5945. >
  5946. {slotVisual}
  5947. </EmptySlotHoverCard>
  5948. )}
  5949. </div>
  5950. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5951. {(ams.humidity != null || ams.temp != null) && (
  5952. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5953. {ams.temp != null && (
  5954. <TemperatureIndicator
  5955. temp={ams.temp}
  5956. goodThreshold={amsThresholds?.tempGood}
  5957. fairThreshold={amsThresholds?.tempFair}
  5958. onClick={() => setAmsHistoryModal({
  5959. amsId: ams.id,
  5960. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5961. mode: 'temperature',
  5962. })}
  5963. compact
  5964. />
  5965. )}
  5966. {ams.humidity != null && (
  5967. <HumidityIndicator
  5968. humidity={ams.humidity}
  5969. goodThreshold={amsThresholds?.humidityGood}
  5970. fairThreshold={amsThresholds?.humidityFair}
  5971. onClick={() => setAmsHistoryModal({
  5972. amsId: ams.id,
  5973. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5974. mode: 'humidity',
  5975. })}
  5976. compact
  5977. />
  5978. )}
  5979. </div>
  5980. )}
  5981. </div>
  5982. </div>
  5983. );
  5984. })}
  5985. {/* External spool(s) - grouped in one card like regular AMS */}
  5986. {status.vt_tray.length > 0 && showExternalSpool && (
  5987. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5988. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5989. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  5990. </div>
  5991. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  5992. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5993. const extTrayId = extTray.id ?? 254;
  5994. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5995. // generically — use active_extruder to determine L vs R:
  5996. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5997. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5998. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5999. (extTrayId === 255 && status.active_extruder === 0)
  6000. : effectiveTrayNow === extTrayId;
  6001. const slotTrayId = extTrayId - 254; // 0 or 1
  6002. const extLabel = isDualNozzle
  6003. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6004. : '';
  6005. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6006. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6007. // Only trusted while it still describes what the printer reports in the
  6008. // slot: the row survives a spool swap, and the display chain below puts
  6009. // it ahead of the live filament id (see slotPresetDescribesTray).
  6010. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx)
  6011. ? extSlotPreset?.preset_name
  6012. : undefined;
  6013. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6014. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6015. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6016. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6017. const extInventoryFill = (() => {
  6018. const sp = extInventoryAssignment?.spool;
  6019. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6020. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6021. }
  6022. return null;
  6023. })();
  6024. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6025. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6026. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6027. ? null : extInventoryFill;
  6028. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6029. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6030. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6031. : undefined;
  6032. const extSlotSpoolForFill = extSlotAssignmentForFill
  6033. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6034. : undefined;
  6035. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6036. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6037. : null;
  6038. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6039. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6040. : extResolvedInventoryFill !== null ? 'inventory' as const
  6041. : extHasFillLevel ? 'ams' as const
  6042. : undefined;
  6043. const extFilamentData = {
  6044. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6045. 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',
  6046. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6047. colorHex: extTray.tray_color || null,
  6048. kFactor: formatKValue(extTray.k),
  6049. fillLevel: extEffectiveFill,
  6050. trayUuid: extTray.tray_uuid || null,
  6051. tagUid: extTray.tag_uid || null,
  6052. fillSource: extFillSource,
  6053. };
  6054. const isEmpty = !extTray.tray_type;
  6055. const emptyKind = getEmptySlotKind(extTray);
  6056. const extSlotContent = (
  6057. <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' : ''}`}>
  6058. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6059. the separate Ext-L/Ext-R caption that made the row taller than
  6060. regular AMS slots), 1-based slot number on single-nozzle. */}
  6061. <FilamentSlotCircle
  6062. trayColor={extTray.tray_color}
  6063. trayType={extTray.tray_type}
  6064. isEmpty={isEmpty}
  6065. emptyKind={emptyKind}
  6066. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6067. />
  6068. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6069. {extTray.tray_type || t('ams.slotEmpty')}
  6070. </div>
  6071. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6072. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6073. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6074. <div
  6075. className="h-full rounded-full transition-all"
  6076. style={{
  6077. width: `${extEffectiveFill}%`,
  6078. backgroundColor: getFillBarColor(extEffectiveFill),
  6079. }}
  6080. />
  6081. )}
  6082. </div>
  6083. </div>
  6084. );
  6085. return (
  6086. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6087. {!isEmpty ? (
  6088. <FilamentHoverCard
  6089. data={extFilamentData}
  6090. actions={renderAmsSlotActions({
  6091. amsId: 255,
  6092. slotId: slotTrayId,
  6093. loadTrayId: extTrayId,
  6094. includeRfid: false,
  6095. })}
  6096. spoolman={{
  6097. enabled: spoolmanEnabled,
  6098. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6099. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6100. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6101. spoolmanUrl,
  6102. syncMode: spoolmanSyncMode,
  6103. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6104. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6105. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6106. setLinkSpoolModal({
  6107. tagUid: extFilamentData.tagUid || linkTag,
  6108. trayUuid: extFilamentData.trayUuid || '',
  6109. printerId: printer.id,
  6110. amsId: 255,
  6111. trayId: slotTrayId,
  6112. });
  6113. } : undefined,
  6114. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6115. }}
  6116. inventory={(() => {
  6117. if (spoolmanEnabled) {
  6118. if (spoolmanLoading) return undefined;
  6119. const slotAssignment = extSlotAssignmentForFill;
  6120. const spoolmanSpool = extSlotSpoolForFill;
  6121. return {
  6122. assignedSpool: spoolmanSpool ? {
  6123. id: spoolmanSpool.id,
  6124. material: spoolmanSpool.material,
  6125. subtype: spoolmanSpool.subtype,
  6126. brand: spoolmanSpool.brand ?? null,
  6127. color_name: spoolmanSpool.color_name ?? null,
  6128. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6129. // The spool's own swatch (#2967). Spoolman carries the
  6130. // extra stops but has no effect field at all, so those
  6131. // rolls gradient and never shimmer.
  6132. rgba: spoolmanSpool.rgba ?? null,
  6133. extra_colors: spoolmanSpool.extra_colors ?? null,
  6134. effect_type: spoolmanSpool.effect_type ?? null,
  6135. remainingWeightGrams: spoolmanSpool.label_weight
  6136. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6137. : undefined,
  6138. } : null,
  6139. onAssignSpool: () => setAssignSpoolModal({
  6140. printerId: printer.id,
  6141. amsId: 255,
  6142. trayId: slotTrayId,
  6143. trayInfo: {
  6144. type: extTray.tray_type || extFilamentData.profile,
  6145. material: extTray.tray_type ?? undefined,
  6146. profile: extFilamentData.profile,
  6147. color: extFilamentData.colorHex || '',
  6148. location: extLabel || t('printers.external'),
  6149. },
  6150. }),
  6151. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6152. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6153. };
  6154. }
  6155. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6156. return {
  6157. assignedSpool: assignment?.spool ? {
  6158. id: assignment.spool.id,
  6159. material: assignment.spool.material,
  6160. subtype: assignment.spool.subtype,
  6161. brand: assignment.spool.brand,
  6162. color_name: assignment.spool.color_name,
  6163. // The spool's own swatch (#2967).
  6164. rgba: assignment.spool.rgba ?? null,
  6165. extra_colors: assignment.spool.extra_colors ?? null,
  6166. effect_type: assignment.spool.effect_type ?? null,
  6167. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6168. } : null,
  6169. onAssignSpool: () => setAssignSpoolModal({
  6170. printerId: printer.id,
  6171. amsId: 255,
  6172. trayId: slotTrayId,
  6173. trayInfo: {
  6174. type: extTray.tray_type || extFilamentData.profile,
  6175. material: extTray.tray_type ?? undefined,
  6176. profile: extFilamentData.profile,
  6177. color: extFilamentData.colorHex || '',
  6178. location: extLabel || t('printers.external'),
  6179. },
  6180. }),
  6181. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6182. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6183. };
  6184. })()}
  6185. configureSlot={{
  6186. enabled: hasPermission('printers:control'),
  6187. onConfigure: () => setConfigureSlotModal({
  6188. amsId: 255,
  6189. trayId: slotTrayId,
  6190. trayCount: 1,
  6191. trayType: extTray.tray_type || undefined,
  6192. trayColor: extTray.tray_color || undefined,
  6193. traySubBrands: extTray.tray_sub_brands || undefined,
  6194. trayInfoIdx: extTray.tray_info_idx || undefined,
  6195. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6196. caliIdx: extTray.cali_idx,
  6197. savedPresetId: slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx) ? extSlotPreset?.preset_id : undefined,
  6198. }),
  6199. }}
  6200. >
  6201. {extSlotContent}
  6202. </FilamentHoverCard>
  6203. ) : (
  6204. <EmptySlotHoverCard
  6205. kind={emptyKind ?? undefined}
  6206. actions={renderAmsSlotActions({
  6207. amsId: 255,
  6208. slotId: slotTrayId,
  6209. loadTrayId: extTrayId,
  6210. includeRfid: false,
  6211. })}
  6212. configureSlot={{
  6213. enabled: hasPermission('printers:control'),
  6214. onConfigure: () => setConfigureSlotModal({
  6215. amsId: 255,
  6216. trayId: slotTrayId,
  6217. trayCount: 1,
  6218. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6219. }),
  6220. }}
  6221. onAssignSpool={() => setAssignSpoolModal({
  6222. printerId: printer.id,
  6223. amsId: 255,
  6224. trayId: slotTrayId,
  6225. trayInfo: {
  6226. type: '',
  6227. material: undefined,
  6228. profile: '',
  6229. color: '',
  6230. location: `External Slot ${slotTrayId + 1}`,
  6231. },
  6232. })}
  6233. >
  6234. {extSlotContent}
  6235. </EmptySlotHoverCard>
  6236. )}
  6237. </div>
  6238. );
  6239. })}
  6240. </div>
  6241. </div>
  6242. )}
  6243. </div>
  6244. </div>
  6245. );
  6246. })()}
  6247. </>
  6248. )}
  6249. {/* Powered-down printer with a dirty plate: the status block above renders
  6250. nothing without a live connection, so the plate-clear control gets its own
  6251. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6252. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6253. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6254. expandedClearPlateButton
  6255. )}
  6256. {/* Bottom block (power row + action bar). Wrapped together so the
  6257. power row hugs the action bar at the card bottom instead of
  6258. floating up when there's less filament content above. */}
  6259. {viewMode === 'expanded' && (
  6260. <div className="mt-auto">
  6261. {smartPlug && (
  6262. <div className="pt-3">
  6263. <div className="flex items-center gap-2 mb-2">
  6264. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6265. {t('printers.power', 'Power')}
  6266. </span>
  6267. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6268. </div>
  6269. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6270. {/* Plug name + current power */}
  6271. <div className="flex items-center gap-2 min-w-0 pl-1">
  6272. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6273. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6274. <span
  6275. 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"
  6276. title={t('smartPlugs.power')}
  6277. >
  6278. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6279. </span>
  6280. </div>
  6281. {/* Spacer */}
  6282. <div className="flex-1" />
  6283. <div className="flex items-center gap-2">
  6284. {/* Auto-off */}
  6285. <button
  6286. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6287. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6288. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6289. 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 ${
  6290. !hasPermission('smart_plugs:control')
  6291. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6292. : smartPlug.auto_off || smartPlug.auto_off_executed
  6293. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6294. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6295. }`}
  6296. >
  6297. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6298. </button>
  6299. <button
  6300. onClick={() => {
  6301. if (plugStatus?.state === 'ON') {
  6302. setShowPowerOffConfirm(true);
  6303. } else {
  6304. setShowPowerOnConfirm(true);
  6305. }
  6306. }}
  6307. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6308. 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 ${
  6309. !hasPermission('smart_plugs:control')
  6310. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6311. : plugStatus?.state === 'ON'
  6312. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6313. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6314. }`}
  6315. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6316. >
  6317. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6318. </button>
  6319. </div>
  6320. </div>
  6321. {/* HA entity buttons row */}
  6322. {scriptPlugs && scriptPlugs.length > 0 && (
  6323. <div className="flex items-center gap-2 mt-2">
  6324. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6325. <span className="text-xs text-bambu-gray">HA:</span>
  6326. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6327. <div className="flex flex-wrap gap-1">
  6328. {scriptPlugs.map(script => {
  6329. const isScript = script.ha_entity_id?.startsWith('script.');
  6330. return (
  6331. <button
  6332. key={script.id}
  6333. onClick={() => {
  6334. if (isScript) {
  6335. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6336. } else {
  6337. setHaToggleConfirm(script);
  6338. }
  6339. }}
  6340. disabled={runScriptMutation.isPending}
  6341. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6342. 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"
  6343. >
  6344. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6345. {script.name}
  6346. </button>
  6347. );
  6348. })}
  6349. </div>
  6350. </div>
  6351. )}
  6352. </div>
  6353. )}
  6354. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6355. a printer can have an enclosure door contact without having a plug,
  6356. and nesting it there would hide the row on exactly those setups. */}
  6357. <PrinterHASensorRow printerId={printer.id} />
  6358. {/* Connection Info & Actions */}
  6359. <div className="pt-4">
  6360. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6361. <div className="flex items-center justify-between gap-2">
  6362. {printerActionsMenu}
  6363. <div className="flex items-center justify-end gap-2 flex-wrap">
  6364. {/* Camera split button: the icon opens whichever view was used
  6365. last, the caret picks between the two and remembers it.
  6366. Replaces the old Settings > General > Camera switch, which
  6367. made choosing between an overlay and a window a trip to
  6368. another page for something you decide per camera. */}
  6369. <div className="flex items-center flex-shrink-0">
  6370. <Button
  6371. variant="secondary"
  6372. size="sm"
  6373. onClick={() => openCameraIn(cameraViewMode)}
  6374. disabled={!status?.connected || !hasPermission('camera:view')}
  6375. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6376. className={`${footerIconButtonClass} !rounded-r-none`}
  6377. >
  6378. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6379. </Button>
  6380. <Button
  6381. variant="secondary"
  6382. size="sm"
  6383. onClick={(e) => {
  6384. // No open/close toggle: the menu's own outside-mousedown
  6385. // handler has already dismissed it by the time this lands.
  6386. const rect = e.currentTarget.getBoundingClientRect();
  6387. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6388. }}
  6389. disabled={!status?.connected || !hasPermission('camera:view')}
  6390. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6391. aria-label={t('settings.cameraViewMode')}
  6392. // Not footerIconButtonClass plus an override: both widths
  6393. // would carry !important and the stylesheet's own order,
  6394. // not this one, would decide which won.
  6395. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6396. >
  6397. <ChevronDown className="w-3 h-3" />
  6398. </Button>
  6399. </div>
  6400. {cameraMenuAnchor && (
  6401. <ContextMenu
  6402. x={cameraMenuAnchor.x}
  6403. y={cameraMenuAnchor.y}
  6404. items={cameraViewModeMenuItems}
  6405. onClose={() => setCameraMenuAnchor(null)}
  6406. />
  6407. )}
  6408. <Button
  6409. variant="secondary"
  6410. size="sm"
  6411. onClick={() => setShowFileManager(true)}
  6412. disabled={!hasPermission('printers:files')}
  6413. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6414. className={footerIconButtonClass}
  6415. >
  6416. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6417. </Button>
  6418. {/* Shown whatever the printer is doing (#2849): this uploads a
  6419. file and queues it, which a busy or offline printer is no
  6420. reason to refuse -- it only means the item waits. Hiding it
  6421. while the drop zone accepted the same file would have left
  6422. the two routes into this flow disagreeing. */}
  6423. <Button
  6424. size="sm"
  6425. onClick={() => setShowUploadForPrint(true)}
  6426. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6427. title={
  6428. !hasPermission('library:upload')
  6429. ? t('fileManager.noPermissionUpload')
  6430. : !hasPermission('queue:create')
  6431. ? t('fileManager.noPermissionAddToQueue')
  6432. : t('common.print')
  6433. }
  6434. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6435. >
  6436. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6437. {t('common.print')}
  6438. </Button>
  6439. </div>
  6440. </div>
  6441. </div>
  6442. </div>
  6443. )}
  6444. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6445. card's horizontal padding instead of running full-bleed into the
  6446. rounded bottom edge. */}
  6447. <ScheduledDryingBanner
  6448. printerId={printer.id}
  6449. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6450. timeFormat={timeFormat}
  6451. />
  6452. </CardContent>
  6453. {/* File Manager Modal */}
  6454. {showFileManager && (
  6455. <FileManagerModal
  6456. printerId={printer.id}
  6457. printerName={printer.name}
  6458. onClose={() => setShowFileManager(false)}
  6459. />
  6460. )}
  6461. {/* Upload for Print Modal */}
  6462. {showUploadForPrint && (
  6463. <FileUploadModal
  6464. folderId={null}
  6465. onClose={() => setShowUploadForPrint(false)}
  6466. onUploadComplete={() => {}}
  6467. autoUpload
  6468. accept=".gcode,.3mf"
  6469. validateFile={(file) => {
  6470. const lower = file.name.toLowerCase();
  6471. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6472. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6473. }
  6474. }}
  6475. onFileUploaded={(uploadedFile) => {
  6476. // Check printer compatibility if sliced_for_model is available in metadata
  6477. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6478. const printerModel = mapModelCode(printer.model);
  6479. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6480. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6481. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6482. }
  6483. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6484. }}
  6485. />
  6486. )}
  6487. {/* Print Modal (after upload) */}
  6488. {printAfterUpload && (
  6489. <PrintModal
  6490. mode="create"
  6491. libraryFileId={printAfterUpload.id}
  6492. archiveName={printAfterUpload.filename}
  6493. initialSelectedPrinterIds={[printer.id]}
  6494. onClose={() => setPrintAfterUpload(null)}
  6495. onSuccess={() => setPrintAfterUpload(null)}
  6496. cleanupLibraryAfterDispatch
  6497. />
  6498. )}
  6499. {/* MQTT Debug Modal */}
  6500. {showMQTTDebug && (
  6501. <MQTTDebugModal
  6502. printerId={printer.id}
  6503. printerName={printer.name}
  6504. onClose={() => setShowMQTTDebug(false)}
  6505. />
  6506. )}
  6507. {showDiagnostic && (
  6508. <ConnectionDiagnosticModal
  6509. printerId={printer.id}
  6510. printerName={printer.name}
  6511. onClose={() => setShowDiagnostic(false)}
  6512. />
  6513. )}
  6514. {showPrinterInfo && (
  6515. <PrinterInfoModal
  6516. printer={printer}
  6517. status={status}
  6518. totalPrintHours={maintenanceInfo?.total_print_hours}
  6519. onClose={closePrinterInfo}
  6520. />
  6521. )}
  6522. {/* Plate Check Result Modal */}
  6523. {plateCheckResult && (
  6524. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6525. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6526. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6527. <div className="flex items-center gap-2">
  6528. {plateCheckResult.needs_calibration ? (
  6529. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6530. ) : plateCheckResult.is_empty ? (
  6531. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6532. ) : (
  6533. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6534. )}
  6535. <h2 className="text-lg font-semibold text-white">
  6536. Build Plate Check
  6537. </h2>
  6538. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6539. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6540. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6541. </span>
  6542. )}
  6543. </div>
  6544. <button
  6545. onClick={() => closePlateCheckModal()}
  6546. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6547. >
  6548. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6549. </button>
  6550. </div>
  6551. <div className="p-4 space-y-4">
  6552. {plateCheckResult.needs_calibration ? (
  6553. <>
  6554. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6555. <p className="font-medium text-blue-700 dark:text-blue-400">
  6556. {t('printers.plateDetection.calibrationRequired')}
  6557. </p>
  6558. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6559. </div>
  6560. <div className="text-sm text-bambu-gray space-y-2">
  6561. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6562. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6563. </div>
  6564. </>
  6565. ) : (
  6566. <>
  6567. <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'}`}>
  6568. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6569. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6570. </p>
  6571. <p className="text-sm text-bambu-gray mt-1">
  6572. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6573. </p>
  6574. </div>
  6575. {plateCheckResult.debug_image_url && (
  6576. <div>
  6577. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6578. <img
  6579. src={plateCheckResult.debug_image_url}
  6580. alt={t('printers.plateDetection.analysisPreview')}
  6581. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6582. />
  6583. <p className="text-xs text-bambu-gray mt-2">
  6584. {t('printers.plateDetection.analysisLegend')}
  6585. </p>
  6586. </div>
  6587. )}
  6588. <p className="text-xs text-bambu-gray">
  6589. {plateCheckResult.message}
  6590. </p>
  6591. </>
  6592. )}
  6593. {/* Saved References Grid */}
  6594. {plateReferences && plateReferences.references.length > 0 && (
  6595. <div className="mt-4">
  6596. <div className="flex items-center gap-2 mb-2">
  6597. <p className="text-sm font-medium text-white shrink-0">
  6598. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6599. </p>
  6600. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6601. </div>
  6602. <div className="grid grid-cols-5 gap-2">
  6603. {plateReferences.references.map((ref) => (
  6604. <div key={ref.index} className="relative group">
  6605. <img
  6606. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6607. alt={ref.label || `Reference ${ref.index + 1}`}
  6608. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6609. />
  6610. {/* Delete button */}
  6611. <button
  6612. onClick={() => handleDeleteRef(ref.index)}
  6613. 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"
  6614. title={t('printers.plateDetection.deleteReference')}
  6615. >
  6616. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6617. </button>
  6618. {/* Label */}
  6619. {editingRefLabel?.index === ref.index ? (
  6620. <input
  6621. type="text"
  6622. value={editingRefLabel.label}
  6623. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6624. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6625. onKeyDown={(e) => {
  6626. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6627. if (e.key === 'Escape') setEditingRefLabel(null);
  6628. }}
  6629. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6630. autoFocus
  6631. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6632. />
  6633. ) : (
  6634. <p
  6635. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6636. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6637. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6638. >
  6639. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6640. </p>
  6641. )}
  6642. {/* Timestamp */}
  6643. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6644. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6645. </p>
  6646. </div>
  6647. ))}
  6648. </div>
  6649. </div>
  6650. )}
  6651. {/* ROI Editor */}
  6652. {!plateCheckResult.needs_calibration && (
  6653. <div className="mt-4">
  6654. <div className="flex items-center justify-between mb-2">
  6655. <div className="flex min-w-0 flex-1 items-center gap-2">
  6656. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6657. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6658. </div>
  6659. {!editingRoi ? (
  6660. <Button
  6661. variant="ghost"
  6662. size="sm"
  6663. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6664. >
  6665. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6666. {t('common.edit')}
  6667. </Button>
  6668. ) : (
  6669. <div className="flex gap-1">
  6670. <Button
  6671. variant="ghost"
  6672. size="sm"
  6673. onClick={() => setEditingRoi(null)}
  6674. disabled={isSavingRoi}
  6675. >
  6676. {t('common.cancel')}
  6677. </Button>
  6678. <Button
  6679. size="sm"
  6680. onClick={handleSaveRoi}
  6681. disabled={isSavingRoi}
  6682. >
  6683. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6684. </Button>
  6685. </div>
  6686. )}
  6687. </div>
  6688. {editingRoi ? (
  6689. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6690. <div className="grid grid-cols-2 gap-3">
  6691. <div>
  6692. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6693. <input
  6694. type="range"
  6695. min="0"
  6696. max="0.9"
  6697. step="0.01"
  6698. value={editingRoi.x}
  6699. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6700. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6701. />
  6702. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6703. </div>
  6704. <div>
  6705. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6706. <input
  6707. type="range"
  6708. min="0"
  6709. max="0.9"
  6710. step="0.01"
  6711. value={editingRoi.y}
  6712. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6713. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6714. />
  6715. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6716. </div>
  6717. <div>
  6718. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6719. <input
  6720. type="range"
  6721. min="0.1"
  6722. max="1"
  6723. step="0.01"
  6724. value={editingRoi.w}
  6725. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6726. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6727. />
  6728. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6729. </div>
  6730. <div>
  6731. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6732. <input
  6733. type="range"
  6734. min="0.1"
  6735. max="1"
  6736. step="0.01"
  6737. value={editingRoi.h}
  6738. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6739. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6740. />
  6741. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6742. </div>
  6743. </div>
  6744. <p className="text-xs text-bambu-gray">
  6745. {t('printers.roi.instruction')}
  6746. </p>
  6747. </div>
  6748. ) : (
  6749. <p className="text-xs text-bambu-gray">
  6750. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6751. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6752. </p>
  6753. )}
  6754. </div>
  6755. )}
  6756. </div>
  6757. <div className="flex justify-end gap-2 p-4">
  6758. {plateCheckResult.needs_calibration ? (
  6759. <>
  6760. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6761. {t('common.cancel')}
  6762. </Button>
  6763. <Button
  6764. onClick={() => handleCalibratePlate()}
  6765. disabled={isCalibrating}
  6766. >
  6767. {isCalibrating ? (
  6768. <>
  6769. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6770. Calibrating...
  6771. </>
  6772. ) : (
  6773. 'Calibrate Empty Plate'
  6774. )}
  6775. </Button>
  6776. </>
  6777. ) : (
  6778. <>
  6779. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6780. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6781. </Button>
  6782. <Button onClick={() => closePlateCheckModal()}>
  6783. Close
  6784. </Button>
  6785. </>
  6786. )}
  6787. </div>
  6788. </div>
  6789. </div>
  6790. )}
  6791. {/* Power On Confirmation */}
  6792. {showPowerOnConfirm && smartPlug && (
  6793. <ConfirmModal
  6794. title={t('printers.confirm.powerOnTitle')}
  6795. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6796. confirmText={t('printers.confirm.powerOnButton')}
  6797. variant="default"
  6798. onConfirm={() => {
  6799. powerControlMutation.mutate('on');
  6800. setShowPowerOnConfirm(false);
  6801. }}
  6802. onCancel={() => setShowPowerOnConfirm(false)}
  6803. />
  6804. )}
  6805. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6806. disconnects MQTT, which stops progress tracking + completion
  6807. notifications for the in-flight job. Idle / FINISH / FAILED states
  6808. skip this dialog and toggle directly. */}
  6809. {confirmMaintenanceEnter && (
  6810. <ConfirmModal
  6811. title={t('printers.maintenance.confirmMidPrintTitle')}
  6812. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6813. confirmText={t('printers.maintenance.menuEnter')}
  6814. variant="danger"
  6815. onConfirm={() => {
  6816. maintenanceMutation.mutate(false);
  6817. setConfirmMaintenanceEnter(false);
  6818. }}
  6819. onCancel={() => setConfirmMaintenanceEnter(false)}
  6820. />
  6821. )}
  6822. {/* Power Off Confirmation */}
  6823. {showPowerOffConfirm && smartPlug && (
  6824. <ConfirmModal
  6825. title={t('printers.confirm.powerOffTitle')}
  6826. message={
  6827. status?.state === 'RUNNING'
  6828. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6829. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6830. }
  6831. confirmText={t('printers.confirm.powerOffButton')}
  6832. variant="danger"
  6833. onConfirm={() => {
  6834. powerControlMutation.mutate('off');
  6835. setShowPowerOffConfirm(false);
  6836. }}
  6837. onCancel={() => setShowPowerOffConfirm(false)}
  6838. />
  6839. )}
  6840. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6841. {haToggleConfirm && (
  6842. <ConfirmModal
  6843. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6844. message={
  6845. status?.state === 'RUNNING'
  6846. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6847. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6848. }
  6849. confirmText={t('printers.confirm.haToggleButton')}
  6850. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6851. onConfirm={() => {
  6852. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6853. setHaToggleConfirm(null);
  6854. }}
  6855. onCancel={() => setHaToggleConfirm(null)}
  6856. />
  6857. )}
  6858. {/* Stop Print Confirmation */}
  6859. {showStopConfirm && (
  6860. <ConfirmModal
  6861. title={t('printers.confirm.stopTitle')}
  6862. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6863. confirmText={t('printers.confirm.stopButton')}
  6864. variant="danger"
  6865. onConfirm={() => {
  6866. stopPrintMutation.mutate();
  6867. setShowStopConfirm(false);
  6868. }}
  6869. onCancel={() => setShowStopConfirm(false)}
  6870. />
  6871. )}
  6872. {/* Pause Print Confirmation */}
  6873. {showPauseConfirm && (
  6874. <ConfirmModal
  6875. title={t('printers.confirm.pauseTitle')}
  6876. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6877. confirmText={t('printers.confirm.pauseButton')}
  6878. variant="default"
  6879. onConfirm={() => {
  6880. pausePrintMutation.mutate();
  6881. setShowPauseConfirm(false);
  6882. }}
  6883. onCancel={() => setShowPauseConfirm(false)}
  6884. />
  6885. )}
  6886. {/* Resume Print Confirmation */}
  6887. {showResumeConfirm && (
  6888. <ConfirmModal
  6889. title={t('printers.confirm.resumeTitle')}
  6890. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6891. confirmText={t('printers.confirm.resumeButton')}
  6892. variant="default"
  6893. onConfirm={() => {
  6894. resumePrintMutation.mutate();
  6895. setShowResumeConfirm(false);
  6896. }}
  6897. onCancel={() => setShowResumeConfirm(false)}
  6898. />
  6899. )}
  6900. {/* Skip Objects Modal */}
  6901. <SkipObjectsModal
  6902. printerId={printer.id}
  6903. isOpen={showSkipObjectsModal}
  6904. onClose={() => setShowSkipObjectsModal(false)}
  6905. />
  6906. {/* HMS Error Modal */}
  6907. {showHMSModal && (
  6908. <HMSErrorModal
  6909. printerName={printer.name}
  6910. errors={status?.hms_errors || []}
  6911. onClose={() => setShowHMSModal(false)}
  6912. printerId={printer.id}
  6913. hasPermission={hasPermission}
  6914. runoutGuidance={runoutGuidance}
  6915. />
  6916. )}
  6917. {/* AI failure detection modal (#1546) */}
  6918. {showAiModal && (
  6919. <AiDetectionModal
  6920. printerName={printer.name}
  6921. detection={aiDetection}
  6922. lastError={aiLastError}
  6923. onClose={() => setShowAiModal(false)}
  6924. />
  6925. )}
  6926. {/* AMS Filament Backup status / control modal (#1762) */}
  6927. {amsBackupModalOpen && status && (
  6928. <AmsBackupModal
  6929. isOpen={amsBackupModalOpen}
  6930. state={status.ams_filament_backup}
  6931. amsUnits={status.ams}
  6932. amsExtruderMap={status.ams_extruder_map}
  6933. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6934. canToggle={hasPermission('printers:control')}
  6935. pending={setAmsBackupMutation.isPending}
  6936. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6937. onClose={() => setAmsBackupModalOpen(false)}
  6938. />
  6939. )}
  6940. {/* AMS History Modal */}
  6941. {amsHistoryModal && (
  6942. <AMSHistoryModal
  6943. isOpen={!!amsHistoryModal}
  6944. onClose={() => setAmsHistoryModal(null)}
  6945. printerId={printer.id}
  6946. printerName={printer.name}
  6947. amsId={amsHistoryModal.amsId}
  6948. amsLabel={amsHistoryModal.amsLabel}
  6949. initialMode={amsHistoryModal.mode}
  6950. thresholds={amsThresholds}
  6951. />
  6952. )}
  6953. {/* Heater History Modal (nozzle / bed / chamber) */}
  6954. {heaterHistoryModal && (
  6955. <HeaterHistoryModal
  6956. isOpen={!!heaterHistoryModal}
  6957. onClose={() => setHeaterHistoryModal(null)}
  6958. printerId={printer.id}
  6959. printerName={printer.name}
  6960. initialKind={heaterHistoryModal.initialKind}
  6961. availableKinds={heaterHistoryModal.availableKinds}
  6962. />
  6963. )}
  6964. {/* Link Spool Modal */}
  6965. {linkSpoolModal && (
  6966. <LinkSpoolModal
  6967. isOpen={!!linkSpoolModal}
  6968. onClose={() => setLinkSpoolModal(null)}
  6969. tagUid={linkSpoolModal.tagUid}
  6970. trayUuid={linkSpoolModal.trayUuid}
  6971. printerId={linkSpoolModal.printerId}
  6972. amsId={linkSpoolModal.amsId}
  6973. trayId={linkSpoolModal.trayId}
  6974. />
  6975. )}
  6976. {/* Assign Spool Modal */}
  6977. {assignSpoolModal && (
  6978. <AssignSpoolModal
  6979. isOpen={!!assignSpoolModal}
  6980. onClose={() => setAssignSpoolModal(null)}
  6981. printerId={assignSpoolModal.printerId}
  6982. amsId={assignSpoolModal.amsId}
  6983. trayId={assignSpoolModal.trayId}
  6984. trayInfo={assignSpoolModal.trayInfo}
  6985. spoolmanEnabled={!!spoolmanEnabled}
  6986. />
  6987. )}
  6988. {/* Configure AMS Slot Modal */}
  6989. {configureSlotModal && (
  6990. <ConfigureAmsSlotModal
  6991. isOpen={!!configureSlotModal}
  6992. onClose={() => setConfigureSlotModal(null)}
  6993. printerId={printer.id}
  6994. slotInfo={configureSlotModal}
  6995. printerModel={mapModelCode(printer.model) || undefined}
  6996. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6997. onSuccess={() => {
  6998. // Refresh slot presets to show updated profile name
  6999. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7000. // Printer status will update automatically via WebSocket when AMS data changes
  7001. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7002. }}
  7003. />
  7004. )}
  7005. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7006. {feedDirectionRequest && (
  7007. <FeedDirectionModal
  7008. slotLabel={feedDirectionRequest.slotLabel}
  7009. amsId={feedDirectionRequest.amsId}
  7010. slotId={feedDirectionRequest.slotId}
  7011. extruderSlots={status?.extruder_slots ?? {}}
  7012. isLoading={loadAmsTrayMutation.isPending}
  7013. onConfirm={(extruderId) =>
  7014. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7015. }
  7016. onCancel={() => setFeedDirectionRequest(null)}
  7017. />
  7018. )}
  7019. {/* Edit Printer Modal */}
  7020. {showEditModal && (
  7021. <EditPrinterModal
  7022. printer={printer}
  7023. onClose={() => setShowEditModal(false)}
  7024. />
  7025. )}
  7026. {/* Firmware Update Modal */}
  7027. {showFirmwareModal && firmwareInfo && (
  7028. <FirmwareUpdateModal
  7029. printer={printer}
  7030. firmwareInfo={firmwareInfo}
  7031. onClose={() => setShowFirmwareModal(false)}
  7032. />
  7033. )}
  7034. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7035. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7036. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7037. const sliderMin = 35;
  7038. const sliderMax = maxTemp + 10;
  7039. return (
  7040. <>
  7041. {/* Backdrop */}
  7042. <div
  7043. className="fixed inset-0 z-[100]"
  7044. data-testid="drying-popover-backdrop"
  7045. onMouseDown={() => {
  7046. // The click that dismisses the native datetime picker lands
  7047. // here; it must not close the popover. The input is still
  7048. // focused at mousedown, so remember that and swallow the
  7049. // matching click.
  7050. dryingBackdropSkipCloseRef.current =
  7051. dryingAtTimeInputRef.current !== null &&
  7052. document.activeElement === dryingAtTimeInputRef.current;
  7053. }}
  7054. onClick={() => {
  7055. if (dryingBackdropSkipCloseRef.current) {
  7056. dryingBackdropSkipCloseRef.current = false;
  7057. return;
  7058. }
  7059. setDryingPopoverAmsId(null);
  7060. }}
  7061. />
  7062. {/* An 'above' popover is anchored by its bottom edge (CSS
  7063. bottom) so late-appearing content grows it upward, staying on
  7064. screen and glued to the trigger. maxHeight caps to the space
  7065. on the anchored side; when the viewport is too short the body
  7066. scrolls and the footer stays pinned. dvh so iOS Safari's
  7067. bottom toolbar doesn't clip the footer. */}
  7068. <div
  7069. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7070. style={{
  7071. left: dryingPopoverPos.left,
  7072. ...(dryingPopoverPos.placement === 'above'
  7073. ? {
  7074. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7075. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7076. }
  7077. : {
  7078. top: dryingPopoverPos.top,
  7079. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7080. }),
  7081. }}
  7082. onClick={e => e.stopPropagation()}
  7083. >
  7084. {/* Header */}
  7085. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7086. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7087. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7088. </div>
  7089. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7090. {/* Body */}
  7091. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7092. {/* Filament type select */}
  7093. <div>
  7094. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7095. <ToolbarDropdown
  7096. value={dryingFilament}
  7097. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7098. onChange={fil => {
  7099. setDryingFilament(fil);
  7100. const preset = dryingPresets[fil];
  7101. if (preset) {
  7102. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7103. setDryingTemp(preset[key]);
  7104. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7105. }
  7106. }}
  7107. fullWidth
  7108. />
  7109. </div>
  7110. {/* Temperature */}
  7111. <div>
  7112. <div className="flex items-center justify-between mb-1">
  7113. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7114. <div className="flex items-center gap-1">
  7115. <NumberInput
  7116. min={45}
  7117. max={maxTemp}
  7118. value={dryingTemp}
  7119. onChange={setDryingTemp}
  7120. fallback={45}
  7121. 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"
  7122. />
  7123. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7124. </div>
  7125. </div>
  7126. <input
  7127. type="range"
  7128. min={sliderMin}
  7129. max={sliderMax}
  7130. value={dryingTemp}
  7131. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7132. className="w-full h-1 accent-bambu-green cursor-pointer"
  7133. />
  7134. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7135. <span>45°C</span>
  7136. <span>{maxTemp}°C</span>
  7137. </div>
  7138. </div>
  7139. {/* Duration */}
  7140. <div>
  7141. <div className="flex items-center justify-between mb-1">
  7142. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7143. <div className="flex items-center gap-1">
  7144. <NumberInput
  7145. min={1}
  7146. max={24}
  7147. value={dryingDuration}
  7148. onChange={setDryingDuration}
  7149. fallback={1}
  7150. 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"
  7151. />
  7152. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7153. </div>
  7154. </div>
  7155. <input
  7156. type="range"
  7157. min={1}
  7158. max={24}
  7159. value={dryingDuration}
  7160. onChange={e => setDryingDuration(Number(e.target.value))}
  7161. className="w-full h-1 accent-bambu-green cursor-pointer"
  7162. />
  7163. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7164. <span>1h</span>
  7165. <span>24h</span>
  7166. </div>
  7167. </div>
  7168. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7169. filament threaded out into the feed tube. The whole AMS
  7170. rotates as one mechanism (all 4 spools turn together), so a
  7171. single loaded slot locks the entire unit. Bambu per-tray
  7172. `state`: 9 = empty, 10 = spool present but not loaded
  7173. (rotation possible), 11 = loaded into tube (rotation impossible).
  7174. Catches both mid-print (active feed) AND idle-with-threaded-
  7175. filament — the H2D's post-print state leaves filament in the
  7176. tube but tray_now resets to 255, which a tray_now-only check
  7177. would silently miss. */}
  7178. {(() => {
  7179. const targetAms = dryingPopoverAmsId !== null
  7180. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7181. : undefined;
  7182. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7183. tray => tray.state === 11,
  7184. );
  7185. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7186. return (
  7187. <button
  7188. type="button"
  7189. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7190. aria-pressed={rotateChecked}
  7191. disabled={trayLoadedInThisAms}
  7192. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7193. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7194. rotateChecked
  7195. ? 'bg-bambu-green border-bambu-green text-white'
  7196. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7197. }`}
  7198. >
  7199. {t('printers.drying.rotateTray')}
  7200. </button>
  7201. );
  7202. })()}
  7203. {/* Start mode: now / after delay / at time (#2638) */}
  7204. <div>
  7205. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7206. <div className="grid grid-cols-3 gap-1">
  7207. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7208. <button
  7209. key={mode}
  7210. type="button"
  7211. onClick={() => setDryingStartMode(mode)}
  7212. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7213. dryingStartMode === mode
  7214. ? 'bg-bambu-green border-bambu-green text-white'
  7215. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7216. }`}
  7217. >
  7218. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7219. </button>
  7220. ))}
  7221. </div>
  7222. {dryingStartMode === 'delay' && (
  7223. // Inline chips: a dropdown menu would be clipped by
  7224. // the popover's scrollable body.
  7225. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7226. {DRYING_DELAY_OPTIONS.map(min => (
  7227. <button
  7228. key={min}
  7229. type="button"
  7230. aria-pressed={dryingDelayMinutes === min}
  7231. onClick={() => setDryingDelayMinutes(min)}
  7232. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7233. dryingDelayMinutes === min
  7234. ? 'bg-bambu-green border-bambu-green text-white'
  7235. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7236. }`}
  7237. >
  7238. {formatDurationFromHours(min / 60)}
  7239. </button>
  7240. ))}
  7241. </div>
  7242. )}
  7243. {dryingStartMode === 'at_time' && (
  7244. <input
  7245. ref={dryingAtTimeInputRef}
  7246. type="datetime-local"
  7247. data-testid="drying-start-at"
  7248. value={dryingStartAt}
  7249. onChange={e => setDryingStartAt(e.target.value)}
  7250. 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]"
  7251. />
  7252. )}
  7253. </div>
  7254. </div>
  7255. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7256. {/* Footer */}
  7257. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7258. <button
  7259. onClick={() => {
  7260. if (dryingPopoverAmsId !== null) {
  7261. // Clamp rotateTray off when any tray in this AMS is loaded into
  7262. // the tube — the rotate UI is disabled there, but the state may
  7263. // linger as `true` from a previous AMS, or a print may have
  7264. // started while the popover was open. Without this clamp the
  7265. // Start payload would carry rotate_tray=true and firmware would
  7266. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7267. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7268. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7269. tray => tray.state === 11,
  7270. );
  7271. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7272. if (dryingStartMode === 'now') {
  7273. startDryingMutation.mutate({
  7274. amsId: dryingPopoverAmsId,
  7275. temp: dryingTemp,
  7276. duration: dryingDuration,
  7277. filament: dryingFilament,
  7278. rotateTray: rotate,
  7279. });
  7280. } else {
  7281. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7282. if (startAfter) {
  7283. scheduleDryingMutation.mutate({
  7284. amsId: dryingPopoverAmsId,
  7285. temp: dryingTemp,
  7286. duration: dryingDuration,
  7287. filament: dryingFilament,
  7288. rotateTray: rotate,
  7289. startAfter,
  7290. });
  7291. }
  7292. }
  7293. }
  7294. }}
  7295. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7296. data-testid="drying-start-confirm"
  7297. 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"
  7298. >
  7299. {dryingStartMode === 'now'
  7300. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7301. : t('printers.drying.schedule')}
  7302. </button>
  7303. </div>
  7304. </div>
  7305. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7306. since the popover clips its own overflow. */}
  7307. <div
  7308. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7309. style={{
  7310. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7311. top: dryingPopoverPos.anchorY - 5,
  7312. ...(dryingPopoverPos.placement === 'above'
  7313. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7314. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7315. }}
  7316. />
  7317. </>
  7318. );
  7319. })()}
  7320. </Card>
  7321. );
  7322. }
  7323. export function AddPrinterModal({
  7324. onClose,
  7325. onAdd,
  7326. existingSerials,
  7327. }: {
  7328. onClose: () => void;
  7329. onAdd: (data: PrinterCreate) => void;
  7330. existingSerials: string[];
  7331. }) {
  7332. const { t } = useTranslation();
  7333. const [form, setForm] = useState<PrinterCreate>({
  7334. name: '',
  7335. serial_number: '',
  7336. ip_address: '',
  7337. access_code: '',
  7338. model: '',
  7339. location: '',
  7340. auto_archive: true,
  7341. });
  7342. // Discovery state
  7343. const [discovering, setDiscovering] = useState(false);
  7344. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7345. const [discoveryError, setDiscoveryError] = useState('');
  7346. const [hasScanned, setHasScanned] = useState(false);
  7347. const [isDocker, setIsDocker] = useState(false);
  7348. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7349. const [subnet, setSubnet] = useState('');
  7350. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7351. // text input so users can scan a subnet Bambuddy isn't directly on
  7352. // (printer behind a router on a different L3 segment — SSDP multicast
  7353. // won't cross that boundary, only an active unicast scan will). #1564
  7354. const [customSubnet, setCustomSubnet] = useState('');
  7355. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7356. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7357. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7358. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7359. // (not block) when checks fail, so the user doesn't add a printer that
  7360. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7361. // failed result awaiting an explicit "save anyway".
  7362. const [checkingSave, setCheckingSave] = useState(false);
  7363. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7364. // Fetch discovery info on mount + restore the last custom CIDR the user
  7365. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7366. // time they open this modal).
  7367. useEffect(() => {
  7368. discoveryApi.getInfo().then(info => {
  7369. setIsDocker(info.is_docker);
  7370. if (info.subnets.length > 0) {
  7371. setDetectedSubnets(info.subnets);
  7372. setSubnet(info.subnets[0]);
  7373. }
  7374. }).catch(() => {
  7375. // Ignore errors, assume not Docker
  7376. });
  7377. try {
  7378. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7379. if (saved) setCustomSubnet(saved);
  7380. } catch {
  7381. // localStorage unavailable (private mode, quota); recall is opportunistic
  7382. }
  7383. }, []);
  7384. // Filter out already-added printers
  7385. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7386. const handleAddSubmit = async (e: React.FormEvent) => {
  7387. e.preventDefault();
  7388. setCheckingSave(true);
  7389. try {
  7390. const result = await api.diagnoseConnection({
  7391. ip_address: form.ip_address.trim(),
  7392. serial_number: form.serial_number.trim() || undefined,
  7393. access_code: form.access_code || undefined,
  7394. });
  7395. if (result.checks.some((c) => c.status === 'fail')) {
  7396. setSaveWarning(result);
  7397. return;
  7398. }
  7399. } catch {
  7400. // Diagnostic infrastructure failed — never block the save on it.
  7401. } finally {
  7402. setCheckingSave(false);
  7403. }
  7404. onAdd(form);
  7405. };
  7406. const startDiscovery = async () => {
  7407. setDiscoveryError('');
  7408. setDiscovered([]);
  7409. setDiscovering(true);
  7410. setHasScanned(false);
  7411. setScanProgress({ scanned: 0, total: 0 });
  7412. // Native installs fall back to subnet scanning when the user picks
  7413. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7414. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7415. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7416. const wantsSubnetScan = isDocker || useCustomSubnet;
  7417. if (wantsSubnetScan && useCustomSubnet) {
  7418. try {
  7419. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7420. } catch {
  7421. // localStorage write best-effort; user just retypes next time
  7422. }
  7423. }
  7424. try {
  7425. if (wantsSubnetScan) {
  7426. await discoveryApi.startSubnetScan(scanCidr);
  7427. // Poll for scan status and results
  7428. const pollInterval = setInterval(async () => {
  7429. try {
  7430. const status = await discoveryApi.getScanStatus();
  7431. setScanProgress({ scanned: status.scanned, total: status.total });
  7432. const printers = await discoveryApi.getDiscoveredPrinters();
  7433. setDiscovered(printers);
  7434. if (!status.running) {
  7435. clearInterval(pollInterval);
  7436. setDiscovering(false);
  7437. setHasScanned(true);
  7438. }
  7439. } catch (e) {
  7440. console.error('Failed to get scan status:', e);
  7441. }
  7442. }, 500);
  7443. } else {
  7444. // Use SSDP discovery for native installs
  7445. await discoveryApi.startDiscovery(10);
  7446. // Poll for discovered printers every second
  7447. const pollInterval = setInterval(async () => {
  7448. try {
  7449. const printers = await discoveryApi.getDiscoveredPrinters();
  7450. setDiscovered(printers);
  7451. } catch (e) {
  7452. console.error('Failed to get discovered printers:', e);
  7453. }
  7454. }, 1000);
  7455. // Stop after 10 seconds
  7456. setTimeout(async () => {
  7457. clearInterval(pollInterval);
  7458. try {
  7459. await discoveryApi.stopDiscovery();
  7460. } catch {
  7461. // Ignore stop errors
  7462. }
  7463. setDiscovering(false);
  7464. setHasScanned(true);
  7465. // Final fetch
  7466. try {
  7467. const printers = await discoveryApi.getDiscoveredPrinters();
  7468. setDiscovered(printers);
  7469. } catch (e) {
  7470. console.error('Failed to get final discovered printers:', e);
  7471. }
  7472. }, 10000);
  7473. }
  7474. } catch (e) {
  7475. console.error('Failed to start discovery:', e);
  7476. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7477. setDiscovering(false);
  7478. setHasScanned(true);
  7479. }
  7480. };
  7481. // Reuse module-level mapModelCode
  7482. const selectPrinter = (printer: DiscoveredPrinter) => {
  7483. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7484. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7485. setForm({
  7486. ...form,
  7487. name: printer.name || '',
  7488. serial_number: serialNumber,
  7489. ip_address: printer.ip_address,
  7490. model: mapModelCode(printer.model),
  7491. });
  7492. // Clear discovery results after selection
  7493. setDiscovered([]);
  7494. };
  7495. // Cleanup discovery on unmount
  7496. useEffect(() => {
  7497. return () => {
  7498. discoveryApi.stopDiscovery().catch(() => {});
  7499. discoveryApi.stopSubnetScan().catch(() => {});
  7500. };
  7501. }, []);
  7502. // Close on Escape key
  7503. useEffect(() => {
  7504. const handleKeyDown = (e: KeyboardEvent) => {
  7505. if (e.key === 'Escape') onClose();
  7506. };
  7507. window.addEventListener('keydown', handleKeyDown);
  7508. return () => window.removeEventListener('keydown', handleKeyDown);
  7509. }, [onClose]);
  7510. return (
  7511. <>
  7512. <div
  7513. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7514. onClick={onClose}
  7515. >
  7516. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7517. <CardContent>
  7518. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7519. {/* Discovery Section */}
  7520. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7521. {/* Subnet picker — always visible. The dropdown lists detected
  7522. interface subnets and a "Custom..." sentinel that reveals
  7523. a CIDR text input for printers on a different L3 segment
  7524. (router, VLAN, etc.). #1564 */}
  7525. <div className="mb-3">
  7526. <label className="block text-sm text-bambu-gray mb-1">
  7527. {t('printers.discovery.subnetToScan')}
  7528. </label>
  7529. {detectedSubnets.length > 0 ? (
  7530. <select
  7531. 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"
  7532. value={useCustomSubnet ? '__custom__' : subnet}
  7533. onChange={(e) => {
  7534. if (e.target.value === '__custom__') {
  7535. setUseCustomSubnet(true);
  7536. } else {
  7537. setUseCustomSubnet(false);
  7538. setSubnet(e.target.value);
  7539. }
  7540. }}
  7541. disabled={discovering}
  7542. >
  7543. {detectedSubnets.map(s => (
  7544. <option key={s} value={s}>{s}</option>
  7545. ))}
  7546. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7547. </select>
  7548. ) : (
  7549. <input
  7550. type="text"
  7551. 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"
  7552. value={subnet}
  7553. onChange={(e) => setSubnet(e.target.value)}
  7554. placeholder="192.168.1.0/24"
  7555. disabled={discovering}
  7556. />
  7557. )}
  7558. {useCustomSubnet && (
  7559. <input
  7560. type="text"
  7561. aria-label={t('printers.discovery.customSubnetLabel')}
  7562. 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"
  7563. value={customSubnet}
  7564. onChange={(e) => setCustomSubnet(e.target.value)}
  7565. placeholder="10.1.1.0/24"
  7566. disabled={discovering}
  7567. />
  7568. )}
  7569. <p className="mt-1 text-xs text-bambu-gray">
  7570. {isDocker
  7571. ? t('printers.discovery.dockerNote')
  7572. : t('printers.discovery.customSubnetNote')}
  7573. </p>
  7574. </div>
  7575. <Button
  7576. type="button"
  7577. variant="secondary"
  7578. onClick={startDiscovery}
  7579. disabled={discovering}
  7580. className="w-full"
  7581. >
  7582. {discovering ? (
  7583. <>
  7584. <Loader2 className="w-4 h-4 animate-spin" />
  7585. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7586. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7587. : t('printers.discovery.scanning')}
  7588. </>
  7589. ) : (
  7590. <>
  7591. <Search className="w-4 h-4" />
  7592. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7593. </>
  7594. )}
  7595. </Button>
  7596. {discoveryError && (
  7597. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7598. )}
  7599. {newPrinters.length > 0 && (
  7600. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7601. {newPrinters.map((printer) => (
  7602. <div
  7603. key={printer.serial}
  7604. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7605. onClick={() => selectPrinter(printer)}
  7606. >
  7607. <div className="min-w-0 flex-1">
  7608. <p className="font-medium text-white text-sm truncate">
  7609. {printer.name || printer.serial}
  7610. </p>
  7611. <p className="text-xs text-bambu-gray truncate">
  7612. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7613. {printer.serial.startsWith('unknown-') && (
  7614. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7615. )}
  7616. </p>
  7617. </div>
  7618. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7619. </div>
  7620. ))}
  7621. </div>
  7622. )}
  7623. {discovering && (
  7624. <p className="mt-2 text-sm text-bambu-gray text-center">
  7625. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7626. </p>
  7627. )}
  7628. {hasScanned && !discovering && discovered.length === 0 && (
  7629. <p className="mt-2 text-sm text-bambu-gray text-center">
  7630. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7631. </p>
  7632. )}
  7633. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7634. <p className="mt-2 text-sm text-bambu-gray text-center">
  7635. {t('printers.discovery.allConfigured')}
  7636. </p>
  7637. )}
  7638. </div>
  7639. <form onSubmit={handleAddSubmit} className="space-y-4">
  7640. <div>
  7641. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7642. <input
  7643. type="text"
  7644. required
  7645. 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"
  7646. value={form.name}
  7647. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7648. placeholder={t('printers.modal.myPrinter')}
  7649. />
  7650. </div>
  7651. <div>
  7652. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7653. <input
  7654. type="text"
  7655. required
  7656. 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])?)*)"
  7657. 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"
  7658. value={form.ip_address}
  7659. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7660. placeholder="192.168.1.100 or printer.local"
  7661. />
  7662. </div>
  7663. <div>
  7664. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7665. <input
  7666. type="text"
  7667. required
  7668. 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"
  7669. value={form.serial_number}
  7670. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7671. placeholder="01P00A000000000"
  7672. />
  7673. </div>
  7674. <div>
  7675. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7676. <input
  7677. type="password"
  7678. required
  7679. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7680. value={form.access_code}
  7681. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7682. placeholder={t('printers.modal.fromPrinterSettings')}
  7683. />
  7684. </div>
  7685. <div>
  7686. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7687. <select
  7688. 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"
  7689. value={form.model || ''}
  7690. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7691. >
  7692. <option value="">{t('printers.modal.selectModel')}</option>
  7693. <optgroup label="A1 Series">
  7694. <option value="A1">A1</option>
  7695. <option value="A1 Mini">A1 Mini</option>
  7696. </optgroup>
  7697. <optgroup label="A2 Series">
  7698. <option value="A2L">A2L</option>
  7699. </optgroup>
  7700. <optgroup label="H2 Series">
  7701. <option value="H2C">H2C</option>
  7702. <option value="H2D">H2D</option>
  7703. <option value="H2D Pro">H2D Pro</option>
  7704. <option value="H2S">H2S</option>
  7705. </optgroup>
  7706. <optgroup label="P Series">
  7707. <option value="P1P">P1P</option>
  7708. <option value="P1S">P1S</option>
  7709. <option value="P2S">P2S</option>
  7710. </optgroup>
  7711. <optgroup label="X1 Series">
  7712. <option value="X1">X1</option>
  7713. <option value="X1C">X1 Carbon</option>
  7714. <option value="X1E">X1E</option>
  7715. </optgroup>
  7716. <optgroup label="X2 Series">
  7717. <option value="X2D">X2D</option>
  7718. </optgroup>
  7719. </select>
  7720. </div>
  7721. <div>
  7722. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7723. <input
  7724. type="text"
  7725. 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"
  7726. value={form.location || ''}
  7727. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7728. placeholder={t('printers.modal.locationPlaceholder')}
  7729. maxLength={100}
  7730. />
  7731. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7732. </div>
  7733. <div className="flex items-center gap-2">
  7734. <input
  7735. type="checkbox"
  7736. id="auto_archive"
  7737. checked={form.auto_archive}
  7738. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7739. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7740. />
  7741. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7742. {t('printers.modal.autoArchiveLabel')}
  7743. </label>
  7744. </div>
  7745. <button
  7746. type="button"
  7747. onClick={() => setShowDiagnostic(true)}
  7748. disabled={!form.ip_address.trim()}
  7749. 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"
  7750. >
  7751. <Stethoscope className="w-4 h-4" />
  7752. {t('diagnostic.runButton')}
  7753. </button>
  7754. {saveWarning ? (
  7755. <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">
  7756. <div className="flex items-start gap-2">
  7757. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7758. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7759. </div>
  7760. <DiagnosticChecklist result={saveWarning} />
  7761. <div className="flex gap-3">
  7762. <Button
  7763. type="button"
  7764. variant="secondary"
  7765. onClick={() => setSaveWarning(null)}
  7766. className="flex-1"
  7767. >
  7768. {t('printers.addPreflight.back')}
  7769. </Button>
  7770. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7771. {t('printers.addPreflight.saveAnyway')}
  7772. </Button>
  7773. </div>
  7774. </div>
  7775. ) : (
  7776. <div className="flex gap-3 pt-2">
  7777. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7778. {t('common.cancel')}
  7779. </Button>
  7780. <Button type="submit" disabled={checkingSave} className="flex-1">
  7781. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7782. </Button>
  7783. </div>
  7784. )}
  7785. </form>
  7786. </CardContent>
  7787. </Card>
  7788. </div>
  7789. {showDiagnostic && (
  7790. <ConnectionDiagnosticModal
  7791. connection={{
  7792. ip_address: form.ip_address.trim(),
  7793. serial_number: form.serial_number.trim() || undefined,
  7794. access_code: form.access_code || undefined,
  7795. }}
  7796. printerName={form.name || null}
  7797. onClose={() => setShowDiagnostic(false)}
  7798. />
  7799. )}
  7800. </>
  7801. );
  7802. }
  7803. function FirmwareUpdateModal({
  7804. printer,
  7805. firmwareInfo,
  7806. onClose,
  7807. }: {
  7808. printer: Printer;
  7809. firmwareInfo: FirmwareUpdateInfo;
  7810. onClose: () => void;
  7811. }) {
  7812. const { t } = useTranslation();
  7813. const queryClient = useQueryClient();
  7814. const { showToast } = useToast();
  7815. const { hasPermission } = useAuth();
  7816. const canUpdate = hasPermission('firmware:update');
  7817. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7818. const [isUploading, setIsUploading] = useState(false);
  7819. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7820. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7821. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7822. );
  7823. // Prepare check query — runs when a version is selected and user can update
  7824. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7825. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7826. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7827. staleTime: 30000,
  7828. enabled: !!selectedVersion && canUpdate && !isUploading,
  7829. });
  7830. // Start upload mutation
  7831. const uploadMutation = useMutation({
  7832. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7833. onSuccess: () => {
  7834. setIsUploading(true);
  7835. // Start polling for status
  7836. const interval = setInterval(async () => {
  7837. try {
  7838. const status = await firmwareApi.getUploadStatus(printer.id);
  7839. setUploadStatus(status);
  7840. if (status.status === 'complete' || status.status === 'error') {
  7841. clearInterval(interval);
  7842. setPollInterval(null);
  7843. setIsUploading(false);
  7844. if (status.status === 'complete') {
  7845. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7846. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7847. }
  7848. }
  7849. } catch {
  7850. // Ignore errors during polling
  7851. }
  7852. }, 2000);
  7853. setPollInterval(interval);
  7854. },
  7855. onError: (error: Error) => {
  7856. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7857. setIsUploading(false);
  7858. },
  7859. });
  7860. // Cleanup on unmount
  7861. useEffect(() => {
  7862. return () => {
  7863. if (pollInterval) clearInterval(pollInterval);
  7864. };
  7865. }, [pollInterval]);
  7866. const handleStartUpload = () => {
  7867. setUploadStatus(null);
  7868. uploadMutation.mutate();
  7869. };
  7870. return (
  7871. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7872. <Card className="w-full max-w-md mx-4">
  7873. <CardContent>
  7874. <div className="flex items-start gap-3 mb-4">
  7875. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7876. {firmwareInfo.update_available
  7877. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7878. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7879. </div>
  7880. <div className="flex-1">
  7881. <h3 className="text-lg font-semibold text-white">
  7882. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7883. </h3>
  7884. <p className="text-sm text-bambu-gray mt-1">
  7885. {printer.name}
  7886. </p>
  7887. </div>
  7888. </div>
  7889. {/* Version Info */}
  7890. {(() => {
  7891. const selectedEntry = selectedVersion
  7892. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7893. : null;
  7894. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7895. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7896. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7897. return (
  7898. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7899. <div className="flex justify-between items-center text-sm">
  7900. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7901. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7902. {firmwareInfo.current_version || t('common.unknown')}
  7903. </span>
  7904. </div>
  7905. {showSecondLine && (
  7906. <div className="flex justify-between items-center text-sm mt-1">
  7907. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7908. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7909. </div>
  7910. )}
  7911. {displayNotes && (
  7912. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7913. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7914. {t('printers.firmwareModal.releaseNotes')}
  7915. </summary>
  7916. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7917. {displayNotes}
  7918. </div>
  7919. </details>
  7920. )}
  7921. </div>
  7922. );
  7923. })()}
  7924. {/* Available versions list */}
  7925. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7926. <div className="mb-4">
  7927. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7928. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7929. {firmwareInfo.available_versions.map((v) => {
  7930. const isCurrent = firmwareInfo.current_version === v.version;
  7931. const isSelected = selectedVersion === v.version;
  7932. const cmp = firmwareInfo.current_version
  7933. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7934. : 0;
  7935. const relLabel = isCurrent
  7936. ? t('printers.firmwareModal.currentBadge')
  7937. : cmp > 0
  7938. ? t('printers.firmwareModal.newerBadge')
  7939. : t('printers.firmwareModal.olderBadge');
  7940. const relClass = isCurrent
  7941. ? 'text-bambu-gray'
  7942. : cmp > 0
  7943. ? 'text-orange-700 dark:text-orange-400'
  7944. : 'text-blue-700 dark:text-blue-400';
  7945. return (
  7946. <button
  7947. key={v.version}
  7948. type="button"
  7949. disabled={!v.file_available || !canUpdate || isCurrent}
  7950. onClick={() => setSelectedVersion(v.version)}
  7951. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7952. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7953. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7954. >
  7955. <div className="flex items-center gap-2 min-w-0">
  7956. <span className="font-mono text-white">{v.version}</span>
  7957. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7958. </div>
  7959. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7960. isCurrent
  7961. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7962. : v.file_available
  7963. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7964. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7965. }`}>
  7966. {isCurrent
  7967. ? t('printers.firmwareModal.installed')
  7968. : v.file_available
  7969. ? t('printers.firmwareModal.usable')
  7970. : t('printers.firmwareModal.unavailable')}
  7971. </span>
  7972. </button>
  7973. );
  7974. })}
  7975. </div>
  7976. </div>
  7977. )}
  7978. {/* Status / Progress (only when a version is selected) */}
  7979. {!selectedVersion ? null : isPreparing ? (
  7980. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7981. <Loader2 className="w-4 h-4 animate-spin" />
  7982. {t('printers.firmwareModal.checkingPrereqs')}
  7983. </div>
  7984. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7985. <div className="mb-4">
  7986. {prepareInfo.can_proceed ? (
  7987. <div className="flex items-center gap-2 text-bambu-green text-sm">
  7988. <Box className="w-4 h-4" />
  7989. {t('printers.firmwareModal.sdCardReady')}
  7990. </div>
  7991. ) : (
  7992. <div className="space-y-1">
  7993. {prepareInfo.errors.map((error, i) => (
  7994. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  7995. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  7996. {error}
  7997. </div>
  7998. ))}
  7999. </div>
  8000. )}
  8001. </div>
  8002. ) : null}
  8003. {/* Upload Progress */}
  8004. {(isUploading || uploadStatus) && uploadStatus && (
  8005. <div className="mb-4">
  8006. <div className="flex items-center justify-between text-sm mb-1">
  8007. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8008. <span className="text-white">{uploadStatus.progress}%</span>
  8009. </div>
  8010. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8011. <div
  8012. className={`h-2 rounded-full transition-all ${
  8013. uploadStatus.status === 'error' ? 'bg-status-error' :
  8014. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8015. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8016. style={{ width: `${uploadStatus.progress}%` }}
  8017. />
  8018. </div>
  8019. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8020. {uploadStatus.error && (
  8021. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8022. )}
  8023. </div>
  8024. )}
  8025. {/* Success Message */}
  8026. {uploadStatus?.status === 'complete' && (
  8027. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8028. <p className="text-sm text-bambu-green font-medium mb-2">
  8029. {t('printers.firmwareModal.uploadedSuccess')}
  8030. </p>
  8031. <p className="text-xs text-bambu-gray">
  8032. {t('printers.firmwareModal.applyInstructions')}
  8033. </p>
  8034. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8035. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8036. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8037. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8038. <li>{t('printers.firmwareModal.step4')}</li>
  8039. </ol>
  8040. </div>
  8041. )}
  8042. {/* Buttons */}
  8043. <div className="flex gap-2 justify-end">
  8044. <Button variant="secondary" onClick={onClose}>
  8045. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8046. </Button>
  8047. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8048. <Button
  8049. onClick={handleStartUpload}
  8050. disabled={uploadMutation.isPending}
  8051. >
  8052. {uploadMutation.isPending ? (
  8053. <>
  8054. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8055. {t('printers.firmwareModal.starting')}
  8056. </>
  8057. ) : (
  8058. <>
  8059. <Download className="w-4 h-4 mr-2" />
  8060. {t('printers.firmwareModal.uploadFirmware')}
  8061. </>
  8062. )}
  8063. </Button>
  8064. )}
  8065. </div>
  8066. </CardContent>
  8067. </Card>
  8068. </div>
  8069. );
  8070. }
  8071. function EditPrinterModal({
  8072. printer,
  8073. onClose,
  8074. }: {
  8075. printer: Printer;
  8076. onClose: () => void;
  8077. }) {
  8078. const { t } = useTranslation();
  8079. const queryClient = useQueryClient();
  8080. const { showToast } = useToast();
  8081. const [form, setForm] = useState({
  8082. name: printer.name,
  8083. ip_address: printer.ip_address,
  8084. access_code: '',
  8085. model: printer.model || '',
  8086. location: printer.location || '',
  8087. auto_archive: printer.auto_archive,
  8088. is_active: printer.is_active,
  8089. });
  8090. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8091. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8092. const [checkingSave, setCheckingSave] = useState(false);
  8093. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8094. const updateMutation = useMutation({
  8095. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8096. onSuccess: () => {
  8097. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8098. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8099. onClose();
  8100. },
  8101. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8102. });
  8103. // Close on Escape key
  8104. useEffect(() => {
  8105. const handleKeyDown = (e: KeyboardEvent) => {
  8106. if (e.key === 'Escape') onClose();
  8107. };
  8108. window.addEventListener('keydown', handleKeyDown);
  8109. return () => window.removeEventListener('keydown', handleKeyDown);
  8110. }, [onClose]);
  8111. const doSave = () => {
  8112. const data: Partial<PrinterCreate> = {
  8113. name: form.name,
  8114. ip_address: form.ip_address,
  8115. model: form.model || undefined,
  8116. location: form.location || undefined,
  8117. auto_archive: form.auto_archive,
  8118. is_active: form.is_active,
  8119. };
  8120. // Only include access_code if it was changed
  8121. if (form.access_code) {
  8122. data.access_code = form.access_code;
  8123. }
  8124. updateMutation.mutate(data);
  8125. };
  8126. const handleSubmit = async (e: React.FormEvent) => {
  8127. e.preventDefault();
  8128. setCheckingSave(true);
  8129. try {
  8130. const result = await api.diagnoseConnection({
  8131. ip_address: form.ip_address.trim(),
  8132. serial_number: printer.serial_number,
  8133. access_code: form.access_code || undefined,
  8134. });
  8135. if (result.checks.some((c) => c.status === 'fail')) {
  8136. setSaveWarning(result);
  8137. return;
  8138. }
  8139. } catch {
  8140. // Diagnostic infrastructure failed — never block the save on it.
  8141. } finally {
  8142. setCheckingSave(false);
  8143. }
  8144. doSave();
  8145. };
  8146. return (
  8147. <div
  8148. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8149. onClick={onClose}
  8150. >
  8151. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8152. <CardContent>
  8153. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8154. <form onSubmit={handleSubmit} className="space-y-4">
  8155. <div>
  8156. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8157. <input
  8158. type="text"
  8159. required
  8160. 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"
  8161. value={form.name}
  8162. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8163. placeholder={t('printers.modal.myPrinter')}
  8164. />
  8165. </div>
  8166. <div>
  8167. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8168. <input
  8169. type="text"
  8170. required
  8171. 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])?)*)"
  8172. 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"
  8173. value={form.ip_address}
  8174. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8175. placeholder="192.168.1.100 or printer.local"
  8176. />
  8177. </div>
  8178. <div>
  8179. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8180. <input
  8181. type="text"
  8182. disabled
  8183. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8184. value={printer.serial_number}
  8185. />
  8186. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8187. </div>
  8188. <div>
  8189. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8190. <input
  8191. type="password"
  8192. 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"
  8193. value={form.access_code}
  8194. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8195. placeholder={t('printers.accessCodePlaceholder')}
  8196. />
  8197. </div>
  8198. <div>
  8199. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8200. <select
  8201. 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"
  8202. value={form.model}
  8203. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8204. >
  8205. <option value="">{t('printers.modal.selectModel')}</option>
  8206. <optgroup label="A1 Series">
  8207. <option value="A1">A1</option>
  8208. <option value="A1 Mini">A1 Mini</option>
  8209. </optgroup>
  8210. <optgroup label="A2 Series">
  8211. <option value="A2L">A2L</option>
  8212. </optgroup>
  8213. <optgroup label="H2 Series">
  8214. <option value="H2C">H2C</option>
  8215. <option value="H2D">H2D</option>
  8216. <option value="H2D Pro">H2D Pro</option>
  8217. <option value="H2S">H2S</option>
  8218. </optgroup>
  8219. <optgroup label="P Series">
  8220. <option value="P1P">P1P</option>
  8221. <option value="P1S">P1S</option>
  8222. <option value="P2S">P2S</option>
  8223. </optgroup>
  8224. <optgroup label="X1 Series">
  8225. <option value="X1">X1</option>
  8226. <option value="X1C">X1 Carbon</option>
  8227. <option value="X1E">X1E</option>
  8228. </optgroup>
  8229. <optgroup label="X2 Series">
  8230. <option value="X2D">X2D</option>
  8231. </optgroup>
  8232. </select>
  8233. </div>
  8234. <div>
  8235. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8236. <input
  8237. type="text"
  8238. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8239. value={form.location}
  8240. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8241. placeholder={t('printers.modal.locationPlaceholder')}
  8242. maxLength={100}
  8243. />
  8244. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8245. </div>
  8246. <div className="flex items-center gap-2">
  8247. <input
  8248. type="checkbox"
  8249. id="edit_auto_archive"
  8250. checked={form.auto_archive}
  8251. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8252. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8253. />
  8254. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8255. {t('printers.modal.autoArchiveLabel')}
  8256. </label>
  8257. </div>
  8258. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8259. is_active because the user-facing concept is "is this printer
  8260. in maintenance" not "is it active". */}
  8261. <div>
  8262. <div className="flex items-center gap-2">
  8263. <input
  8264. type="checkbox"
  8265. id="edit_maintenance_mode"
  8266. checked={!form.is_active}
  8267. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8268. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8269. />
  8270. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8271. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8272. {t('printers.maintenance.editFieldLabel')}
  8273. </label>
  8274. </div>
  8275. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8276. {t('printers.maintenance.editFieldHelp')}
  8277. </p>
  8278. </div>
  8279. {saveWarning ? (
  8280. <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">
  8281. <div className="flex items-start gap-2">
  8282. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8283. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8284. </div>
  8285. <DiagnosticChecklist result={saveWarning} />
  8286. <div className="flex gap-3">
  8287. <Button
  8288. type="button"
  8289. variant="secondary"
  8290. onClick={() => setSaveWarning(null)}
  8291. className="flex-1"
  8292. >
  8293. {t('printers.addPreflight.back')}
  8294. </Button>
  8295. <Button
  8296. type="button"
  8297. onClick={doSave}
  8298. className="flex-1"
  8299. disabled={updateMutation.isPending}
  8300. >
  8301. {t('printers.addPreflight.saveAnyway')}
  8302. </Button>
  8303. </div>
  8304. </div>
  8305. ) : (
  8306. <div className="flex gap-3 pt-4">
  8307. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8308. {t('common.cancel')}
  8309. </Button>
  8310. <Button
  8311. type="submit"
  8312. className="flex-1"
  8313. disabled={updateMutation.isPending || checkingSave}
  8314. >
  8315. {checkingSave
  8316. ? t('printers.addPreflight.checking')
  8317. : updateMutation.isPending
  8318. ? t('common.saving')
  8319. : t('printers.modal.saveChanges')}
  8320. </Button>
  8321. </div>
  8322. )}
  8323. </form>
  8324. </CardContent>
  8325. </Card>
  8326. </div>
  8327. );
  8328. }
  8329. // Component to check if a printer is offline (for power dropdown)
  8330. function usePrinterOfflineStatus(printerId: number) {
  8331. const { data: status } = useQuery({
  8332. queryKey: ['printerStatus', printerId],
  8333. queryFn: () => api.getPrinterStatus(printerId),
  8334. refetchInterval: 30000,
  8335. });
  8336. return !status?.connected;
  8337. }
  8338. // Power dropdown item for an offline printer
  8339. function PowerDropdownItem({
  8340. printer,
  8341. plug,
  8342. onPowerOn,
  8343. isPowering,
  8344. }: {
  8345. printer: Printer;
  8346. plug: { id: number; name: string };
  8347. onPowerOn: (plugId: number) => void;
  8348. isPowering: boolean;
  8349. }) {
  8350. const isOffline = usePrinterOfflineStatus(printer.id);
  8351. // Fetch plug status
  8352. const { data: plugStatus } = useQuery({
  8353. queryKey: ['smartPlugStatus', plug.id],
  8354. queryFn: () => api.getSmartPlugStatus(plug.id),
  8355. refetchInterval: 10000,
  8356. });
  8357. // Only show if printer is offline
  8358. if (!isOffline) {
  8359. return null;
  8360. }
  8361. return (
  8362. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8363. <div className="flex items-center gap-2 min-w-0">
  8364. <span className="text-sm text-white truncate">{printer.name}</span>
  8365. {plugStatus && (
  8366. <span
  8367. className={`text-xs px-1.5 py-0.5 rounded ${
  8368. plugStatus.state === 'ON'
  8369. ? 'bg-bambu-green/20 text-bambu-green'
  8370. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8371. }`}
  8372. >
  8373. {plugStatus.state || '?'}
  8374. </span>
  8375. )}
  8376. </div>
  8377. <button
  8378. onClick={() => onPowerOn(plug.id)}
  8379. disabled={isPowering || plugStatus?.state === 'ON'}
  8380. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8381. plugStatus?.state === 'ON'
  8382. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8383. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8384. }`}
  8385. >
  8386. <Power className="w-3 h-3" />
  8387. {isPowering ? '...' : 'On'}
  8388. </button>
  8389. </div>
  8390. );
  8391. }
  8392. export function PrintersPage() {
  8393. const { t } = useTranslation();
  8394. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8395. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8396. const accentButtonClass = {
  8397. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8398. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8399. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8400. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8401. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8402. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8403. }[activeAccent];
  8404. const [showAddModal, setShowAddModal] = useState(false);
  8405. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8406. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8407. });
  8408. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8409. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8410. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8411. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8412. });
  8413. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8414. return localStorage.getItem('printerSortAsc') !== 'false';
  8415. });
  8416. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8417. const [cardSize, setCardSize] = useState<number>(() => {
  8418. const saved = localStorage.getItem('printerCardSize');
  8419. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8420. });
  8421. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8422. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8423. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8424. });
  8425. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8426. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8427. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8428. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8429. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8430. });
  8431. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8432. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8433. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8434. });
  8435. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8436. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8437. // Defaulting to 'full' because the cards already show this info — users who
  8438. // pick cam-wall view still want to glance the same details without flipping.
  8439. // Kept apart from the card size: S on the cards also means the compact
  8440. // layout, and a wall of 2 cameras wants big tiles next to small cards (#2735).
  8441. const [camWallTileSize, setCamWallTileSize] = useState<number>(() => {
  8442. const saved = parseInt(localStorage.getItem('camWallTileSize') || '', 10);
  8443. return saved >= 1 && saved <= 4 ? saved : DEFAULT_CAM_WALL_TILE_SIZE;
  8444. });
  8445. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8446. const saved = localStorage.getItem('camWallStatusMode');
  8447. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8448. });
  8449. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8450. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8451. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8452. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8453. requestAnimationFrame(() => {
  8454. requestAnimationFrame(() => {
  8455. const card = document.getElementById(`printer-card-${printerId}`);
  8456. if (!card) return;
  8457. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8458. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8459. window.scrollTo({
  8460. top: Math.max(0, top),
  8461. behavior: 'smooth',
  8462. });
  8463. });
  8464. });
  8465. }, []);
  8466. const openCompactCard = useCallback((printerId: number) => {
  8467. setCompactDrilldownPrinterId(printerId);
  8468. setCardSize(2);
  8469. localStorage.setItem('printerCardSize', '2');
  8470. scrollPrinterIntoView(printerId);
  8471. }, [scrollPrinterIntoView]);
  8472. const returnToCompactCards = useCallback(() => {
  8473. const printerId = compactDrilldownPrinterId;
  8474. setCompactDrilldownPrinterId(null);
  8475. setCardSize(1);
  8476. localStorage.setItem('printerCardSize', '1');
  8477. if (printerId != null) {
  8478. scrollPrinterIntoView(printerId);
  8479. }
  8480. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8481. const [search, setSearch] = useState('');
  8482. // Both filters persist like every other preference on this page (#2833).
  8483. // `search` deliberately does not: a box that silently refills itself on
  8484. // return is more surprising than a dropdown that remembers.
  8485. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8486. // Validated on read: a value the dropdown no longer offers would filter
  8487. // every printer out, and nothing would explain why.
  8488. const saved = localStorage.getItem('printerStatusFilter');
  8489. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8490. });
  8491. const [locationFilter, setLocationFilter] = useState<string>(
  8492. () => localStorage.getItem('printerLocationFilter') || 'all'
  8493. );
  8494. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8495. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8496. try {
  8497. const saved = localStorage.getItem('printerCollapsedSections');
  8498. return saved ? JSON.parse(saved) : {};
  8499. } catch { return {}; }
  8500. });
  8501. const queryClient = useQueryClient();
  8502. const { showToast } = useToast();
  8503. const { hasPermission } = useAuth();
  8504. // Which way the camera buttons open a stream. Chosen per click from the
  8505. // button's own menu; null until this browser has made a choice, so the
  8506. // stored setting below can act as the default a fresh browser starts from.
  8507. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8508. () => readStoredCameraViewMode()
  8509. );
  8510. // Embedded camera viewer state - supports multiple simultaneous viewers
  8511. // Persisted to localStorage so cameras reopen after navigation
  8512. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8513. const saved = localStorage.getItem('openEmbeddedCameras');
  8514. if (saved) {
  8515. try {
  8516. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8517. return new Map(cameras.map(c => [c.id, c]));
  8518. } catch {
  8519. return new Map();
  8520. }
  8521. }
  8522. return new Map();
  8523. });
  8524. // Persist open cameras to localStorage when they change
  8525. useEffect(() => {
  8526. const cameras = Array.from(embeddedCameraPrinters.values());
  8527. if (cameras.length > 0) {
  8528. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8529. } else {
  8530. localStorage.removeItem('openEmbeddedCameras');
  8531. }
  8532. }, [embeddedCameraPrinters]);
  8533. const { data: printers, isLoading } = useQuery({
  8534. queryKey: ['printers'],
  8535. queryFn: api.getPrinters,
  8536. });
  8537. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8538. // so users with printers:read but no settings:read still get the values needed
  8539. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8540. const { data: settings } = useQuery({
  8541. queryKey: ['ui-preferences'],
  8542. queryFn: api.getUiPreferences,
  8543. });
  8544. // Only once the preferences are in: deciding on `undefined` meant a check
  8545. // switched off still went out once per printer on every page load.
  8546. const firmwareChecksOn = settings !== undefined && settings.check_printer_firmware !== false;
  8547. // Parse user-configured temperature/fan presets once, with defensive fallback
  8548. // to built-in defaults on parse failure (validators on the backend already
  8549. // reject malformed writes, so this is just forward-compat).
  8550. const effectiveNozzleTempPresets = useMemo(
  8551. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8552. [settings?.nozzle_temp_presets],
  8553. );
  8554. const effectiveBedTempPresets = useMemo(
  8555. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8556. [settings?.bed_temp_presets],
  8557. );
  8558. const effectiveChamberTempPresets = useMemo(
  8559. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8560. [settings?.chamber_temp_presets],
  8561. );
  8562. const effectiveFanSpeedPresets = useMemo(
  8563. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8564. [settings?.fan_speed_presets],
  8565. );
  8566. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8567. const effectiveDryingPresets = useMemo(() => {
  8568. if (settings?.drying_presets) {
  8569. try {
  8570. const userPresets = JSON.parse(settings.drying_presets);
  8571. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8572. return { ...DRYING_PRESETS, ...userPresets };
  8573. }
  8574. } catch { /* ignore parse errors, use defaults */ }
  8575. }
  8576. return DRYING_PRESETS;
  8577. }, [settings?.drying_presets]);
  8578. // The local choice wins over the stored one: someone without settings:update
  8579. // cannot write their pick back, and a preference that silently reverted on
  8580. // the next render would be worse than none at all.
  8581. const cameraViewMode: CameraViewMode =
  8582. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8583. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8584. storeCameraViewMode(mode);
  8585. setChosenCameraViewMode(mode);
  8586. // Best effort, and only a default for other browsers -- the choice is
  8587. // already in effect here. Users below settings:update simply keep theirs
  8588. // locally, which is why the failure is logged rather than surfaced.
  8589. if (hasPermission('settings:update')) {
  8590. api.updateSettings({ camera_view_mode: mode })
  8591. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8592. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8593. }
  8594. }, [hasPermission, queryClient]);
  8595. // Fetch all smart plugs to know which printers have them
  8596. const { data: smartPlugs } = useQuery({
  8597. queryKey: ['smart-plugs'],
  8598. queryFn: api.getSmartPlugs,
  8599. });
  8600. // Fetch maintenance overview for all printers to show badges
  8601. const { data: maintenanceOverview } = useQuery({
  8602. queryKey: ['maintenanceOverview'],
  8603. queryFn: api.getMaintenanceOverview,
  8604. staleTime: 60 * 1000, // 1 minute
  8605. });
  8606. // Live AI failure detection state for the card badges (#1546). Matches the
  8607. // 10s refetch of the Failure Detection settings panel.
  8608. const { data: obicoPrinterStatus } = useQuery({
  8609. queryKey: ['obico-printer-status'],
  8610. queryFn: api.getObicoPrinterStatus,
  8611. refetchInterval: 10000,
  8612. });
  8613. // Badge visibility: detection enabled AND this printer in the monitored set
  8614. // (monitored_printers null = all). Live per-print state is passed separately.
  8615. const isAiMonitored = useCallback(
  8616. (printerId: number) =>
  8617. obicoPrinterStatus?.enabled === true &&
  8618. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8619. [obicoPrinterStatus],
  8620. );
  8621. // Fetch Spoolman status to enable link spool feature
  8622. const { data: spoolmanStatus } = useQuery({
  8623. queryKey: ['spoolman-status'],
  8624. queryFn: api.getSpoolmanStatus,
  8625. staleTime: 60 * 1000, // 1 minute
  8626. });
  8627. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8628. // Fetch Spoolman settings to get sync mode
  8629. const { data: spoolmanSettings } = useQuery({
  8630. queryKey: ['spoolman-settings'],
  8631. queryFn: api.getSpoolmanSettings,
  8632. enabled: !!spoolmanEnabled,
  8633. staleTime: 60 * 1000, // 1 minute
  8634. });
  8635. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8636. // Fetch unlinked spools to know if link button should be enabled
  8637. const { data: unlinkedSpools } = useQuery({
  8638. queryKey: ['unlinked-spools'],
  8639. queryFn: api.getUnlinkedSpools,
  8640. enabled: !!spoolmanEnabled,
  8641. staleTime: 30 * 1000, // 30 seconds
  8642. });
  8643. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8644. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8645. const { data: linkedSpoolsData } = useQuery({
  8646. queryKey: ['linked-spools'],
  8647. queryFn: api.getLinkedSpools,
  8648. enabled: !!spoolmanEnabled,
  8649. staleTime: 30 * 1000, // 30 seconds
  8650. });
  8651. const linkedSpools = linkedSpoolsData?.linked;
  8652. // Fetch spool assignments for inventory feature
  8653. const { data: spoolAssignments } = useQuery({
  8654. queryKey: ['spool-assignments'],
  8655. queryFn: () => api.getAssignments(),
  8656. enabled: hasPermission('inventory:view_assignments'),
  8657. staleTime: 30 * 1000,
  8658. });
  8659. const unassignMutation = useMutation({
  8660. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8661. api.unassignSpool(printerId, amsId, trayId),
  8662. onSuccess: () => {
  8663. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8664. },
  8665. });
  8666. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8667. queryKey: ['spoolman-inventory-spools'],
  8668. queryFn: () => api.getSpoolmanInventorySpools(false),
  8669. enabled: !!spoolmanEnabled,
  8670. staleTime: 30 * 1000,
  8671. });
  8672. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8673. queryKey: ['spoolman-slot-assignments'],
  8674. queryFn: () => api.getSpoolmanSlotAssignments(),
  8675. enabled: !!spoolmanEnabled,
  8676. staleTime: 30 * 1000,
  8677. });
  8678. const unassignSpoolmanMutation = useMutation({
  8679. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8680. onSuccess: () => {
  8681. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8682. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8683. },
  8684. });
  8685. // Helper to find assignment for a specific slot
  8686. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8687. return spoolAssignments?.find(
  8688. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8689. );
  8690. };
  8691. // Create a map of printer_id -> maintenance info for quick lookup
  8692. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8693. (acc, overview) => {
  8694. acc[overview.printer_id] = {
  8695. due_count: overview.due_count,
  8696. warning_count: overview.warning_count,
  8697. total_print_hours: overview.total_print_hours,
  8698. };
  8699. return acc;
  8700. },
  8701. {} as Record<number, PrinterMaintenanceInfo>
  8702. ) || {};
  8703. // Create a map of printer_id -> smart plug
  8704. const smartPlugByPrinter = smartPlugs?.reduce(
  8705. (acc, plug) => {
  8706. if (plug.printer_id) {
  8707. acc[plug.printer_id] = plug;
  8708. }
  8709. return acc;
  8710. },
  8711. {} as Record<number, typeof smartPlugs[0]>
  8712. ) || {};
  8713. const addMutation = useMutation({
  8714. mutationFn: api.createPrinter,
  8715. onSuccess: () => {
  8716. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8717. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8718. setShowAddModal(false);
  8719. },
  8720. onError: (error: Error) => {
  8721. // Localized message when the backend returns a stable error code;
  8722. // the raw message is an English fallback for non-UI clients.
  8723. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8724. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8725. return;
  8726. }
  8727. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8728. },
  8729. });
  8730. const powerOnMutation = useMutation({
  8731. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8732. onSuccess: () => {
  8733. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8734. setPoweringOn(null);
  8735. },
  8736. onError: () => {
  8737. setPoweringOn(null);
  8738. },
  8739. });
  8740. // Bulk selection state
  8741. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8742. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8743. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8744. const [bulkActionPending, setBulkActionPending] = useState(false);
  8745. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8746. const toggleSelect = useCallback((id: number) => {
  8747. setSelectedPrinterIds(prev => {
  8748. const next = new Set(prev);
  8749. if (next.has(id)) next.delete(id);
  8750. else next.add(id);
  8751. return next;
  8752. });
  8753. }, []);
  8754. const clearSelection = useCallback(() => {
  8755. setSelectedPrinterIds(new Set());
  8756. setIsSelectionMode(false);
  8757. }, []);
  8758. // Escape key exits selection mode
  8759. useEffect(() => {
  8760. const handleKeyDown = (e: KeyboardEvent) => {
  8761. if (e.key === 'Escape' && selectionMode) {
  8762. clearSelection();
  8763. }
  8764. };
  8765. window.addEventListener('keydown', handleKeyDown);
  8766. return () => window.removeEventListener('keydown', handleKeyDown);
  8767. }, [selectionMode, clearSelection]);
  8768. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8769. setBulkActionPending(true);
  8770. const ids = Array.from(selectedPrinterIds);
  8771. // Filter to only applicable printers based on cached state
  8772. const applicableIds = ids.filter(id => {
  8773. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8774. // clearPlate is checked before the connection filter: it only releases a
  8775. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8776. // down — every other action here needs to reach the machine (#2864).
  8777. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8778. if (!status?.connected) return false;
  8779. switch (action) {
  8780. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8781. case 'pause': return status.state === 'RUNNING';
  8782. case 'resume': return status.state === 'PAUSE';
  8783. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8784. default: return false;
  8785. }
  8786. });
  8787. if (applicableIds.length === 0) {
  8788. showToast(t('printers.bulk.noneApplicable'), 'error');
  8789. setBulkActionPending(false);
  8790. setBulkConfirmAction(null);
  8791. return;
  8792. }
  8793. const apiCall = {
  8794. stop: api.stopPrint,
  8795. pause: api.pausePrint,
  8796. resume: api.resumePrint,
  8797. clearPlate: api.clearPlate,
  8798. clearHMS: api.clearHMSErrors,
  8799. }[action];
  8800. const results = await Promise.allSettled(
  8801. applicableIds.map(id => apiCall(id))
  8802. );
  8803. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8804. const failed = results.filter(r => r.status === 'rejected').length;
  8805. if (failed === 0) {
  8806. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8807. } else {
  8808. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8809. }
  8810. // Invalidate status queries for affected printers
  8811. applicableIds.forEach(id => {
  8812. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8813. });
  8814. setBulkActionPending(false);
  8815. setBulkConfirmAction(null);
  8816. }, [selectedPrinterIds, queryClient, showToast, t]);
  8817. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8818. // Actions that need confirmation
  8819. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8820. setBulkConfirmAction(action);
  8821. } else {
  8822. executeBulkAction(action);
  8823. }
  8824. }, [executeBulkAction]);
  8825. const toggleHideDisconnected = () => {
  8826. const newValue = !hideDisconnected;
  8827. setHideDisconnected(newValue);
  8828. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8829. };
  8830. const handleSortChange = (newSort: SortOption) => {
  8831. setSortBy(newSort);
  8832. localStorage.setItem('printerSortBy', newSort);
  8833. };
  8834. const handleStatusFilterChange = (value: string) => {
  8835. setStatusFilter(value);
  8836. localStorage.setItem('printerStatusFilter', value);
  8837. };
  8838. const handleLocationFilterChange = (value: string) => {
  8839. setLocationFilter(value);
  8840. localStorage.setItem('printerLocationFilter', value);
  8841. };
  8842. const toggleSortDirection = () => {
  8843. const newAsc = !sortAsc;
  8844. setSortAsc(newAsc);
  8845. localStorage.setItem('printerSortAsc', String(newAsc));
  8846. };
  8847. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8848. const getGridClasses = () => {
  8849. switch (cardSize) {
  8850. 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
  8851. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8852. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8853. case 4: return 'grid-cols-1'; // XL: single column, full width
  8854. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8855. }
  8856. };
  8857. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8858. // Increment version counter whenever a printer status cache entry is updated so
  8859. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8860. useEffect(() => {
  8861. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8862. if (
  8863. event.type === 'updated' &&
  8864. Array.isArray(event.query.queryKey) &&
  8865. event.query.queryKey[0] === 'printerStatus'
  8866. ) {
  8867. setStatusCacheVersion(v => v + 1);
  8868. }
  8869. });
  8870. return unsubscribe;
  8871. }, [queryClient]);
  8872. // Filter printers by search term, status, and location
  8873. const filteredPrinters = useMemo(() => {
  8874. if (!printers) return [];
  8875. let result = printers;
  8876. // Text search
  8877. if (search.trim()) {
  8878. const q = search.trim().toLowerCase();
  8879. result = result.filter(p =>
  8880. p.name.toLowerCase().includes(q) ||
  8881. (p.model || '').toLowerCase().includes(q) ||
  8882. (p.location || '').toLowerCase().includes(q) ||
  8883. (p.serial_number || '').toLowerCase().includes(q)
  8884. );
  8885. }
  8886. // Location filter
  8887. if (locationFilter !== 'all') {
  8888. result = result.filter(p => (p.location || '') === locationFilter);
  8889. }
  8890. // Status filter
  8891. if (statusFilter !== 'all') {
  8892. result = result.filter(p => {
  8893. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8894. if (!status?.connected) return statusFilter === 'offline';
  8895. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8896. switch (statusFilter) {
  8897. case 'printing': return status.state === 'RUNNING';
  8898. case 'paused': return status.state === 'PAUSE';
  8899. case 'finished': return status.state === 'FINISH';
  8900. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8901. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8902. case 'offline': return false; // Connected printers are never offline
  8903. default: return true;
  8904. }
  8905. });
  8906. }
  8907. return result;
  8908. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8909. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8910. // Derive unique locations for the location filter dropdown
  8911. const availableLocations = useMemo(() => {
  8912. if (!printers) return [];
  8913. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8914. }, [printers]);
  8915. // A saved location can outlive what it matched -- renamed, cleared, or the
  8916. // only printer that had it deleted. The dropdown is rendered only while some
  8917. // printer has a location, so a stale one would hide every printer *and* the
  8918. // control to undo it, leaving an empty page and no way back (#2833).
  8919. // Deliberately waits for `printers`: it is undefined while the query is in
  8920. // flight, and acting on the empty list that produces would throw the saved
  8921. // filter away every time the page loads.
  8922. useEffect(() => {
  8923. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8924. setLocationFilter('all');
  8925. localStorage.setItem('printerLocationFilter', 'all');
  8926. }, [printers, availableLocations, locationFilter]);
  8927. // Sort printers based on selected option
  8928. const sortedPrinters = useMemo(() => {
  8929. const sorted = [...filteredPrinters];
  8930. switch (sortBy) {
  8931. case 'name':
  8932. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8933. break;
  8934. case 'model':
  8935. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8936. break;
  8937. case 'location':
  8938. // Sort by location, with ungrouped printers last
  8939. sorted.sort((a, b) => {
  8940. const locA = a.location || '';
  8941. const locB = b.location || '';
  8942. if (!locA && locB) return 1;
  8943. if (locA && !locB) return -1;
  8944. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  8945. });
  8946. break;
  8947. case 'status':
  8948. // Sort by status: HMS errors > printing > idle > offline
  8949. sorted.sort((a, b) => {
  8950. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  8951. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  8952. const getPriority = (s: typeof statusA) => {
  8953. if (!s?.connected) return 3; // offline
  8954. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  8955. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  8956. if (s.state === 'RUNNING') return 1; // printing
  8957. return 2; // idle
  8958. };
  8959. return getPriority(statusA) - getPriority(statusB);
  8960. });
  8961. break;
  8962. case 'eta':
  8963. sorted.sort((a, b) => {
  8964. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8965. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8966. const tier = (s: typeof statusA) => {
  8967. if (!s?.connected) return 3; // offline last
  8968. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8969. if (s.state === 'RUNNING') return 1; // printing without ETA
  8970. return 2; // idle
  8971. };
  8972. const ta = tier(statusA);
  8973. const tb = tier(statusB);
  8974. if (ta !== tb) return ta - tb;
  8975. if (ta === 0) {
  8976. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8977. if (diff !== 0) return diff;
  8978. }
  8979. return a.name.localeCompare(b.name);
  8980. });
  8981. break;
  8982. }
  8983. // Apply ascending/descending
  8984. if (!sortAsc) {
  8985. sorted.reverse();
  8986. }
  8987. return sorted;
  8988. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  8989. const selectAll = useCallback(() => {
  8990. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  8991. setIsSelectionMode(true);
  8992. }, [sortedPrinters]);
  8993. const selectByState = useCallback((state: PrinterState) => {
  8994. setSelectedPrinterIds(prev => {
  8995. const next = new Set(prev);
  8996. sortedPrinters.forEach(p => {
  8997. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8998. if (classifyPrinterStatus(status) === state) next.add(p.id);
  8999. });
  9000. return next;
  9001. });
  9002. setIsSelectionMode(true);
  9003. }, [sortedPrinters, queryClient]);
  9004. const selectByLocation = useCallback((location: string) => {
  9005. setSelectedPrinterIds(prev => {
  9006. const next = new Set(prev);
  9007. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9008. return next;
  9009. });
  9010. setIsSelectionMode(true);
  9011. }, [sortedPrinters]);
  9012. const selectByModel = useCallback((model: string) => {
  9013. setSelectedPrinterIds(prev => {
  9014. const next = new Set(prev);
  9015. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9016. return next;
  9017. });
  9018. setIsSelectionMode(true);
  9019. }, [sortedPrinters]);
  9020. const toggleSectionCollapse = useCallback((key: string) => {
  9021. setCollapsedSections(prev => {
  9022. const next = { ...prev, [key]: !prev[key] };
  9023. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9024. return next;
  9025. });
  9026. }, []);
  9027. // Group printers when sorted by location, status, or model
  9028. const groupedPrinters = useMemo(() => {
  9029. if (sortBy === 'name' || sortBy === 'eta') return null;
  9030. const groups: Record<string, typeof sortedPrinters> = {};
  9031. if (sortBy === 'location') {
  9032. sortedPrinters.forEach(printer => {
  9033. const location = printer.location || 'Ungrouped';
  9034. if (!groups[location]) groups[location] = [];
  9035. groups[location].push(printer);
  9036. });
  9037. } else if (sortBy === 'model') {
  9038. sortedPrinters.forEach(printer => {
  9039. const model = printer.model || 'Unknown';
  9040. if (!groups[model]) groups[model] = [];
  9041. groups[model].push(printer);
  9042. });
  9043. } else if (sortBy === 'status') {
  9044. sortedPrinters.forEach(printer => {
  9045. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9046. const group = classifyPrinterStatus(status);
  9047. if (!groups[group]) groups[group] = [];
  9048. groups[group].push(printer);
  9049. });
  9050. }
  9051. return groups;
  9052. // 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
  9053. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9054. const toolbarRef = useRef<HTMLDivElement>(null);
  9055. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9056. const expandedToolbarWidthRef = useRef(0);
  9057. const [compactToolbar, setCompactToolbar] = useState(false);
  9058. const measureToolbar = useCallback(() => {
  9059. const toolbar = toolbarRef.current;
  9060. if (!toolbar) return;
  9061. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9062. if (measuredControlsWidth) {
  9063. expandedToolbarWidthRef.current = measuredControlsWidth;
  9064. }
  9065. const searchMinimumWidth = 220;
  9066. const gapWidth = 8;
  9067. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9068. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9069. }, []);
  9070. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9071. useLayoutEffect(() => {
  9072. measureToolbar();
  9073. const toolbar = toolbarRef.current;
  9074. if (!toolbar) return;
  9075. if (typeof ResizeObserver === 'undefined') {
  9076. window.addEventListener('resize', measureToolbar);
  9077. return () => window.removeEventListener('resize', measureToolbar);
  9078. }
  9079. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9080. resizeObserver.observe(toolbar);
  9081. window.addEventListener('resize', measureToolbar);
  9082. return () => {
  9083. resizeObserver.disconnect();
  9084. window.removeEventListener('resize', measureToolbar);
  9085. };
  9086. }, [
  9087. measureToolbar,
  9088. printers?.length,
  9089. availableLocations.length,
  9090. hideDisconnected,
  9091. smartPlugCount,
  9092. ]);
  9093. const renderFilterControls = (inMenu = false) => (
  9094. <>
  9095. {/* Status filter */}
  9096. {printers && printers.length > 0 && (
  9097. <ToolbarDropdown
  9098. value={statusFilter}
  9099. onChange={handleStatusFilterChange}
  9100. fullWidth={inMenu}
  9101. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9102. />
  9103. )}
  9104. {/* Location filter — only shown when at least one printer has a location */}
  9105. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9106. <ToolbarDropdown
  9107. value={locationFilter}
  9108. onChange={handleLocationFilterChange}
  9109. fullWidth={inMenu}
  9110. options={[
  9111. { value: 'all', label: t('printers.filter.allLocations') },
  9112. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9113. ]}
  9114. />
  9115. )}
  9116. <button
  9117. type="button"
  9118. onClick={toggleHideDisconnected}
  9119. aria-pressed={hideDisconnected}
  9120. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9121. hideDisconnected
  9122. ? 'bg-bambu-green border-bambu-green text-white'
  9123. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9124. }`}
  9125. >
  9126. {t('printers.hideOffline')}
  9127. </button>
  9128. </>
  9129. );
  9130. const renderViewControls = (inMenu = false) => (
  9131. <>
  9132. {/* Sort dropdown */}
  9133. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9134. <ToolbarDropdown<SortOption>
  9135. value={sortBy}
  9136. onChange={handleSortChange}
  9137. fullWidth={inMenu}
  9138. options={[
  9139. { value: 'name', label: t('printers.sort.name') },
  9140. { value: 'status', label: t('printers.sort.status') },
  9141. { value: 'model', label: t('printers.sort.model') },
  9142. { value: 'location', label: t('printers.sort.location') },
  9143. { value: 'eta', label: t('printers.sort.eta') },
  9144. ]}
  9145. />
  9146. <button
  9147. onClick={toggleSortDirection}
  9148. 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"
  9149. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9150. >
  9151. {sortAsc ? (
  9152. <ArrowUp className="w-4 h-4 text-white" />
  9153. ) : (
  9154. <ArrowDown className="w-4 h-4 text-white" />
  9155. )}
  9156. </button>
  9157. <RouterLink
  9158. to="/printer-locations"
  9159. 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"
  9160. title={t('printers.locations.title')}
  9161. aria-label={t('printers.locations.title')}
  9162. >
  9163. <Box className="w-4 h-4 text-bambu-green" />
  9164. </RouterLink>
  9165. </div>
  9166. {/* Page view toggle: Cards / Cam Wall */}
  9167. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9168. <button
  9169. type="button"
  9170. onClick={() => {
  9171. setPageView('cards');
  9172. localStorage.setItem('printerPageView', 'cards');
  9173. }}
  9174. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9175. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9176. }`}
  9177. title={t('printers.pageView.cards')}
  9178. aria-pressed={pageView === 'cards'}
  9179. >
  9180. <LayoutGrid className="w-3.5 h-3.5" />
  9181. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9182. </button>
  9183. <button
  9184. type="button"
  9185. onClick={() => {
  9186. setPageView('camwall');
  9187. localStorage.setItem('printerPageView', 'camwall');
  9188. }}
  9189. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9190. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9191. }`}
  9192. title={t('printers.pageView.camWall')}
  9193. aria-pressed={pageView === 'camwall'}
  9194. disabled={!hasPermission('camera:view')}
  9195. >
  9196. <MonitorPlay className="w-3.5 h-3.5" />
  9197. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9198. </button>
  9199. </div>
  9200. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9201. view, and the page a kiosk token points at. Only offered once the wall
  9202. is the active view, so it doesn't compete with the toggle above. */}
  9203. {pageView === 'camwall' && hasPermission('camera:view') && (
  9204. <RouterLink
  9205. to="/camwall"
  9206. 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' : ''}`}
  9207. title={t('printers.pageView.openCamWallPage')}
  9208. >
  9209. <ExternalLink className="w-3.5 h-3.5" />
  9210. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9211. </RouterLink>
  9212. )}
  9213. {/* Card size selector */}
  9214. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9215. {cardSizeLabels.map((label, index) => {
  9216. const size = index + 1;
  9217. const isSelected = (pageView === 'camwall' ? camWallTileSize : cardSize) === size;
  9218. return (
  9219. <button
  9220. key={label}
  9221. onClick={() => {
  9222. if (pageView === 'camwall') {
  9223. setCamWallTileSize(size);
  9224. localStorage.setItem('camWallTileSize', String(size));
  9225. return;
  9226. }
  9227. setCompactDrilldownPrinterId(null);
  9228. setCardSize(size);
  9229. localStorage.setItem('printerCardSize', String(size));
  9230. }}
  9231. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9232. index === 0 ? 'rounded-l-lg' : ''
  9233. } ${
  9234. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9235. } ${
  9236. isSelected
  9237. ? 'bg-bambu-green text-white'
  9238. : 'text-white hover:bg-bambu-dark-tertiary'
  9239. }`}
  9240. title={t(`printers.${pageView === 'camwall' ? 'camWall.tileSize' : 'cardSize'}.${['small', 'medium', 'large', 'extraLarge'][index]}`)}
  9241. >
  9242. {label}
  9243. </button>
  9244. );
  9245. })}
  9246. </div>
  9247. </>
  9248. );
  9249. const renderActionControls = (inMenu = false) => (
  9250. <>
  9251. {/* Bulk select toggle */}
  9252. <button
  9253. onClick={() => {
  9254. if (selectionMode) clearSelection();
  9255. else setIsSelectionMode(true);
  9256. }}
  9257. className={`h-8 px-2 rounded-lg border transition-colors ${inMenu ? 'w-full justify-center gap-1.5 text-sm font-medium flex items-center' : ''} ${
  9258. selectionMode
  9259. ? 'bg-bambu-green border-bambu-green text-white'
  9260. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9261. }`}
  9262. title={t('printers.bulk.select')}
  9263. disabled={!hasPermission('printers:control')}
  9264. >
  9265. <CheckSquare className="w-4 h-4" />
  9266. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9267. </button>
  9268. {/* Power dropdown for offline printers with smart plugs */}
  9269. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9270. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9271. <button
  9272. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9273. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9274. inMenu
  9275. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9276. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9277. }`}
  9278. >
  9279. <span className="flex items-center gap-1.5">
  9280. <Power className="w-4 h-4" />
  9281. {t('printers.powerOn')}
  9282. </span>
  9283. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9284. </button>
  9285. {showPowerDropdown && (
  9286. <>
  9287. {/* Backdrop to close dropdown */}
  9288. <div
  9289. className="fixed inset-0 z-10"
  9290. onClick={() => setShowPowerDropdown(false)}
  9291. />
  9292. <div className="absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1">
  9293. <div className="px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary">
  9294. {t('printers.offlinePrintersWithPlugs')}
  9295. </div>
  9296. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9297. <PowerDropdownItem
  9298. key={printer.id}
  9299. printer={printer}
  9300. plug={smartPlugByPrinter[printer.id]}
  9301. onPowerOn={(plugId) => {
  9302. setPoweringOn(plugId);
  9303. powerOnMutation.mutate(plugId);
  9304. }}
  9305. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9306. />
  9307. ))}
  9308. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9309. <div className="px-3 py-2 text-sm text-bambu-gray">
  9310. No printers with smart plugs
  9311. </div>
  9312. )}
  9313. </div>
  9314. </>
  9315. )}
  9316. </div>
  9317. )}
  9318. <Button
  9319. onClick={() => setShowAddModal(true)}
  9320. disabled={!hasPermission('printers:create')}
  9321. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9322. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9323. >
  9324. <Plus className="w-4 h-4" />
  9325. {t('printers.addPrinter')}
  9326. </Button>
  9327. </>
  9328. );
  9329. return (
  9330. <div className="p-4 md:p-8">
  9331. <div className="space-y-3 mb-6">
  9332. <div>
  9333. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9334. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9335. {t('printers.title')}
  9336. </h1>
  9337. <StatusSummaryBar printers={printers} />
  9338. </div>
  9339. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9340. {/* Only show search bar when printers exist */}
  9341. {printers && printers.length > 0 && (
  9342. <div className="relative min-w-0 flex-1">
  9343. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9344. <input
  9345. type="search"
  9346. name="printer-search"
  9347. autoComplete="off"
  9348. data-1p-ignore
  9349. data-lpignore="true"
  9350. value={search}
  9351. onChange={(e) => setSearch(e.target.value)}
  9352. placeholder={t('printers.search')}
  9353. aria-label={t('printers.search')}
  9354. className="w-full h-8 pl-9 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  9355. />
  9356. {search && (
  9357. <button
  9358. type="button"
  9359. aria-label={t('common.clear')}
  9360. onClick={() => setSearch('')}
  9361. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9362. >
  9363. <X className="w-4 h-4" />
  9364. </button>
  9365. )}
  9366. </div>
  9367. )}
  9368. <div
  9369. ref={expandedToolbarControlsRef}
  9370. aria-hidden={compactToolbar}
  9371. inert={compactToolbar}
  9372. className={`${compactToolbar ? 'absolute -left-[9999px] top-0 flex w-max pointer-events-none opacity-0' : 'flex'} ml-auto items-center justify-end gap-2 flex-nowrap [&>*]:shrink-0`}
  9373. >
  9374. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9375. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9376. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9377. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9378. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9379. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9380. </div>
  9381. {compactToolbar && (
  9382. <div className="ml-auto flex items-center justify-end gap-1">
  9383. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9384. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9385. </ToolbarMenu>
  9386. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9387. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9388. </ToolbarMenu>
  9389. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9390. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9391. </ToolbarMenu>
  9392. </div>
  9393. )}
  9394. </div>
  9395. </div>
  9396. {isLoading ? (
  9397. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9398. ) : printers?.length === 0 ? (
  9399. <Card>
  9400. <CardContent className="text-center py-12">
  9401. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9402. <Button
  9403. onClick={() => setShowAddModal(true)}
  9404. disabled={!hasPermission('printers:create')}
  9405. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9406. >
  9407. <Plus className="w-4 h-4" />
  9408. {t('printers.addPrinter')}
  9409. </Button>
  9410. </CardContent>
  9411. </Card>
  9412. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9413. <Card>
  9414. <CardContent className="text-center py-12">
  9415. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9416. </CardContent>
  9417. </Card>
  9418. ) : pageView === 'camwall' ? (
  9419. <CameraWall
  9420. printers={sortedPrinters}
  9421. maxLive={camWallMaxLive}
  9422. snapshotIntervalSec={camWallSnapshotSec}
  9423. tileSize={camWallTileSize}
  9424. onTileClick={(id, name) => {
  9425. // A wall tile has no room for a split button, so it follows the
  9426. // mode the card buttons last chose.
  9427. if (cameraViewMode === 'embedded') {
  9428. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9429. } else {
  9430. openCameraWindow(id);
  9431. }
  9432. }}
  9433. statusMode={camWallStatusMode}
  9434. onChangeMaxLive={(next) => {
  9435. setCamWallMaxLive(next);
  9436. localStorage.setItem('camWallMaxLive', String(next));
  9437. }}
  9438. onChangeSnapshotIntervalSec={(next) => {
  9439. setCamWallSnapshotSec(next);
  9440. localStorage.setItem('camWallSnapshotSec', String(next));
  9441. }}
  9442. onChangeStatusMode={(next) => {
  9443. setCamWallStatusMode(next);
  9444. localStorage.setItem('camWallStatusMode', next);
  9445. }}
  9446. />
  9447. ) : groupedPrinters ? (
  9448. /* Grouped view (location, status, or model) */
  9449. <div className="space-y-6">
  9450. {(() => {
  9451. const keys = sortBy === 'status'
  9452. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9453. : Object.keys(groupedPrinters);
  9454. // For status grouping, asc/desc flips the fixed priority order
  9455. // (asc = error→offline, desc = offline→error). This matches the
  9456. // sort-toggle behaviour for other groupings.
  9457. return (sortAsc ? keys : [...keys].reverse());
  9458. })().map((groupKey) => {
  9459. const groupPrinters = groupedPrinters[groupKey];
  9460. const collapseKey = `${sortBy}:${groupKey}`;
  9461. const isOpen = !collapsedSections[collapseKey];
  9462. const dot = sortBy === 'status'
  9463. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9464. : 'bg-bambu-green';
  9465. const label = sortBy === 'status'
  9466. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9467. : groupKey;
  9468. return (
  9469. <Collapsible
  9470. key={groupKey}
  9471. open={isOpen}
  9472. onToggle={() => toggleSectionCollapse(collapseKey)}
  9473. summaryClassName="py-1"
  9474. summary={
  9475. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9476. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9477. {label}
  9478. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9479. {selectionMode && (
  9480. <button
  9481. onClick={(e) => {
  9482. e.stopPropagation();
  9483. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9484. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9485. else if (sortBy === 'model') selectByModel(groupKey);
  9486. }}
  9487. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9488. >
  9489. {t('printers.bulk.selectAll')}
  9490. </button>
  9491. )}
  9492. </h2>
  9493. }
  9494. >
  9495. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9496. {groupPrinters.map((printer) => (
  9497. <PrinterCard
  9498. key={printer.id}
  9499. printer={printer}
  9500. hideIfDisconnected={hideDisconnected}
  9501. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9502. viewMode={viewMode}
  9503. cardSize={cardSize}
  9504. amsThresholds={settings ? {
  9505. humidityGood: Number(settings.ams_humidity_good) || 40,
  9506. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9507. tempGood: Number(settings.ams_temp_good) || 28,
  9508. tempFair: Number(settings.ams_temp_fair) || 35,
  9509. } : undefined}
  9510. spoolmanEnabled={spoolmanEnabled}
  9511. hasUnlinkedSpools={hasUnlinkedSpools}
  9512. linkedSpools={linkedSpools}
  9513. spoolmanUrl={spoolmanStatus?.url}
  9514. spoolmanSyncMode={spoolmanSyncMode}
  9515. onGetAssignment={getAssignment}
  9516. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9517. spoolmanSpools={spoolmanSpools}
  9518. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9519. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9520. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9521. timeFormat={settings?.time_format || 'system'}
  9522. cameraViewMode={cameraViewMode}
  9523. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9524. onSelectCameraViewMode={selectCameraViewMode}
  9525. checkPrinterFirmware={firmwareChecksOn}
  9526. dryingPresets={effectiveDryingPresets}
  9527. nozzleTempPresets={effectiveNozzleTempPresets}
  9528. bedTempPresets={effectiveBedTempPresets}
  9529. chamberTempPresets={effectiveChamberTempPresets}
  9530. fanSpeedPresets={effectiveFanSpeedPresets}
  9531. requirePlateClear={settings?.require_plate_clear === true}
  9532. selectionMode={selectionMode}
  9533. isSelected={selectedPrinterIds.has(printer.id)}
  9534. onToggleSelect={toggleSelect}
  9535. onOpenCompactCard={openCompactCard}
  9536. aiDetectionEnabled={isAiMonitored(printer.id)}
  9537. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9538. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9539. />
  9540. ))}
  9541. </div>
  9542. </Collapsible>
  9543. );
  9544. })}
  9545. </div>
  9546. ) : (
  9547. /* Regular grid view */
  9548. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9549. {sortedPrinters.map((printer) => (
  9550. <PrinterCard
  9551. key={printer.id}
  9552. printer={printer}
  9553. hideIfDisconnected={hideDisconnected}
  9554. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9555. viewMode={viewMode}
  9556. cardSize={cardSize}
  9557. spoolmanEnabled={spoolmanEnabled}
  9558. hasUnlinkedSpools={hasUnlinkedSpools}
  9559. linkedSpools={linkedSpools}
  9560. spoolmanUrl={spoolmanStatus?.url}
  9561. spoolmanSyncMode={spoolmanSyncMode}
  9562. onGetAssignment={getAssignment}
  9563. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9564. spoolmanSpools={spoolmanSpools}
  9565. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9566. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9567. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9568. amsThresholds={settings ? {
  9569. humidityGood: Number(settings.ams_humidity_good) || 40,
  9570. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9571. tempGood: Number(settings.ams_temp_good) || 28,
  9572. tempFair: Number(settings.ams_temp_fair) || 35,
  9573. } : undefined}
  9574. timeFormat={settings?.time_format || 'system'}
  9575. cameraViewMode={cameraViewMode}
  9576. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9577. onSelectCameraViewMode={selectCameraViewMode}
  9578. checkPrinterFirmware={firmwareChecksOn}
  9579. dryingPresets={effectiveDryingPresets}
  9580. nozzleTempPresets={effectiveNozzleTempPresets}
  9581. bedTempPresets={effectiveBedTempPresets}
  9582. chamberTempPresets={effectiveChamberTempPresets}
  9583. fanSpeedPresets={effectiveFanSpeedPresets}
  9584. requirePlateClear={settings?.require_plate_clear === true}
  9585. selectionMode={selectionMode}
  9586. isSelected={selectedPrinterIds.has(printer.id)}
  9587. onToggleSelect={toggleSelect}
  9588. onOpenCompactCard={openCompactCard}
  9589. aiDetectionEnabled={isAiMonitored(printer.id)}
  9590. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9591. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9592. />
  9593. ))}
  9594. </div>
  9595. )}
  9596. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9597. <button
  9598. type="button"
  9599. onClick={returnToCompactCards}
  9600. 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}`}
  9601. title={t('common.back', 'Back')}
  9602. >
  9603. <ArrowLeft className="w-4 h-4" />
  9604. {t('common.back', 'Back')}
  9605. </button>
  9606. )}
  9607. {showAddModal && (
  9608. <AddPrinterModal
  9609. onClose={() => setShowAddModal(false)}
  9610. onAdd={(data) => addMutation.mutate(data)}
  9611. existingSerials={printers?.map(p => p.serial_number) || []}
  9612. />
  9613. )}
  9614. {/* Bulk selection toolbar */}
  9615. {selectionMode && printers && (
  9616. <BulkPrinterToolbar
  9617. selectedIds={selectedPrinterIds}
  9618. printers={printers}
  9619. onClose={clearSelection}
  9620. onSelectAll={selectAll}
  9621. onSelectByLocation={selectByLocation}
  9622. onSelectByState={selectByState}
  9623. onAction={handleBulkAction}
  9624. actionPending={bulkActionPending}
  9625. />
  9626. )}
  9627. {/* Bulk action confirmation modals */}
  9628. {bulkConfirmAction === 'stop' && (
  9629. <ConfirmModal
  9630. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9631. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9632. confirmText={t('printers.bulk.confirm.stopButton')}
  9633. variant="danger"
  9634. isLoading={bulkActionPending}
  9635. onConfirm={() => executeBulkAction('stop')}
  9636. onCancel={() => setBulkConfirmAction(null)}
  9637. />
  9638. )}
  9639. {bulkConfirmAction === 'pause' && (
  9640. <ConfirmModal
  9641. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9642. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9643. confirmText={t('printers.bulk.confirm.pauseButton')}
  9644. isLoading={bulkActionPending}
  9645. onConfirm={() => executeBulkAction('pause')}
  9646. onCancel={() => setBulkConfirmAction(null)}
  9647. />
  9648. )}
  9649. {bulkConfirmAction === 'clearPlate' && (
  9650. <ConfirmModal
  9651. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9652. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9653. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9654. isLoading={bulkActionPending}
  9655. onConfirm={() => executeBulkAction('clearPlate')}
  9656. onCancel={() => setBulkConfirmAction(null)}
  9657. />
  9658. )}
  9659. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9660. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9661. <EmbeddedCameraViewer
  9662. key={camera.id}
  9663. printerId={camera.id}
  9664. printerName={camera.name}
  9665. viewerIndex={index}
  9666. onClose={() => setEmbeddedCameraPrinters(prev => {
  9667. const next = new Map(prev);
  9668. next.delete(camera.id);
  9669. return next;
  9670. })}
  9671. />
  9672. ))}
  9673. </div>
  9674. );
  9675. }