PrintersPage.tsx 500 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { mapModelCode } from '../utils/printerModel';
  5. import { formatPrintName } from '../utils/printName';
  6. import { isBedSlinger } from '../utils/bedSlinger';
  7. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  8. import {
  9. openCameraWindow,
  10. readStoredCameraViewMode,
  11. storeCameraViewMode,
  12. type CameraViewMode,
  13. } from '../utils/camera';
  14. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  15. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  16. import {
  17. isExternalSpoolHidden,
  18. setExternalSpoolHidden as persistExternalSpoolHidden,
  19. } from '../utils/printerCardPrefs';
  20. import {
  21. BED_TEMP_DEFAULTS,
  22. CHAMBER_TEMP_DEFAULTS,
  23. FAN_SPEED_DEFAULTS,
  24. NOZZLE_TEMP_DEFAULTS,
  25. buildPresetOptions,
  26. parsePresetTriple,
  27. } from '../utils/temperatureFanPresets';
  28. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  29. // covers header + filament select + temp slider + duration + rotate-tray
  30. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  31. // earlier); under-estimating leaves the popover clipped off the bottom (the
  32. // original bug at #1447).
  33. const DRYING_POPOVER_WIDTH = 240;
  34. // Height in "now" mode plus the tallest start-mode control; a conservative
  35. // over-estimate just flips the popover above the trigger sooner.
  36. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  37. // Delay presets for the "After delay" drying start mode, in minutes.
  38. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  39. // Every printer card reads the same fleet-wide scheduled-drying list.
  40. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  41. // Why a due run has not started yet: every waiting_reason the scheduler can
  42. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  43. // for ..." with no hint why nothing is happening.
  44. const WAITING_REASON_KEYS: Record<string, string> = {
  45. ams_power_required: 'printers.drying.powerRequired',
  46. ams_retract_filament: 'printers.drying.retractFilament',
  47. ams_blocked: 'printers.drying.cannotDryNow',
  48. ams_not_found: 'printers.drying.waitingAmsNotFound',
  49. printer_offline: 'printers.drying.waitingOffline',
  50. printer_busy: 'printers.drying.waitingPrinterBusy',
  51. already_drying: 'printers.drying.waitingAlreadyDrying',
  52. interrupted: 'printers.drying.waitingInterrupted',
  53. };
  54. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  55. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  56. }
  57. // Why a scheduled drying failed, by the code the scheduler stores. A row with
  58. // no code (failed before codes existed) or an unknown one shows the backend's
  59. // English error_message instead.
  60. const FAILED_REASON_KEYS: Record<string, string> = {
  61. screen_only: 'printers.drying.screenOnly',
  62. unsupported: 'printers.drying.notSupported',
  63. did_not_start: 'printers.drying.scheduleFailedDidNotStart',
  64. };
  65. function failedReasonKey(code: string | null | undefined): string | undefined {
  66. return code ? FAILED_REASON_KEYS[code] : undefined;
  67. }
  68. // Which cannot-dry code to name when the firmware reports several at once.
  69. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  70. // button's tooltip and a scheduled row's waiting reason describe one blocked
  71. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  72. // left at the outlet, and both need the user to go and do something. The rest
  73. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  74. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  75. const codes = (reasons ?? []).map(r => Number(r));
  76. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  77. if (codes.includes(3)) return 'printers.drying.retractFilament';
  78. return 'printers.drying.cannotDryNow';
  79. }
  80. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  81. import { useTranslation } from 'react-i18next';
  82. import { useTheme } from '../contexts/ThemeContext';
  83. import { useAuth } from '../contexts/AuthContext';
  84. import {
  85. Plus,
  86. Link,
  87. Unlink,
  88. Signal,
  89. Clock,
  90. MoreVertical,
  91. Trash2,
  92. RefreshCw,
  93. RotateCw,
  94. Box,
  95. HardDrive,
  96. AlertTriangle,
  97. AlertCircle,
  98. Terminal,
  99. Power,
  100. Zap,
  101. Wrench,
  102. ChevronDown,
  103. Eye,
  104. EyeOff,
  105. Filter,
  106. Pencil,
  107. ArrowLeft,
  108. ArrowRight,
  109. ArrowUp,
  110. ArrowDown,
  111. Layers,
  112. Video,
  113. Search,
  114. Loader2,
  115. Square,
  116. Pause,
  117. Play,
  118. X,
  119. Fan,
  120. Wind,
  121. AirVent,
  122. Download,
  123. ScanSearch,
  124. CheckCircle,
  125. CheckSquare,
  126. XCircle,
  127. User,
  128. Home,
  129. Printer as PrinterIcon,
  130. Info,
  131. Cable,
  132. Flame,
  133. Hourglass,
  134. Repeat,
  135. Snowflake,
  136. Gauge,
  137. DoorOpen,
  138. DoorClosed,
  139. Move,
  140. LogIn,
  141. LogOut,
  142. MoreHorizontal,
  143. SlidersHorizontal,
  144. Stethoscope,
  145. ScanEye,
  146. LineChart as LineChartIcon,
  147. LayoutGrid,
  148. MonitorPlay,
  149. ExternalLink,
  150. PictureInPicture2,
  151. ThumbsUp,
  152. ThumbsDown,
  153. KeyRound,
  154. } from 'lucide-react';
  155. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  156. // Aliased: lucide-react already exports a `Link` icon into this module.
  157. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  158. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  159. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  160. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  161. import { Card, CardContent } from '../components/Card';
  162. import { Button } from '../components/Button';
  163. import { ConfirmModal } from '../components/ConfirmModal';
  164. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  165. import { FileManagerModal } from '../components/FileManagerModal';
  166. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  167. import { CameraWall } from '../components/CameraWall';
  168. import { DEFAULT_CAM_WALL_TILE_SIZE } from '../components/camWallTileSize';
  169. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  170. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  171. import { HMSErrorModal, filterKnownHMSErrors, isSevereHMSError } from '../components/HMSErrorModal';
  172. import { AiDetectionModal } from '../components/AiDetectionModal';
  173. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  174. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  175. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  176. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  177. import { AmsBackupModal } from '../components/AmsBackupModal';
  178. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  179. import type { HeaterSensorKind } from '../api/client';
  180. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  181. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  182. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  183. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  184. import { useToast } from '../contexts/ToastContext';
  185. import { ChamberLight } from '../components/icons/ChamberLight';
  186. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  187. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  188. import { FileUploadModal } from '../components/FileUploadModal';
  189. import { PrintModal } from '../components/PrintModal';
  190. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  191. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  192. import { plateCheckFailureText } from '../utils/plateCheck';
  193. import { amsHasLoadedTray, getAmsLabel, getEmptySlotKind, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isAmsHtUnit, isBambuLabSpool, trayForSlot, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  194. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  195. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  196. import { Collapsible } from '../components/Collapsible';
  197. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  198. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  199. import { NumberInput } from '../components/NumberInput';
  200. import { getCurrencySymbol } from '../utils/currency';
  201. import { useUiSettings } from '../hooks/useUiSettings';
  202. import { isSlicedLibraryFile, mayBeSlicedFileName } from '../utils/libraryFiles';
  203. // The status filter's options, and the only values it may hold. One list so a
  204. // saved filter cannot be validated against a set the dropdown has since moved
  205. // on from (#2833). Labels stay literal so they remain greppable.
  206. const STATUS_FILTER_OPTIONS = [
  207. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  208. { value: 'printing', labelKey: 'printers.status.printing' },
  209. { value: 'paused', labelKey: 'printers.status.paused' },
  210. { value: 'idle', labelKey: 'printers.status.idle' },
  211. { value: 'finished', labelKey: 'printers.status.finished' },
  212. { value: 'error', labelKey: 'printers.status.error' },
  213. { value: 'offline', labelKey: 'printers.status.offline' },
  214. ] as const;
  215. function isKnownStatusFilter(value: string | null): boolean {
  216. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  217. }
  218. export interface SpoolmanSlotAssignmentRow {
  219. printer_id: number;
  220. ams_id: number;
  221. tray_id: number;
  222. spoolman_spool_id: number;
  223. }
  224. // Color names resolve via getColorName() which reads the backend color_catalog
  225. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  226. // Format K value with 3 decimal places, default to 0.020 if null
  227. function formatKValue(k: number | null | undefined): string {
  228. const value = k ?? 0.020;
  229. return value.toFixed(3);
  230. }
  231. // K-profile value shown on the slot card itself (#2532) rather than only inside
  232. // the hover popup, the way BambuStudio shows it per slot.
  233. //
  234. // `k` arrives already gated on the slot being loaded; falsy means the printer
  235. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  236. // missing value, which is captioned inside the hover card but would read as a
  237. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  238. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  239. // reported 0 makes that expression evaluate to the number 0, and React renders
  240. // numbers, putting a bare "0" under the material name.
  241. //
  242. // `reserve` holds the row's height open on the slots without a value whenever
  243. // some other slot on the same card has one, so every fill bar stays on one line.
  244. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  245. const { t } = useTranslation();
  246. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  247. if (!k) {
  248. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  249. }
  250. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  251. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  252. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  253. // family per browser and so measured differently in Safari.
  254. return (
  255. <div className={className} title={t('ams.kFactor')}>
  256. {t('ams.kFactorShort')} {formatKValue(k)}
  257. </div>
  258. );
  259. }
  260. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  261. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  262. const { mode } = useTheme();
  263. const { t } = useTranslation();
  264. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  265. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  266. return (
  267. <span
  268. 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"
  269. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  270. title={side === 'L' ? t('common.left') : t('common.right')}
  271. >
  272. {side}
  273. </span>
  274. );
  275. }
  276. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  277. // deliberately a different colour, because it means something different: this
  278. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  279. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  280. const { mode } = useTheme();
  281. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  282. return (
  283. <span
  284. 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"
  285. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  286. title={title}
  287. >
  288. {FTS_INLET_SIDE[inlet]}
  289. </span>
  290. );
  291. }
  292. /**
  293. * Which side indicator, if any, belongs on an AMS card header.
  294. *
  295. * Three sources, in descending authority:
  296. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  297. * through the switch, so the inlet is the only meaningful label.
  298. * 2. A real extruder id from ams_extruder_map.
  299. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  300. * never reported a map. This one is only a guess, and it is suppressed
  301. * when a switch is installed: with an FTS every unit reports extruder
  302. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  303. * nothing but their unit numbers.
  304. */
  305. function amsSideBadge(
  306. amsId: number,
  307. amsExtruderMap: Record<string, number>,
  308. amsSwitchInlet: Record<string, 'A' | 'B'>,
  309. ftsInstalled: boolean
  310. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  311. const inlet = amsSwitchInlet[String(amsId)];
  312. if (inlet) return { kind: 'inlet', inlet };
  313. const mapped = amsExtruderMap[String(amsId)];
  314. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  315. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  316. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  317. return null;
  318. }
  319. // Expand nozzle type codes to material names
  320. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  321. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  322. function nozzleTypeName(type: string, t: (key: string) => string): string {
  323. if (!type) return '';
  324. // Full text names (from main nozzle info)
  325. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  326. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  327. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  328. // 4-char codes (e.g. "HS01"): last 2 digits = material
  329. if (type.length >= 4) {
  330. const material = type.slice(2, 4);
  331. if (material === '00') return t('printers.nozzleStainlessSteel');
  332. if (material === '01') return t('printers.nozzleHardenedSteel');
  333. if (material === '05') return t('printers.nozzleTungstenCarbide');
  334. }
  335. // 2-digit numeric codes
  336. if (type === '00') return t('printers.nozzleStainlessSteel');
  337. if (type === '01') return t('printers.nozzleHardenedSteel');
  338. if (type === '05') return t('printers.nozzleTungstenCarbide');
  339. // 2-char alpha codes: H prefix = hardened steel
  340. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  341. return type;
  342. }
  343. // Parse flow type from nozzle type code
  344. // HH = high flow, HS = standard/normal
  345. function nozzleFlowName(type: string, t: (key: string) => string): string {
  346. if (!type) return '';
  347. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  348. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  349. return '';
  350. }
  351. // Per-slot hover card for nozzle rack
  352. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  353. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  354. slot: import('../api/client').NozzleRackSlot;
  355. index: number;
  356. activeStatus?: boolean;
  357. filamentName?: string;
  358. children: React.ReactNode;
  359. }) {
  360. const { t } = useTranslation();
  361. const [isVisible, setIsVisible] = useState(false);
  362. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  363. const triggerRef = useRef<HTMLDivElement>(null);
  364. const cardRef = useRef<HTMLDivElement>(null);
  365. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  366. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  367. const isMounted = slot.stat === 1;
  368. useEffect(() => {
  369. if (isVisible && triggerRef.current && cardRef.current) {
  370. const triggerRect = triggerRef.current.getBoundingClientRect();
  371. const cardHeight = cardRef.current.offsetHeight;
  372. const headerHeight = 56;
  373. const spaceAbove = triggerRect.top - headerHeight;
  374. const spaceBelow = window.innerHeight - triggerRect.bottom;
  375. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  376. setPosition('bottom');
  377. } else {
  378. setPosition('top');
  379. }
  380. }
  381. }, [isVisible]);
  382. const handleMouseEnter = () => {
  383. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  384. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  385. };
  386. const handleMouseLeave = () => {
  387. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  388. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  389. };
  390. useEffect(() => {
  391. return () => {
  392. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  393. };
  394. }, []);
  395. const filamentCss = parseFilamentColor(slot.filament_color);
  396. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  397. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  398. return (
  399. <div
  400. ref={triggerRef}
  401. className="relative"
  402. onMouseEnter={handleMouseEnter}
  403. onMouseLeave={handleMouseLeave}
  404. >
  405. {children}
  406. {isVisible && (
  407. <div
  408. ref={cardRef}
  409. className={`
  410. absolute left-1/2 -translate-x-1/2 z-50
  411. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  412. animate-in fade-in-0 zoom-in-95 duration-150
  413. `}
  414. style={{ maxWidth: 'calc(100vw - 24px)' }}
  415. >
  416. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  417. {isEmpty ? (
  418. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  419. Slot {index + 1} — Empty
  420. </div>
  421. ) : (
  422. <div className="p-2.5 space-y-1.5">
  423. {/* Diameter */}
  424. <div className="flex items-center justify-between">
  425. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  426. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  427. </div>
  428. {/* Type */}
  429. {typeFull && (
  430. <div className="flex items-center justify-between">
  431. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  432. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  433. </div>
  434. )}
  435. {/* Flow (hide if empty) */}
  436. {flowFull && (
  437. <div className="flex items-center justify-between">
  438. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  439. <span className="text-xs text-white font-semibold">{flowFull}</span>
  440. </div>
  441. )}
  442. {/* Status badge */}
  443. <div className="flex items-center justify-between">
  444. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  445. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  446. activeStatus || isMounted
  447. ? 'bg-green-900/50 text-green-400'
  448. : 'bg-bambu-dark-tertiary text-bambu-gray'
  449. }`}>
  450. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  451. </span>
  452. </div>
  453. {/* Wear (hide if null) */}
  454. {slot.wear != null && (
  455. <div className="flex items-center justify-between">
  456. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  457. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  458. </div>
  459. )}
  460. {/* Max Temp (hide if 0) */}
  461. {slot.max_temp > 0 && (
  462. <div className="flex items-center justify-between">
  463. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  464. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  465. </div>
  466. )}
  467. {/* Serial (hide if empty) */}
  468. {slot.serial_number && (
  469. <div className="flex items-center justify-between">
  470. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  471. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  472. </div>
  473. )}
  474. {/* Filament: material type + color swatch (hide if no color) */}
  475. {(filamentCss || slot.filament_type) && (
  476. <div className="flex items-center justify-between">
  477. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  478. <div className="flex items-center gap-1">
  479. {filamentCss && (
  480. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  481. )}
  482. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  483. </div>
  484. </div>
  485. )}
  486. </div>
  487. )}
  488. </div>
  489. {/* Arrow pointer */}
  490. <div
  491. className={`
  492. absolute left-1/2 -translate-x-1/2 w-0 h-0
  493. border-l-[6px] border-l-transparent
  494. border-r-[6px] border-r-transparent
  495. ${position === 'top'
  496. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  497. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  498. `}
  499. />
  500. </div>
  501. )}
  502. </div>
  503. );
  504. }
  505. // Dual-nozzle hover card showing L and R nozzle details side by side
  506. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  507. leftSlot?: import('../api/client').NozzleRackSlot;
  508. rightSlot?: import('../api/client').NozzleRackSlot;
  509. activeNozzle: 'L' | 'R';
  510. filamentInfo?: Record<string, { name: string; k: number | null }>;
  511. children: React.ReactNode;
  512. }) {
  513. const { t } = useTranslation();
  514. const [isVisible, setIsVisible] = useState(false);
  515. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  516. const triggerRef = useRef<HTMLDivElement>(null);
  517. const cardRef = useRef<HTMLDivElement>(null);
  518. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  519. useEffect(() => {
  520. if (isVisible && triggerRef.current && cardRef.current) {
  521. const triggerRect = triggerRef.current.getBoundingClientRect();
  522. const cardHeight = cardRef.current.offsetHeight;
  523. const headerHeight = 56;
  524. const spaceAbove = triggerRect.top - headerHeight;
  525. const spaceBelow = window.innerHeight - triggerRect.bottom;
  526. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  527. setPosition('bottom');
  528. } else {
  529. setPosition('top');
  530. }
  531. }
  532. }, [isVisible]);
  533. const handleMouseEnter = () => {
  534. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  535. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  536. };
  537. const handleMouseLeave = () => {
  538. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  539. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  540. };
  541. useEffect(() => {
  542. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  543. }, []);
  544. if (!leftSlot && !rightSlot) return <>{children}</>;
  545. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  546. const isActive = activeNozzle === side;
  547. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  548. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  549. const filamentCss = parseFilamentColor(slot.filament_color);
  550. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  551. return (
  552. <div className="flex-1 space-y-1.5">
  553. <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'}`}>
  554. {side === 'L' ? t('common.left') : t('common.right')}
  555. </div>
  556. {slot.nozzle_diameter && (
  557. <div className="flex items-center justify-between">
  558. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  559. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  560. </div>
  561. )}
  562. {typeFull && (
  563. <div className="flex items-center justify-between">
  564. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  565. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  566. </div>
  567. )}
  568. {flowFull && (
  569. <div className="flex items-center justify-between">
  570. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  571. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  572. </div>
  573. )}
  574. <div className="flex items-center justify-between">
  575. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  576. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  577. isActive
  578. ? 'bg-green-900/50 text-green-400'
  579. : 'bg-bambu-dark-tertiary text-bambu-gray'
  580. }`}>
  581. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  582. </span>
  583. </div>
  584. {slot.wear != null && (
  585. <div className="flex items-center justify-between">
  586. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  587. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  588. </div>
  589. )}
  590. {/* Serial and max temp only available on the right (removable) nozzle */}
  591. {side === 'R' && slot.max_temp > 0 && (
  592. <div className="flex items-center justify-between">
  593. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  594. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  595. </div>
  596. )}
  597. {side === 'R' && slot.serial_number && (
  598. <div className="flex items-center justify-between">
  599. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  600. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  601. </div>
  602. )}
  603. {(filamentCss || slot.filament_type || slot.filament_id) && (
  604. <div className="flex items-center justify-between">
  605. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  606. <div className="flex items-center gap-1">
  607. {filamentCss && (
  608. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  609. )}
  610. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  611. {filamentName || slot.filament_type || slot.filament_id || ''}
  612. </span>
  613. </div>
  614. </div>
  615. )}
  616. </div>
  617. );
  618. };
  619. return (
  620. <div
  621. ref={triggerRef}
  622. className="relative flex-1"
  623. onMouseEnter={handleMouseEnter}
  624. onMouseLeave={handleMouseLeave}
  625. >
  626. {children}
  627. {isVisible && (
  628. <div
  629. ref={cardRef}
  630. className={`
  631. absolute left-1/2 -translate-x-1/2 z-50
  632. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  633. animate-in fade-in-0 zoom-in-95 duration-150
  634. `}
  635. style={{ maxWidth: 'calc(100vw - 24px)' }}
  636. >
  637. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  638. <div className="p-2.5 flex gap-3">
  639. {leftSlot && renderColumn(leftSlot, 'L')}
  640. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  641. {rightSlot && renderColumn(rightSlot, 'R')}
  642. </div>
  643. </div>
  644. {/* Arrow pointer */}
  645. <div
  646. className={`
  647. absolute left-1/2 -translate-x-1/2 w-0 h-0
  648. border-l-[6px] border-l-transparent
  649. border-r-[6px] border-r-transparent
  650. ${position === 'top'
  651. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  652. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  653. `}
  654. />
  655. </div>
  656. )}
  657. </div>
  658. );
  659. }
  660. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  661. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  662. const { t } = useTranslation();
  663. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  664. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  665. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  666. // base — computing it from min(present IDs) shifts everything left when slot 16
  667. // is the one currently mounted (#943).
  668. const rackNozzles = slots.filter(s => s.id >= 2);
  669. const RACK_SIZE = 6;
  670. const RACK_BASE_ID = 16;
  671. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  672. { length: RACK_SIZE },
  673. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  674. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  675. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  676. },
  677. );
  678. return (
  679. // Sized to its contents rather than growing: the six chips are a fixed
  680. // width at any one card size, so extra width would be dead space taken
  681. // from the temperature cards beside it — which are flex-1 with a 0 basis
  682. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  683. // stays enabled so the card still gives way on a narrow printer card
  684. // instead of overflowing.
  685. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  686. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  687. <div className="flex gap-[3px] justify-center">
  688. {rackSlots.map((slot, i) => {
  689. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  690. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  691. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  692. return (
  693. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  694. <div className="flex flex-col items-center gap-0.5">
  695. <div
  696. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  697. isEmpty
  698. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  699. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  700. }`}
  701. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  702. >
  703. <span
  704. data-rack-diameter
  705. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  706. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  707. >
  708. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  709. </span>
  710. </div>
  711. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  712. acted on without counting chips. Sits below the chip rather
  713. than inside it: the chip is barely wider than its own
  714. diameter text and already carries that over a
  715. filament-coloured background. */}
  716. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  717. {i + 1}
  718. </span>
  719. </div>
  720. </NozzleSlotHoverCard>
  721. );
  722. })}
  723. </div>
  724. </div>
  725. );
  726. }
  727. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  728. function WaterDropEmpty({ className }: { className?: string }) {
  729. return (
  730. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  731. <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"/>
  732. </svg>
  733. );
  734. }
  735. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  736. function WaterDropHalf({ className }: { className?: string }) {
  737. return (
  738. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  739. <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"/>
  740. <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"/>
  741. </svg>
  742. );
  743. }
  744. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  745. function WaterDropFull({ className }: { className?: string }) {
  746. return (
  747. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  748. <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"/>
  749. <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"/>
  750. </svg>
  751. );
  752. }
  753. // Thermometer SVG - empty outline
  754. function ThermometerEmpty({ className }: { className?: string }) {
  755. return (
  756. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  757. <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"/>
  758. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  759. </svg>
  760. );
  761. }
  762. // Thermometer SVG - half filled (gold - same as humidity fair)
  763. function ThermometerHalf({ className }: { className?: string }) {
  764. return (
  765. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  766. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  767. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  768. <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"/>
  769. </svg>
  770. );
  771. }
  772. // Thermometer SVG - fully filled (red - same as humidity bad)
  773. function ThermometerFull({ className }: { className?: string }) {
  774. return (
  775. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  776. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  777. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  778. <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"/>
  779. </svg>
  780. );
  781. }
  782. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  783. // Added for visual parity with the thermometer icons on the dual-nozzle card
  784. // that previously had no icon at all (#1115, design by @m4rtini2).
  785. function NozzleIcon({ className }: { className?: string }) {
  786. return (
  787. <svg
  788. className={className}
  789. viewBox="0 0 24 24"
  790. fill="none"
  791. xmlns="http://www.w3.org/2000/svg"
  792. stroke="currentColor"
  793. strokeWidth="1.5"
  794. strokeLinecap="round"
  795. strokeLinejoin="round"
  796. >
  797. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  798. <rect x="6" y="11.5" width="12.1" height="3.7" />
  799. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  800. </svg>
  801. );
  802. }
  803. // Heater thermometer icon - filled when heating, outline when off
  804. interface HeaterThermometerProps {
  805. className?: string;
  806. color: string; // The color class (e.g., "text-orange-400")
  807. isHeating: boolean;
  808. }
  809. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  810. // Extract the actual color from Tailwind class for SVG fill
  811. const colorMap: Record<string, string> = {
  812. 'text-orange-400': '#fb923c',
  813. 'text-blue-400': '#60a5fa',
  814. 'text-green-400': '#4ade80',
  815. };
  816. const fillColor = colorMap[color] || '#888';
  817. // Glow style when heating
  818. const glowStyle = isHeating ? {
  819. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  820. } : {};
  821. if (isHeating) {
  822. // Filled thermometer with glow - heater is ON
  823. return (
  824. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  825. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  826. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  827. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke={fillColor} strokeWidth="1" fill="none"/>
  828. </svg>
  829. );
  830. }
  831. // Empty thermometer - heater is OFF
  832. return (
  833. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  834. <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"/>
  835. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  836. </svg>
  837. );
  838. }
  839. // AMS Filament Backup tri-state indicator + toggle.
  840. // state=true → ON, click to disable
  841. // state=false → OFF, click opens modal
  842. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  843. interface AmsBackupBadgeProps {
  844. state: boolean | null;
  845. onClick: () => void;
  846. }
  847. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  848. const { t } = useTranslation();
  849. const known = state !== null;
  850. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  851. let title: string;
  852. if (state === true) {
  853. className += known
  854. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  855. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  856. title = t('printers.amsBackup.titleOn');
  857. } else if (state === false) {
  858. className += known
  859. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  860. : 'bg-bambu-dark text-bambu-gray cursor-default';
  861. title = t('printers.amsBackup.titleOff');
  862. } else {
  863. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  864. title = t('printers.amsBackup.titleUnknown');
  865. }
  866. return (
  867. <button
  868. type="button"
  869. disabled={!known}
  870. onClick={() => known && onClick()}
  871. className={className}
  872. title={title}
  873. aria-label={title}
  874. >
  875. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  876. </button>
  877. );
  878. }
  879. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  880. // like AmsBackupBadge so the two sit together in the section header, but
  881. // pinned to the right-hand end of the rule: this is a view preference for the
  882. // row, not a property of the printer.
  883. interface ExternalSpoolToggleProps {
  884. hidden: boolean;
  885. onClick: () => void;
  886. }
  887. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  888. const { t } = useTranslation();
  889. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  890. return (
  891. <button
  892. type="button"
  893. onClick={onClick}
  894. aria-pressed={hidden}
  895. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  896. hidden
  897. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  898. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  899. }`}
  900. title={title}
  901. aria-label={title}
  902. >
  903. {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)]" />}
  904. </button>
  905. );
  906. }
  907. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  908. // Reference: https://github.com/theicedmango/bambu-humidity
  909. interface HumidityIndicatorProps {
  910. humidity: number | string;
  911. goodThreshold?: number; // <= this is green
  912. fairThreshold?: number; // <= this is orange, > is red
  913. onClick?: () => void;
  914. compact?: boolean; // Smaller version for grid layout
  915. }
  916. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  917. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  918. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  919. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  920. // Status thresholds (configurable via settings)
  921. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  922. let textColor: string;
  923. let statusText: string;
  924. if (isNaN(humidityValue)) {
  925. textColor = '#C3C2C1';
  926. statusText = 'Unknown';
  927. } else if (humidityValue <= good) {
  928. textColor = '#22a352'; // Green - Good
  929. statusText = 'Good';
  930. } else if (humidityValue <= fair) {
  931. textColor = '#d4a017'; // Gold - Fair
  932. statusText = 'Fair';
  933. } else {
  934. textColor = '#c62828'; // Red - Bad
  935. statusText = 'Bad';
  936. }
  937. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  938. let DropComponent: React.FC<{ className?: string }>;
  939. if (isNaN(humidityValue)) {
  940. DropComponent = WaterDropEmpty;
  941. } else if (humidityValue <= good) {
  942. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  943. } else if (humidityValue <= fair) {
  944. DropComponent = WaterDropHalf; // Fair - half filled
  945. } else {
  946. DropComponent = WaterDropFull; // Bad - full (too humid)
  947. }
  948. return (
  949. <button
  950. type="button"
  951. onClick={onClick}
  952. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  953. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  954. >
  955. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  956. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  957. </button>
  958. );
  959. }
  960. // Temperature indicator with dynamic icon and coloring
  961. interface TemperatureIndicatorProps {
  962. temp: number;
  963. goodThreshold?: number; // <= this is blue
  964. fairThreshold?: number; // <= this is orange, > is red
  965. onClick?: () => void;
  966. compact?: boolean; // Smaller version for grid layout
  967. }
  968. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  969. // Ensure thresholds are numbers
  970. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  971. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  972. let textColor: string;
  973. let statusText: string;
  974. let ThermoComponent: React.FC<{ className?: string }>;
  975. if (temp <= good) {
  976. textColor = '#22a352'; // Green - good (same as humidity)
  977. statusText = 'Good';
  978. ThermoComponent = ThermometerEmpty;
  979. } else if (temp <= fair) {
  980. textColor = '#d4a017'; // Gold - fair (same as humidity)
  981. statusText = 'Fair';
  982. ThermoComponent = ThermometerHalf;
  983. } else {
  984. textColor = '#c62828'; // Red - bad (same as humidity)
  985. statusText = 'Bad';
  986. ThermoComponent = ThermometerFull;
  987. }
  988. return (
  989. <button
  990. type="button"
  991. onClick={onClick}
  992. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  993. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  994. >
  995. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  996. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  997. </button>
  998. );
  999. }
  1000. // How long to wait for an AMS to report a live drying cycle after the printer
  1001. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  1002. // within a couple of seconds; 30s covers the slowest observed push cadence
  1003. // without leaving the user waiting on a verdict.
  1004. const DRY_START_CONFIRM_MS = 30_000;
  1005. export function CoverImage({
  1006. url,
  1007. printName,
  1008. className = 'w-20 h-20',
  1009. radiusClass = 'rounded-lg',
  1010. }: {
  1011. url: string | null;
  1012. printName?: string;
  1013. className?: string;
  1014. radiusClass?: string;
  1015. }) {
  1016. const { t } = useTranslation();
  1017. const [loaded, setLoaded] = useState(false);
  1018. const [error, setError] = useState(false);
  1019. const [showOverlay, setShowOverlay] = useState(false);
  1020. const imgRef = useRef<HTMLImageElement>(null);
  1021. // Cache-bust the image URL when the print name changes so the browser
  1022. // fetches the new cover instead of serving the stale cached image.
  1023. const cacheBustedUrl = useMemo(() => {
  1024. if (!url) return null;
  1025. const sep = url.includes('?') ? '&' : '?';
  1026. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1027. }, [url, printName]);
  1028. // Re-evaluate load state when the image URL changes, and ask the element
  1029. // whether it is already showing something rather than assuming it is not.
  1030. //
  1031. // `onLoad` used to be the only thing that could set `loaded`, and this
  1032. // effect reset it to false unconditionally. That is right when the URL
  1033. // really changes, but it also runs on mount — and the two are not the same
  1034. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1035. // constant for the duration of a print, so navigating away from the
  1036. // printers page and back re-mounts with a byte-identical src that the
  1037. // browser serves from its in-memory cache. The `load` event for a cache hit
  1038. // and React's passive-effect flush are both plain tasks with no ordering
  1039. // between them, so when `load` won, this effect ran afterwards and undid
  1040. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1041. // sat there until a full reload. Nothing recovered it, because the URL
  1042. // never changes again during the print and so this effect never re-runs.
  1043. //
  1044. // Being a race, it reproduced every time for #2826's reporter and not at
  1045. // all here, which is also why the network panel showed no request: there
  1046. // was no request to show.
  1047. //
  1048. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1049. // which of the two ran first. It is also correct for the case the reporter
  1050. // proposed (a `load` that fires before React's handler is live), so the
  1051. // fix stands whichever mechanism is really at work.
  1052. useEffect(() => {
  1053. setError(false);
  1054. const el = imgRef.current;
  1055. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1056. }, [cacheBustedUrl]);
  1057. return (
  1058. <>
  1059. <div
  1060. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1061. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1062. >
  1063. {cacheBustedUrl && !error ? (
  1064. <>
  1065. <img
  1066. ref={imgRef}
  1067. src={cacheBustedUrl}
  1068. alt={t('printers.printPreview')}
  1069. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1070. onLoad={() => setLoaded(true)}
  1071. onError={() => setError(true)}
  1072. />
  1073. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1074. </>
  1075. ) : (
  1076. <Box className="w-8 h-8 text-bambu-gray" />
  1077. )}
  1078. </div>
  1079. {/* Cover Image Overlay */}
  1080. {showOverlay && cacheBustedUrl && (
  1081. <div
  1082. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1083. onClick={() => setShowOverlay(false)}
  1084. >
  1085. <div className="relative max-w-2xl max-h-full">
  1086. <img
  1087. src={cacheBustedUrl}
  1088. alt={t('printers.printPreview')}
  1089. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1090. />
  1091. {printName && (
  1092. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1093. )}
  1094. </div>
  1095. </div>
  1096. )}
  1097. </>
  1098. );
  1099. }
  1100. interface PrinterMaintenanceInfo {
  1101. due_count: number;
  1102. warning_count: number;
  1103. total_print_hours: number;
  1104. }
  1105. // Status summary bar component - uses queryClient to read cached statuses
  1106. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1107. const { t } = useTranslation();
  1108. const queryClient = useQueryClient();
  1109. // Subscribe to query cache changes to re-render when status updates
  1110. // Throttled to prevent rapid re-renders from causing tab crashes
  1111. const [cacheTick, setCacheTick] = useState(0);
  1112. useEffect(() => {
  1113. let pending = false;
  1114. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1115. if (!pending) {
  1116. pending = true;
  1117. requestAnimationFrame(() => {
  1118. setCacheTick(t => t + 1);
  1119. pending = false;
  1120. });
  1121. }
  1122. });
  1123. return () => unsubscribe();
  1124. }, [queryClient]);
  1125. const { counts, nextFinish } = useMemo(() => {
  1126. let printing = 0;
  1127. let paused = 0;
  1128. let finished = 0;
  1129. let idle = 0;
  1130. let offline = 0;
  1131. let loading = 0;
  1132. let error = 0;
  1133. let nextPrinterName: string | null = null;
  1134. let nextRemainingMin: number | null = null;
  1135. let nextProgress: number = 0;
  1136. printers?.forEach((printer) => {
  1137. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1138. if (status === undefined) {
  1139. // Status not yet loaded - don't count as offline yet
  1140. loading++;
  1141. } else if (!status.connected) {
  1142. offline++;
  1143. } else {
  1144. // Count printers with active HMS errors as problems
  1145. const knownHmsCount =
  1146. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1147. if (knownHmsCount > 0) {
  1148. error++;
  1149. }
  1150. switch (status.state) {
  1151. case 'RUNNING':
  1152. printing++;
  1153. if (status.remaining_time != null && status.remaining_time > 0) {
  1154. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1155. nextRemainingMin = status.remaining_time;
  1156. nextPrinterName = printer.name;
  1157. nextProgress = status.progress || 0;
  1158. }
  1159. }
  1160. break;
  1161. case 'PAUSE':
  1162. paused++;
  1163. break;
  1164. case 'FINISH':
  1165. finished++;
  1166. break;
  1167. case 'FAILED':
  1168. // FAILED is the printer's terminal gcode_state after a print stops —
  1169. // including user cancellations, where there's no actual fault. Only
  1170. // count it as a "problem" when an HMS error is also active; otherwise
  1171. // it's just a print that ended unsuccessfully and the plate needs
  1172. // clearing (same as FINISH from the operator's perspective).
  1173. if (knownHmsCount > 0) {
  1174. // Already counted above
  1175. } else {
  1176. finished++;
  1177. }
  1178. break;
  1179. default:
  1180. idle++;
  1181. break;
  1182. }
  1183. }
  1184. });
  1185. return {
  1186. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1187. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1188. };
  1189. // eslint-disable-next-line react-hooks/exhaustive-deps
  1190. }, [printers, queryClient, cacheTick]);
  1191. if (!printers?.length) return null;
  1192. const badges: { count: number; dot: string; label: string }[] = [
  1193. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1194. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1195. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1196. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1197. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1198. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1199. ];
  1200. return (
  1201. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1202. {badges.map(({ count, dot, label }) => count > 0 && (
  1203. <div key={label} className="flex items-center gap-1.5">
  1204. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1205. <span className="text-bambu-gray">
  1206. <span className="text-white font-medium">{count}</span> {label}
  1207. </span>
  1208. </div>
  1209. ))}
  1210. {nextFinish && (
  1211. <>
  1212. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1213. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1214. <div className="flex items-center gap-2">
  1215. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1216. <span className="text-white font-medium">{nextFinish.name}</span>
  1217. </div>
  1218. <div className="flex items-center gap-2 w-full sm:w-auto">
  1219. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1220. <div
  1221. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1222. style={{ width: `${nextFinish.progress}%` }}
  1223. />
  1224. </div>
  1225. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1226. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1227. </div>
  1228. </div>
  1229. </>
  1230. )}
  1231. </div>
  1232. );
  1233. }
  1234. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1235. type ViewMode = 'expanded' | 'compact';
  1236. type ToolbarDropdownOption<T extends string> = {
  1237. value: T;
  1238. label: string;
  1239. };
  1240. function ToolbarDropdown<T extends string>({
  1241. value,
  1242. options,
  1243. onChange,
  1244. fullWidth = false,
  1245. }: {
  1246. value: T;
  1247. options: ToolbarDropdownOption<T>[];
  1248. onChange: (value: T) => void;
  1249. fullWidth?: boolean;
  1250. }) {
  1251. const [isOpen, setIsOpen] = useState(false);
  1252. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1253. return (
  1254. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1255. <button
  1256. type="button"
  1257. onClick={() => setIsOpen(open => !open)}
  1258. 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'}`}
  1259. >
  1260. <span className="truncate">{selectedOption?.label}</span>
  1261. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1262. </button>
  1263. {isOpen && (
  1264. <>
  1265. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1266. <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">
  1267. {options.map(option => (
  1268. <button
  1269. key={option.value}
  1270. type="button"
  1271. onClick={() => {
  1272. onChange(option.value);
  1273. setIsOpen(false);
  1274. }}
  1275. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1276. option.value === value ? 'text-bambu-green' : 'text-white'
  1277. }`}
  1278. >
  1279. {option.label}
  1280. </button>
  1281. ))}
  1282. </div>
  1283. </>
  1284. )}
  1285. </div>
  1286. );
  1287. }
  1288. function ToolbarMenu({
  1289. label,
  1290. icon,
  1291. children,
  1292. }: {
  1293. label: string;
  1294. icon: React.ReactNode;
  1295. children: React.ReactNode;
  1296. }) {
  1297. const [isOpen, setIsOpen] = useState(false);
  1298. return (
  1299. <div className="relative">
  1300. <button
  1301. type="button"
  1302. onClick={() => setIsOpen(open => !open)}
  1303. 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"
  1304. aria-label={label}
  1305. title={label}
  1306. >
  1307. {icon}
  1308. </button>
  1309. {isOpen && (
  1310. <>
  1311. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1312. <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">
  1313. {children}
  1314. </div>
  1315. </>
  1316. )}
  1317. </div>
  1318. );
  1319. }
  1320. function IndicatorControlPopover({
  1321. title,
  1322. options = [],
  1323. unit,
  1324. customMin,
  1325. customMax,
  1326. customStep = 1,
  1327. widthClass = 'w-[240px]',
  1328. popoverWidth = 240,
  1329. popoverHeight = 280,
  1330. isPending,
  1331. onClose,
  1332. onSubmit,
  1333. children,
  1334. }: {
  1335. title: string;
  1336. options?: Array<{ label: string; value: number }>;
  1337. unit?: string;
  1338. customMin?: number;
  1339. customMax?: number;
  1340. customStep?: number;
  1341. widthClass?: string;
  1342. popoverWidth?: number;
  1343. popoverHeight?: number;
  1344. isPending?: boolean;
  1345. onClose: () => void;
  1346. onSubmit?: (value: number) => void;
  1347. children?: React.ReactNode;
  1348. }) {
  1349. const anchorRef = useRef<HTMLSpanElement>(null);
  1350. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1351. const [customValue, setCustomValue] = useState('');
  1352. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1353. // can position via fixed coords. Portaling to document.body escapes
  1354. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1355. // own contexts and would otherwise cover the popover even at z-[60].
  1356. useLayoutEffect(() => {
  1357. const trigger = anchorRef.current?.parentElement;
  1358. if (!trigger) return;
  1359. const measure = () => {
  1360. const rect = trigger.getBoundingClientRect();
  1361. setCoords(computePopoverPosition({
  1362. triggerRect: rect,
  1363. popoverWidth,
  1364. estimatedHeight: popoverHeight,
  1365. horizontalAlign: 'center',
  1366. }));
  1367. };
  1368. measure();
  1369. window.addEventListener('resize', measure);
  1370. window.addEventListener('scroll', measure, true);
  1371. return () => {
  1372. window.removeEventListener('resize', measure);
  1373. window.removeEventListener('scroll', measure, true);
  1374. };
  1375. }, [popoverWidth, popoverHeight]);
  1376. const showCustomInput = unit !== undefined;
  1377. const submitCustom = () => {
  1378. const value = Number(customValue);
  1379. if (!Number.isFinite(value)) return;
  1380. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1381. onSubmit?.(Math.round(bounded));
  1382. };
  1383. return (
  1384. <>
  1385. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1386. {createPortal(
  1387. <>
  1388. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1389. <div
  1390. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1391. style={{
  1392. top: coords?.top ?? -9999,
  1393. left: coords?.left ?? -9999,
  1394. visibility: coords ? 'visible' : 'hidden',
  1395. }}
  1396. onClick={e => e.stopPropagation()}
  1397. >
  1398. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1399. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1400. {options.length > 0 && (
  1401. <div className="px-3 py-2.5">
  1402. <div className="grid grid-cols-2 gap-1.5">
  1403. {options.map(option => (
  1404. <button
  1405. key={`${option.label}-${option.value}`}
  1406. type="button"
  1407. disabled={isPending}
  1408. onClick={() => onSubmit?.(option.value)}
  1409. 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"
  1410. >
  1411. {option.label}
  1412. </button>
  1413. ))}
  1414. </div>
  1415. </div>
  1416. )}
  1417. {children}
  1418. {showCustomInput && (
  1419. <>
  1420. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1421. <form
  1422. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1423. onSubmit={(e) => {
  1424. e.preventDefault();
  1425. submitCustom();
  1426. }}
  1427. >
  1428. <input
  1429. type="number"
  1430. min={customMin}
  1431. max={customMax}
  1432. step={customStep}
  1433. value={customValue}
  1434. onChange={e => setCustomValue(e.target.value)}
  1435. placeholder="Custom"
  1436. 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"
  1437. />
  1438. <button
  1439. type="submit"
  1440. disabled={isPending || customValue.trim() === ''}
  1441. 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"
  1442. >
  1443. Set
  1444. </button>
  1445. </form>
  1446. </>
  1447. )}
  1448. </div>
  1449. </>,
  1450. document.body
  1451. )}
  1452. </>
  1453. );
  1454. }
  1455. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1456. function NozzleTemperatureControlBox({
  1457. label,
  1458. current,
  1459. target,
  1460. isActive,
  1461. isPending,
  1462. onSubmit,
  1463. options = NOZZLE_TEMPERATURE_OPTIONS,
  1464. }: {
  1465. label: string;
  1466. current?: number;
  1467. target?: number;
  1468. isActive: boolean;
  1469. isPending?: boolean;
  1470. onSubmit: (value: number) => void;
  1471. options?: Array<{ label: string; value: number }>;
  1472. }) {
  1473. const [customValue, setCustomValue] = useState('');
  1474. const submitCustom = () => {
  1475. const value = Number(customValue);
  1476. if (!Number.isFinite(value)) return;
  1477. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1478. };
  1479. return (
  1480. <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'}`}>
  1481. <div className="mb-1.5 flex items-center justify-between gap-2">
  1482. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1483. <span className="text-[10px] text-bambu-gray">
  1484. {Math.round(current ?? 0)}°C
  1485. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1486. </span>
  1487. </div>
  1488. <div className="grid grid-cols-2 gap-1">
  1489. {options.map(option => (
  1490. <button
  1491. key={`${label}-${option.value}`}
  1492. type="button"
  1493. disabled={isPending}
  1494. onClick={() => onSubmit(option.value)}
  1495. 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"
  1496. >
  1497. {option.label}
  1498. </button>
  1499. ))}
  1500. </div>
  1501. <form
  1502. className="mt-1.5 flex gap-1"
  1503. onSubmit={(e) => {
  1504. e.preventDefault();
  1505. submitCustom();
  1506. }}
  1507. >
  1508. <input
  1509. type="number"
  1510. min={0}
  1511. max={320}
  1512. step={1}
  1513. value={customValue}
  1514. onChange={e => setCustomValue(e.target.value)}
  1515. placeholder="Custom"
  1516. 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"
  1517. />
  1518. <button
  1519. type="submit"
  1520. disabled={isPending || customValue.trim() === ''}
  1521. 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"
  1522. >
  1523. Set
  1524. </button>
  1525. </form>
  1526. </div>
  1527. );
  1528. }
  1529. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1530. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1531. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1532. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1533. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1534. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1535. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1536. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1537. };
  1538. /** Classify a printer into one of the UI status buckets. */
  1539. function classifyPrinterStatus(
  1540. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1541. ): PrinterState {
  1542. if (!status?.connected) return 'offline';
  1543. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1544. if (hmsErrors.length > 0) return 'error';
  1545. switch (status.state) {
  1546. case 'RUNNING': return 'printing';
  1547. case 'PAUSE': return 'paused';
  1548. case 'FINISH': return 'finished';
  1549. // FAILED without an active HMS error is the printer's terminal state after
  1550. // any unsuccessful end — including user-cancellations. Treat the same as
  1551. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1552. // HMS code is actually attached (handled by the early-return above).
  1553. case 'FAILED': return 'finished';
  1554. default: return 'idle';
  1555. }
  1556. }
  1557. /**
  1558. * Get human-readable status display text for a printer.
  1559. * Uses stg_cur_name for detailed calibration/preparation stages,
  1560. * otherwise formats the gcode_state nicely.
  1561. */
  1562. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1563. // If we have a specific stage name (calibration, heating, etc.), use it
  1564. if (stg_cur_name) {
  1565. return stg_cur_name;
  1566. }
  1567. // Format the gcode_state nicely
  1568. switch (state) {
  1569. case 'RUNNING':
  1570. return 'Printing';
  1571. case 'PAUSE':
  1572. return 'Paused';
  1573. case 'FINISH':
  1574. return 'Finished';
  1575. case 'FAILED':
  1576. return 'Failed';
  1577. case 'IDLE':
  1578. return 'Idle';
  1579. default:
  1580. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1581. }
  1582. }
  1583. // Bambu models that ship with an enclosure chamber fan (firmware field
  1584. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1585. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1586. // widget is hidden in fanItems instead of rendered greyed-out.
  1587. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1588. 'X1C',
  1589. 'X1',
  1590. 'X1E',
  1591. 'X2D',
  1592. 'P1S',
  1593. 'P2S',
  1594. 'H2D',
  1595. 'H2D Pro',
  1596. 'H2C',
  1597. 'H2S',
  1598. ]);
  1599. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1600. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1601. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1602. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1603. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1604. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1605. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1606. 'P2S',
  1607. 'X2D',
  1608. ]);
  1609. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1610. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1611. // • User-defined friendly name (editable, protected by printers:update)
  1612. // • AMS serial number
  1613. // • AMS firmware version
  1614. export function AmsNameHoverCard({
  1615. ams,
  1616. printerId,
  1617. label,
  1618. amsLabels,
  1619. canEdit,
  1620. onSaved,
  1621. children,
  1622. }: {
  1623. ams: import('../api/client').AMSUnit;
  1624. printerId: number;
  1625. label: string; // auto-generated label, e.g. "AMS-A"
  1626. amsLabels?: Record<number, string>;
  1627. canEdit: boolean;
  1628. onSaved: () => void;
  1629. children: React.ReactNode;
  1630. }) {
  1631. const { t } = useTranslation();
  1632. const [isVisible, setIsVisible] = useState(false);
  1633. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1634. const [editValue, setEditValue] = useState('');
  1635. const [isSaving, setIsSaving] = useState(false);
  1636. const [saveError, setSaveError] = useState<string | null>(null);
  1637. const [isInputFocused, setIsInputFocused] = useState(false);
  1638. const triggerRef = useRef<HTMLDivElement>(null);
  1639. const cardRef = useRef<HTMLDivElement>(null);
  1640. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1641. useEffect(() => {
  1642. if (isVisible) {
  1643. setEditValue(amsLabels?.[ams.id] ?? '');
  1644. setSaveError(null);
  1645. requestAnimationFrame(() => {
  1646. if (triggerRef.current && cardRef.current) {
  1647. const rect = triggerRef.current.getBoundingClientRect();
  1648. const spaceAbove = rect.top - 56;
  1649. const spaceBelow = window.innerHeight - rect.bottom;
  1650. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1651. }
  1652. });
  1653. }
  1654. }, [isVisible, amsLabels, ams.id]);
  1655. const handleMouseEnter = () => {
  1656. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1657. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1658. };
  1659. const handleMouseLeave = () => {
  1660. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1661. if (!isInputFocused) {
  1662. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1663. }
  1664. };
  1665. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1666. const handleSave = async () => {
  1667. if (!canEdit) return;
  1668. setIsSaving(true);
  1669. setSaveError(null);
  1670. try {
  1671. const trimmed = editValue.trim();
  1672. if (trimmed) {
  1673. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1674. } else {
  1675. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1676. }
  1677. onSaved();
  1678. setIsVisible(false);
  1679. } catch (err) {
  1680. setSaveError(err instanceof Error ? err.message : String(err));
  1681. } finally {
  1682. setIsSaving(false);
  1683. }
  1684. };
  1685. const handleClear = async () => {
  1686. if (!canEdit) return;
  1687. setIsSaving(true);
  1688. setSaveError(null);
  1689. try {
  1690. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1691. onSaved();
  1692. setIsVisible(false);
  1693. } catch (err) {
  1694. setSaveError(err instanceof Error ? err.message : String(err));
  1695. } finally {
  1696. setIsSaving(false);
  1697. }
  1698. };
  1699. return (
  1700. <div
  1701. ref={triggerRef}
  1702. className="relative inline-block"
  1703. onMouseEnter={handleMouseEnter}
  1704. onMouseLeave={handleMouseLeave}
  1705. >
  1706. {children}
  1707. {isVisible && (
  1708. <div
  1709. ref={cardRef}
  1710. className={`
  1711. absolute left-0 z-50
  1712. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1713. animate-in fade-in-0 zoom-in-95 duration-150
  1714. `}
  1715. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1716. onMouseEnter={handleMouseEnter}
  1717. onMouseLeave={handleMouseLeave}
  1718. >
  1719. <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">
  1720. {/* AMS auto-label */}
  1721. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1722. {/* Serial number */}
  1723. <div className="flex items-center justify-between gap-2">
  1724. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1725. {t('printers.amsPopup.serialNumber')}
  1726. </span>
  1727. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1728. </div>
  1729. {/* Firmware version */}
  1730. <div className="flex items-center justify-between gap-2">
  1731. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1732. {t('printers.amsPopup.firmwareVersion')}
  1733. </span>
  1734. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1735. </div>
  1736. {/* Friendly name editor */}
  1737. <div className="space-y-1">
  1738. <div className="flex items-center gap-2">
  1739. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1740. {t('printers.amsPopup.friendlyName')}
  1741. </span>
  1742. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1743. </div>
  1744. <input
  1745. type="text"
  1746. value={editValue}
  1747. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1748. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1749. onFocus={() => setIsInputFocused(true)}
  1750. onBlur={() => {
  1751. setIsInputFocused(false);
  1752. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1753. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1754. }}
  1755. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1756. disabled={!canEdit}
  1757. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1758. 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"
  1759. maxLength={100}
  1760. />
  1761. {canEdit && (
  1762. <div className="space-y-1">
  1763. {saveError && (
  1764. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1765. )}
  1766. <div className="flex gap-1 justify-end">
  1767. <button
  1768. onClick={handleSave}
  1769. disabled={isSaving}
  1770. 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"
  1771. >
  1772. {t('printers.amsPopup.save')}
  1773. </button>
  1774. {amsLabels?.[ams.id] && (
  1775. <button
  1776. onClick={handleClear}
  1777. disabled={isSaving}
  1778. 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"
  1779. >
  1780. {t('printers.amsPopup.clear')}
  1781. </button>
  1782. )}
  1783. </div>
  1784. </div>
  1785. )}
  1786. </div>
  1787. </div>
  1788. </div>
  1789. )}
  1790. </div>
  1791. );
  1792. }
  1793. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1794. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1795. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1796. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1797. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1798. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1799. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1800. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1801. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1802. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1803. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1804. };
  1805. // How much the printer card's body type and icons grow at each card size
  1806. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1807. // 1.0 and an existing install looks identical until the user picks L or XL --
  1808. // the same control the request asked to have this follow.
  1809. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1810. // The scaled sizes, handed to the card subtree as custom properties. Every
  1811. // converted class names its old fixed value as the fallback, so anything that
  1812. // renders outside a card root -- the portalled temperature popover -- keeps
  1813. // exactly the size it has today.
  1814. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1815. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1816. // Rounded to a tenth so the values stay readable in devtools.
  1817. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1818. return {
  1819. '--pc-t8': px(8),
  1820. '--pc-t9': px(9),
  1821. '--pc-t10': px(10),
  1822. '--pc-t11': px(11),
  1823. '--pc-i2': px(8),
  1824. '--pc-i25': px(10),
  1825. '--pc-i3': px(12),
  1826. '--pc-i35': px(14),
  1827. '--pc-i4': px(16),
  1828. '--pc-i5': px(20),
  1829. '--pc-i7': px(28),
  1830. } as React.CSSProperties;
  1831. }
  1832. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1833. const { t } = useTranslation();
  1834. const queryClient = useQueryClient();
  1835. const { showToast } = useToast();
  1836. // One fleet-wide query shared by every card, not one per card: the list is
  1837. // nearly always empty and a 20-printer fleet would otherwise make 20
  1838. // requests every 30s. React Query dedupes on the key.
  1839. const { data: scheduled = [] } = useQuery({
  1840. queryKey: SCHEDULED_DRYINGS_KEY,
  1841. queryFn: () => api.listScheduledDryings(),
  1842. refetchInterval: 30_000,
  1843. });
  1844. // The live AMS status reports a starting cycle well before the next poll;
  1845. // refetch so a just-dispatched schedule doesn't linger as pending.
  1846. useEffect(() => {
  1847. if (dryingActive) {
  1848. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1849. }
  1850. }, [dryingActive, queryClient]);
  1851. const cancelMutation = useMutation({
  1852. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1853. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1854. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1855. });
  1856. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1857. // old firmware on a printer that was offline at schedule time), and without
  1858. // this the run just vanishes with only the backend log saying why.
  1859. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1860. if (rows.length === 0) return null;
  1861. return (
  1862. <div className="mt-2 space-y-1">
  1863. {rows.map(s => {
  1864. const failed = s.status === 'failed';
  1865. const reasonKey = waitingReasonKey(s.waiting_reason);
  1866. const failedKey = failedReasonKey(s.error_code);
  1867. return (
  1868. <div
  1869. key={s.id}
  1870. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1871. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1872. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1873. }`}
  1874. >
  1875. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1876. {failed ? (
  1877. t('printers.drying.scheduleFailedReason', {
  1878. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1879. })
  1880. ) : (
  1881. <>
  1882. {s.start_after
  1883. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1884. : t('printers.drying.scheduledAsap')}
  1885. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1886. </>
  1887. )}
  1888. </span>
  1889. <button
  1890. onClick={() => cancelMutation.mutate(s.id)}
  1891. disabled={cancelMutation.isPending}
  1892. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1893. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1894. >
  1895. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1896. </button>
  1897. </div>
  1898. );
  1899. })}
  1900. </div>
  1901. );
  1902. }
  1903. function PrinterCard({
  1904. printer,
  1905. hideIfDisconnected,
  1906. maintenanceInfo,
  1907. viewMode = 'expanded',
  1908. cardSize = 2,
  1909. amsThresholds,
  1910. spoolmanEnabled = false,
  1911. linkedSpools,
  1912. spoolmanUrl,
  1913. spoolmanSyncMode,
  1914. onGetAssignment,
  1915. onUnassignSpool,
  1916. spoolmanSpools,
  1917. spoolmanSlotAssignments,
  1918. spoolmanLoading = false,
  1919. onUnassignSpoolmanSpool,
  1920. timeFormat = 'system',
  1921. cameraViewMode = 'window',
  1922. onOpenEmbeddedCamera,
  1923. onSelectCameraViewMode,
  1924. checkPrinterFirmware = true,
  1925. dryingPresets = DRYING_PRESETS,
  1926. requirePlateClear = false,
  1927. selectionMode = false,
  1928. isSelected = false,
  1929. onToggleSelect,
  1930. onOpenCompactCard,
  1931. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1932. bedTempPresets = BED_TEMP_DEFAULTS,
  1933. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1934. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1935. aiDetectionEnabled = false,
  1936. aiDetection,
  1937. aiLastError = null,
  1938. }: {
  1939. printer: Printer;
  1940. hideIfDisconnected?: boolean;
  1941. maintenanceInfo?: PrinterMaintenanceInfo;
  1942. viewMode?: ViewMode;
  1943. cardSize?: number;
  1944. amsThresholds?: {
  1945. humidityGood: number;
  1946. humidityFair: number;
  1947. tempGood: number;
  1948. tempFair: number;
  1949. };
  1950. spoolmanEnabled?: boolean;
  1951. hasUnlinkedSpools?: boolean;
  1952. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1953. spoolmanUrl?: string | null;
  1954. spoolmanSyncMode?: string | null;
  1955. spoolAssignments?: SpoolAssignment[];
  1956. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1957. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1958. spoolmanSpools?: InventorySpool[];
  1959. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1960. spoolmanLoading?: boolean;
  1961. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1962. timeFormat?: 'system' | '12h' | '24h';
  1963. cameraViewMode?: CameraViewMode;
  1964. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1965. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  1966. checkPrinterFirmware?: boolean;
  1967. dryingPresets?: Record<string, DryingPreset>;
  1968. requirePlateClear?: boolean;
  1969. selectionMode?: boolean;
  1970. isSelected?: boolean;
  1971. onToggleSelect?: (id: number) => void;
  1972. onOpenCompactCard?: (id: number) => void;
  1973. nozzleTempPresets?: readonly [number, number, number];
  1974. bedTempPresets?: readonly [number, number, number];
  1975. chamberTempPresets?: readonly [number, number, number];
  1976. fanSpeedPresets?: readonly [number, number, number];
  1977. aiDetectionEnabled?: boolean;
  1978. aiDetection?: AiDetection;
  1979. aiLastError?: string | null;
  1980. }) {
  1981. const { t } = useTranslation();
  1982. const queryClient = useQueryClient();
  1983. const navigate = useNavigate();
  1984. const { showToast } = useToast();
  1985. const { hasPermission, canModify, authEnabled, isAdmin } = useAuth();
  1986. const [showMenu, setShowMenu] = useState(false);
  1987. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1988. const [deleteArchives, setDeleteArchives] = useState(true);
  1989. const [showEditModal, setShowEditModal] = useState(false);
  1990. const [showFileManager, setShowFileManager] = useState(false);
  1991. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1992. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1993. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1994. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1995. const [showHMSModal, setShowHMSModal] = useState(false);
  1996. // #1546: AI failure detection modal — opens from the AI badge.
  1997. const [showAiModal, setShowAiModal] = useState(false);
  1998. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1999. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  2000. // External spool visibility (#1782) — browser-local, per printer. Read once
  2001. // per card; the toggle that writes it is the only thing that changes it.
  2002. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2003. isExternalSpoolHidden(printer.id),
  2004. );
  2005. const toggleExternalSpool = useCallback(() => {
  2006. setExternalSpoolHidden((prev) => {
  2007. const next = !prev;
  2008. persistExternalSpoolHidden(printer.id, next);
  2009. return next;
  2010. });
  2011. }, [printer.id]);
  2012. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2013. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2014. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2015. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2016. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2017. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2018. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2019. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2020. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2021. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2022. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2023. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2024. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2025. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2026. // AMS drying popover state: which AMS unit has the popover open
  2027. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2028. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2029. const [dryingFilament, setDryingFilament] = useState('PLA');
  2030. const [dryingTemp, setDryingTemp] = useState(50);
  2031. const [dryingDuration, setDryingDuration] = useState(4);
  2032. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2033. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2034. // go through scheduleDryingMutation.
  2035. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2036. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2037. const [dryingStartAt, setDryingStartAt] = useState('');
  2038. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2039. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2040. // Reset every field the popover owns, including the start mode. Leaving the
  2041. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2042. // the next open, by then in the past, and the POST rejected it.
  2043. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2044. const firstTray = ams.tray.find(t => t.tray_type);
  2045. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2046. // Only reachable if a custom preset set dropped PLA itself.
  2047. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2048. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2049. setDryingFilament(filType);
  2050. setDryingTemp(preset[moduleType] || preset.n3f);
  2051. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2052. setDryingRotateTray(false);
  2053. setDryingStartMode('now');
  2054. setDryingDelayMinutes(120);
  2055. setDryingStartAt('');
  2056. setDryingPopoverModuleType(ams.module_type);
  2057. setDryingPopoverAmsId(ams.id);
  2058. setDryingPopoverAnchor(trigger);
  2059. }, [dryingPresets]);
  2060. // Re-measure on resize/scroll so the popover and its arrow track the
  2061. // flame button, like IndicatorControlPopover.
  2062. useLayoutEffect(() => {
  2063. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2064. const measure = () => {
  2065. setDryingPopoverPos(computePopoverPosition({
  2066. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2067. popoverWidth: DRYING_POPOVER_WIDTH,
  2068. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2069. horizontalAlign: 'center',
  2070. }));
  2071. };
  2072. measure();
  2073. window.addEventListener('resize', measure);
  2074. window.addEventListener('scroll', measure, true);
  2075. return () => {
  2076. window.removeEventListener('resize', measure);
  2077. window.removeEventListener('scroll', measure, true);
  2078. };
  2079. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2080. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2081. // Whether the click hitting the backdrop is the one that dismissed the
  2082. // native datetime picker (see the backdrop's onMouseDown).
  2083. const dryingBackdropSkipCloseRef = useRef(false);
  2084. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2085. // an object rather than a bare id so restarting drying on the SAME unit produces
  2086. // a new identity and rearms the timeout below.
  2087. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2088. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2089. const [isDropUploading, setIsDropUploading] = useState(false);
  2090. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2091. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2092. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2093. // inside the card would have to open upward into the card body; anchored to
  2094. // the viewport it escapes the card and the grid's scroll container both.
  2095. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2096. const dragCounterRef = useRef(0);
  2097. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2098. amsId: number;
  2099. amsLabel: string;
  2100. mode: 'humidity' | 'temperature';
  2101. } | null>(null);
  2102. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2103. initialKind: HeaterSensorKind;
  2104. availableKinds: HeaterSensorKind[];
  2105. } | null>(null);
  2106. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2107. tagUid: string;
  2108. trayUuid: string;
  2109. printerId: number;
  2110. amsId: number;
  2111. trayId: number;
  2112. } | null>(null);
  2113. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2114. printerId: number;
  2115. amsId: number;
  2116. trayId: number;
  2117. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2118. } | null>(null);
  2119. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2120. amsId: number;
  2121. trayId: number;
  2122. trayType?: string;
  2123. trayColor?: string;
  2124. traySubBrands?: string;
  2125. trayInfoIdx?: string;
  2126. extruderId?: number;
  2127. caliIdx?: number | null;
  2128. savedPresetId?: string;
  2129. } | null>(null);
  2130. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2131. const [plateCheckResult, setPlateCheckResult] = useState<{
  2132. is_empty: boolean;
  2133. confidence: number;
  2134. difference_percent: number;
  2135. message: string;
  2136. debug_image_url?: string;
  2137. needs_calibration: boolean;
  2138. failure_reason?: string | null;
  2139. light_warning?: boolean;
  2140. reference_count?: number;
  2141. max_references?: number;
  2142. roi?: { x: number; y: number; w: number; h: number };
  2143. } | null>(null);
  2144. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2145. const [isCalibrating, setIsCalibrating] = useState(false);
  2146. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2147. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2148. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2149. const { data: status } = useQuery({
  2150. queryKey: ['printerStatus', printer.id],
  2151. queryFn: () => api.getPrinterStatus(printer.id),
  2152. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2153. });
  2154. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2155. const { data: firmwareInfo } = useQuery({
  2156. queryKey: ['firmwareUpdate', printer.id],
  2157. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2158. staleTime: 5 * 60 * 1000,
  2159. refetchInterval: 5 * 60 * 1000,
  2160. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2161. });
  2162. // Collect unique tray_info_idx values for cloud filament info lookup
  2163. const trayInfoIds = useMemo(() => {
  2164. const ids = new Set<string>();
  2165. if (status?.ams) {
  2166. for (const ams of status.ams) {
  2167. for (const tray of ams.tray || []) {
  2168. if (tray.tray_info_idx) {
  2169. ids.add(tray.tray_info_idx);
  2170. }
  2171. }
  2172. }
  2173. }
  2174. for (const vt of status?.vt_tray ?? []) {
  2175. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2176. }
  2177. if (status?.nozzle_rack) {
  2178. for (const slot of status.nozzle_rack) {
  2179. if (slot.filament_id) {
  2180. ids.add(slot.filament_id);
  2181. }
  2182. }
  2183. }
  2184. return Array.from(ids);
  2185. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2186. // Collect loaded filament types for queue widget filtering
  2187. const loadedFilamentTypes = useMemo(() => {
  2188. const types = new Set<string>();
  2189. if (status?.ams) {
  2190. for (const ams of status.ams) {
  2191. for (const tray of ams.tray || []) {
  2192. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2193. }
  2194. }
  2195. }
  2196. for (const vt of status?.vt_tray ?? []) {
  2197. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2198. }
  2199. return types;
  2200. }, [status?.ams, status?.vt_tray]);
  2201. // Collect loaded filament type+color pairs for queue widget override matching
  2202. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2203. const loadedFilaments = useMemo(() => {
  2204. const filaments = new Set<string>();
  2205. if (status?.ams) {
  2206. for (const ams of status.ams) {
  2207. for (const tray of ams.tray || []) {
  2208. if (tray.tray_type && tray.tray_color) {
  2209. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2210. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2211. }
  2212. }
  2213. }
  2214. }
  2215. for (const vt of status?.vt_tray ?? []) {
  2216. if (vt.tray_type && vt.tray_color) {
  2217. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2218. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2219. }
  2220. }
  2221. return filaments;
  2222. }, [status?.ams, status?.vt_tray]);
  2223. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2224. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2225. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2226. const loadedVariants = useMemo(() => {
  2227. const variants = new Set<string>();
  2228. if (status?.ams) {
  2229. for (const ams of status.ams) {
  2230. for (const tray of ams.tray || []) {
  2231. if (tray.tray_type && tray.tray_color) {
  2232. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2233. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2234. }
  2235. }
  2236. }
  2237. }
  2238. for (const vt of status?.vt_tray ?? []) {
  2239. if (vt.tray_type && vt.tray_color) {
  2240. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2241. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2242. }
  2243. }
  2244. return variants;
  2245. }, [status?.ams, status?.vt_tray]);
  2246. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2247. const { data: filamentInfo } = useQuery({
  2248. queryKey: ['filamentInfo', trayInfoIds],
  2249. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2250. enabled: trayInfoIds.length > 0,
  2251. staleTime: 5 * 60 * 1000, // 5 minutes
  2252. });
  2253. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2254. const { data: slotPresets } = useQuery({
  2255. queryKey: ['slotPresets', printer.id],
  2256. queryFn: () => api.getSlotPresets(printer.id),
  2257. staleTime: 2 * 60 * 1000, // 2 minutes
  2258. });
  2259. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2260. // Only queried when there's a running print backed by an archive; shared
  2261. // React Query cache with the Queue / Archives pages keeps it cheap.
  2262. const activeArchiveId =
  2263. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2264. const { data: activeArchivePlates } = useQuery({
  2265. queryKey: ['archive-plates', activeArchiveId],
  2266. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2267. enabled: activeArchiveId != null,
  2268. staleTime: 5 * 60 * 1000,
  2269. });
  2270. const activePlateLabel = (() => {
  2271. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2272. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2273. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2274. })();
  2275. // Fetch user-defined AMS friendly names from the database
  2276. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2277. queryKey: ['amsLabels', printer.id],
  2278. queryFn: () => api.getAmsLabels(printer.id),
  2279. staleTime: 5 * 60 * 1000, // 5 minutes
  2280. });
  2281. // Cache WiFi signal to prevent it disappearing on updates
  2282. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2283. useEffect(() => {
  2284. if (status?.wifi_signal != null) {
  2285. setCachedWifiSignal(status.wifi_signal);
  2286. }
  2287. }, [status?.wifi_signal]);
  2288. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2289. // Cache connected state to prevent flicker when status briefly becomes undefined
  2290. const cachedConnected = useRef<boolean | undefined>(undefined);
  2291. useEffect(() => {
  2292. if (status?.connected !== undefined) {
  2293. cachedConnected.current = status.connected;
  2294. }
  2295. }, [status?.connected]);
  2296. const isConnected = status?.connected ?? cachedConnected.current;
  2297. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2298. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2299. useEffect(() => {
  2300. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2301. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2302. }
  2303. }, [status?.ams_extruder_map]);
  2304. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2305. ? status.ams_extruder_map
  2306. : cachedAmsExtruderMap.current;
  2307. // Same caching for the Filament Track Switch inlet bindings, for the same
  2308. // reason: a partial MQTT frame briefly empties the map and the badges would
  2309. // otherwise blink out.
  2310. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2311. useEffect(() => {
  2312. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2313. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2314. }
  2315. }, [status?.ams_switch_inlet]);
  2316. const ftsInstalled = status?.fila_switch?.installed === true;
  2317. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2318. ? status.ams_switch_inlet
  2319. : cachedAmsSwitchInlet.current;
  2320. // Cache AMS data to prevent it disappearing on idle/offline printers
  2321. const cachedAmsData = useRef<AMSUnit[]>([]);
  2322. useEffect(() => {
  2323. if (status?.ams && status.ams.length > 0) {
  2324. cachedAmsData.current = status.ams;
  2325. }
  2326. }, [status?.ams]);
  2327. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2328. // #2532: the K-profile line only exists on slots the printer has actually
  2329. // calibrated. The AMS units and the external-spool group are flex siblings in
  2330. // one row, so on a card that shows a value anywhere, the slots without one
  2331. // reserve the same height -- otherwise their fill bars sit a line above their
  2332. // neighbours'. A card with no calibrated slot at all is unaffected.
  2333. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2334. || (status?.vt_tray ?? []).some(tray => tray.k);
  2335. // Confirm a drying cycle actually started (#2533). Firmware answers
  2336. // ams_filament_drying with result=success even when it then silently declines,
  2337. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2338. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2339. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2340. // means the printer took the command and dropped it.
  2341. useEffect(() => {
  2342. if (!dryStartWatch) return;
  2343. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2344. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2345. }, [dryStartWatch, amsData]);
  2346. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2347. // otherwise rearm the timeout on every frame, so it would never elapse.
  2348. useEffect(() => {
  2349. if (!dryStartWatch) return;
  2350. const timer = setTimeout(() => {
  2351. setDryStartWatch(null);
  2352. showToast(t('printers.drying.toastNotStarted'), 'error');
  2353. }, DRY_START_CONFIRM_MS);
  2354. return () => clearTimeout(timer);
  2355. }, [dryStartWatch, showToast, t]);
  2356. // Cache tray_now to prevent flickering when undefined values come in
  2357. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2358. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2359. const cachedTrayNow = useRef<number | undefined>(undefined);
  2360. const currentTrayNow = status?.tray_now;
  2361. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2362. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2363. cachedTrayNow.current = currentTrayNow;
  2364. } else if (currentTrayNow === 255) {
  2365. cachedTrayNow.current = undefined;
  2366. }
  2367. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2368. ? currentTrayNow
  2369. : cachedTrayNow.current;
  2370. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2371. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2372. // expectedTray = the slot the firmware now expects filament in
  2373. // previousTray = the slot that ran out
  2374. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2375. // so these are often different — the graphic highlights the expected one.
  2376. const expectedTray = status?.expected_tray ?? null;
  2377. const previousTray = status?.previous_tray ?? null;
  2378. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2379. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2380. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2381. if (globalId === null) return null;
  2382. if (globalId === 254) return t('printers.expectedSlot.external');
  2383. if (globalId >= 128 && globalId <= 135) {
  2384. return amsLabels?.[globalId] || getAmsLabel(globalId);
  2385. }
  2386. const amsId = Math.floor(globalId / 4);
  2387. const slot = globalId % 4;
  2388. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId);
  2389. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2390. };
  2391. const runoutGuidance = status?.state === 'PAUSE'
  2392. ? {
  2393. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2394. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2395. }
  2396. : null;
  2397. // Fetch smart plug for this printer
  2398. const { data: smartPlug } = useQuery({
  2399. queryKey: ['smartPlugByPrinter', printer.id],
  2400. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2401. });
  2402. // Fetch script plugs for this printer (for multi-device control)
  2403. const { data: scriptPlugs } = useQuery({
  2404. queryKey: ['scriptPlugsByPrinter', printer.id],
  2405. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2406. });
  2407. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2408. const { data: plugStatus } = useQuery({
  2409. queryKey: ['smartPlugStatus', smartPlug?.id],
  2410. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2411. enabled: !!smartPlug,
  2412. refetchInterval: 10000, // 10 seconds for real-time power display
  2413. });
  2414. // Fetch queue count for this printer
  2415. const { data: queueItems } = useQuery({
  2416. queryKey: ['queue', printer.id, 'pending'],
  2417. queryFn: () => api.getQueue(printer.id, 'pending'),
  2418. });
  2419. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2420. // so the badge only shows on printers that can actually run the queued jobs.
  2421. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2422. const queueCount = useMemo(() => {
  2423. if (!queueItems?.length) return 0;
  2424. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2425. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2426. // Fetch currently printing queue item to show who started it (Issue #206)
  2427. const { data: printingQueueItems } = useQuery({
  2428. queryKey: ['queue', printer.id, 'printing'],
  2429. queryFn: () => api.getQueue(printer.id, 'printing'),
  2430. enabled: status?.state === 'RUNNING',
  2431. });
  2432. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2433. const { data: reprintUser } = useQuery({
  2434. queryKey: ['currentPrintUser', printer.id],
  2435. queryFn: () => api.getCurrentPrintUser(printer.id),
  2436. enabled: status?.state === 'RUNNING',
  2437. });
  2438. // Combine both sources: queue item user takes precedence, then reprint user
  2439. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2440. // Last print of this printer. One shared request for every card on the page
  2441. // (the key is the same for all of them); each card picks its own row.
  2442. const { data: lastPrint } = useQuery({
  2443. queryKey: ['archives', 'last-per-printer'],
  2444. queryFn: () => api.getLastArchivePerPrinter(),
  2445. select: (archives) => archives.find((a) => a.printer_id === printer.id),
  2446. });
  2447. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2448. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2449. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2450. // gate is up and the just-finished print asked for a verdict, offer
  2451. // Good/Reject right where the operator releases the plate. Releasing the
  2452. // plate without answering stays possible — the two are orthogonal (though
  2453. // the confirm_default_good_on_plate_clear setting can couple them).
  2454. // Only offered to whoever may record it: the PATCH checks archives:update
  2455. // against the archive's owner, so for anyone else the pair could only fail.
  2456. const pendingConfirmArchive =
  2457. lastPrint &&
  2458. lastPrint.status === 'completed' &&
  2459. lastPrint.confirm_requested &&
  2460. lastPrint.user_verdict == null &&
  2461. canModify('archives', 'update', lastPrint.created_by_id)
  2462. ? lastPrint
  2463. : null;
  2464. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2465. // Auto Power Off the printer is powered down exactly when the operator clears the
  2466. // plate. Hiding the control there left no way to release the gate (#2864).
  2467. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2468. const activePrintName = status?.current_print && isPrintingOrPaused
  2469. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2470. : null;
  2471. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2472. useEffect(() => {
  2473. if (activePrintName) {
  2474. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2475. } else if (!needsPlateClear) {
  2476. setRetainedPrintJob(null);
  2477. }
  2478. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2479. const plateStatus = (() => {
  2480. // Connected-only because the pill's only render site sits inside the live-status
  2481. // panel. For a powered-down printer the plate-clear button itself carries the
  2482. // state — see the standalone slot below the status block (#2864).
  2483. if (!requirePlateClear || !status?.connected) return null;
  2484. if (isPrintingOrPaused) {
  2485. return {
  2486. label: t('printers.plateStatus.inUse'),
  2487. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2488. };
  2489. }
  2490. if (status.awaiting_plate_clear) {
  2491. return {
  2492. label: t('printers.plateStatus.notCleared'),
  2493. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2494. };
  2495. }
  2496. return {
  2497. label: t('printers.plateStatus.cleared'),
  2498. className: 'bg-status-ok/20 text-status-ok',
  2499. };
  2500. })();
  2501. const plateStatusPill = plateStatus ? (
  2502. <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}`}>
  2503. {plateStatus.label}
  2504. </span>
  2505. ) : null;
  2506. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2507. const shouldHide = hideIfDisconnected && isConnected === false;
  2508. const deleteMutation = useMutation({
  2509. mutationFn: (options: { deleteArchives: boolean }) =>
  2510. api.deletePrinter(printer.id, options.deleteArchives),
  2511. onSuccess: () => {
  2512. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2513. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2514. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2515. // What was limited to the printer went with it (providers, virtual
  2516. // printers, smart plugs) or lost it (API keys, Obico).
  2517. queryClient.invalidateQueries({ queryKey: ['notification-providers'] });
  2518. queryClient.invalidateQueries({ queryKey: ['virtual-printers'] });
  2519. queryClient.invalidateQueries({ queryKey: ['api-keys'] });
  2520. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2521. // Obico's printer list lost it; a cached copy would save it back.
  2522. queryClient.invalidateQueries({ queryKey: ['settings'] });
  2523. },
  2524. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2525. });
  2526. const connectMutation = useMutation({
  2527. mutationFn: () => api.connectPrinter(printer.id),
  2528. onSuccess: () => {
  2529. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2530. },
  2531. });
  2532. const forceRefreshMutation = useMutation({
  2533. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2534. onSuccess: () => {
  2535. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2536. showToast(t('printers.forceRefreshSuccess'), 'success');
  2537. },
  2538. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2539. });
  2540. const unlinkSpoolMutation = useMutation({
  2541. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2542. onSuccess: (result) => {
  2543. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2544. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2545. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2546. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2547. },
  2548. onError: (error: Error) => {
  2549. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2550. },
  2551. });
  2552. // AMS drying mutations
  2553. const startDryingMutation = useMutation({
  2554. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2555. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2556. onSuccess: (_data, { amsId }) => {
  2557. setDryingPopoverAmsId(null);
  2558. setDryStartWatch({ amsId });
  2559. // "Command sent", not "drying started" — at this point the printer has only
  2560. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2561. // the cycle is genuinely live; the watcher below covers the case where it
  2562. // never appears.
  2563. showToast(t('printers.drying.toastCommandSent'), 'success');
  2564. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2565. },
  2566. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2567. });
  2568. // Scheduled (delayed / at-time) drying runs (#2638)
  2569. const scheduleDryingMutation = useMutation({
  2570. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2571. api.createScheduledDrying({
  2572. printer_id: printer.id,
  2573. ams_id: params.amsId,
  2574. temp: params.temp,
  2575. duration_hours: params.duration,
  2576. filament: params.filament,
  2577. rotate_tray: params.rotateTray,
  2578. start_after: params.startAfter,
  2579. }),
  2580. onSuccess: () => {
  2581. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2582. setDryingPopoverAmsId(null);
  2583. },
  2584. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2585. });
  2586. const stopDryingMutation = useMutation({
  2587. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2588. onSuccess: () => {
  2589. setDryStartWatch(null);
  2590. showToast(t('printers.drying.toastStopped'), 'success');
  2591. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2592. },
  2593. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2594. });
  2595. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2596. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2597. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2598. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2599. // showing the old backup state until the user reopens it.
  2600. const setAmsBackupMutation = useMutation({
  2601. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2602. onSuccess: (_data, enabled) => {
  2603. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2604. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2605. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2606. },
  2607. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2608. });
  2609. // Smart plug control mutations
  2610. const powerControlMutation = useMutation({
  2611. mutationFn: (action: 'on' | 'off') =>
  2612. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2613. onSuccess: () => {
  2614. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2615. },
  2616. });
  2617. const toggleAutoOffMutation = useMutation({
  2618. mutationFn: (enabled: boolean) =>
  2619. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2620. onSuccess: () => {
  2621. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2622. // Also invalidate the smart-plugs list to keep Settings page in sync
  2623. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2624. },
  2625. });
  2626. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2627. const runScriptMutation = useMutation({
  2628. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2629. onSuccess: () => {
  2630. showToast(t('printers.toast.scriptTriggered'));
  2631. },
  2632. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2633. });
  2634. // Print control mutations
  2635. const stopPrintMutation = useMutation({
  2636. mutationFn: () => api.stopPrint(printer.id),
  2637. onSuccess: () => {
  2638. showToast(t('printers.toast.printStopped'));
  2639. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2640. },
  2641. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2642. });
  2643. const pausePrintMutation = useMutation({
  2644. mutationFn: () => api.pausePrint(printer.id),
  2645. onSuccess: () => {
  2646. showToast(t('printers.toast.printPaused'));
  2647. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2648. },
  2649. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2650. });
  2651. const resumePrintMutation = useMutation({
  2652. mutationFn: () => api.resumePrint(printer.id),
  2653. onSuccess: () => {
  2654. showToast(t('printers.toast.printResumed'));
  2655. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2656. },
  2657. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2658. });
  2659. const clearPlateMutation = useMutation({
  2660. mutationFn: () => api.clearPlate(printer.id),
  2661. onSuccess: () => {
  2662. showToast(t('queue.clearPlateSuccess'));
  2663. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2664. old ? { ...old, awaiting_plate_clear: false } : old
  2665. );
  2666. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2667. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2668. },
  2669. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2670. });
  2671. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2672. // reject goes through the dialog for the optional reason + reprint.
  2673. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2674. // Only "good" is answered on the card. A reject wants a reason and possibly
  2675. // a reprint, so that button opens the dialog instead — and the parameter
  2676. // says as much, rather than accepting a verdict this path cannot send and
  2677. // then reporting it as good.
  2678. const cardVerdictMutation = useMutation({
  2679. mutationFn: (verdict: 'good') =>
  2680. api.updateArchive(pendingConfirmArchive!.id, {
  2681. user_verdict: verdict,
  2682. user_verdict_source: 'printer_card',
  2683. }),
  2684. onSuccess: () => {
  2685. showToast(t('confirmOutcome.savedGood'), 'success');
  2686. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2687. },
  2688. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2689. });
  2690. // Rendered from two places: inside the live-status block for a connected printer,
  2691. // and standalone below it for a powered-down one, whose status block isn't rendered
  2692. // at all (#2864). Shared so the two can't drift apart.
  2693. const expandedClearPlateButton = (
  2694. <>
  2695. {pendingConfirmArchive && (
  2696. <div className="mt-2 flex items-center gap-1.5">
  2697. <span
  2698. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2699. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2700. >
  2701. {t('confirmOutcome.cardPrompt')}
  2702. </span>
  2703. <button
  2704. type="button"
  2705. onClick={() => setShowConfirmOutcome(true)}
  2706. disabled={cardVerdictMutation.isPending}
  2707. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2708. title={t('confirmOutcome.reject')}
  2709. >
  2710. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2711. </button>
  2712. <button
  2713. type="button"
  2714. onClick={() => cardVerdictMutation.mutate('good')}
  2715. disabled={cardVerdictMutation.isPending}
  2716. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2717. title={t('confirmOutcome.good')}
  2718. >
  2719. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2720. </button>
  2721. </div>
  2722. )}
  2723. <button
  2724. type="button"
  2725. onClick={() => clearPlateMutation.mutate()}
  2726. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2727. 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"
  2728. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2729. >
  2730. {clearPlateMutation.isPending ? (
  2731. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2732. ) : (
  2733. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2734. )}
  2735. {t('printers.plateStatus.markCleared')}
  2736. </button>
  2737. {showConfirmOutcome && pendingConfirmArchive && (
  2738. <ConfirmOutcomeDialog
  2739. archiveId={pendingConfirmArchive.id}
  2740. onClose={() => setShowConfirmOutcome(false)}
  2741. />
  2742. )}
  2743. </>
  2744. );
  2745. const nozzleTemperatureMutation = useMutation({
  2746. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2747. api.setNozzleTemperature(printer.id, target, nozzle),
  2748. onSuccess: (result) => {
  2749. setStatusControlMenu(null);
  2750. showToast(result.message);
  2751. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2752. },
  2753. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2754. });
  2755. const bedTemperatureMutation = useMutation({
  2756. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2757. onSuccess: (result) => {
  2758. setStatusControlMenu(null);
  2759. showToast(result.message);
  2760. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2761. },
  2762. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2763. });
  2764. const chamberTemperatureMutation = useMutation({
  2765. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2766. onSuccess: (result) => {
  2767. setStatusControlMenu(null);
  2768. showToast(result.message);
  2769. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2770. },
  2771. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2772. });
  2773. const fanSpeedMutation = useMutation({
  2774. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2775. api.setFanSpeed(printer.id, fan, speed),
  2776. onMutate: async ({ fan, speed }) => {
  2777. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2778. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2779. const fanField = {
  2780. part: 'cooling_fan_speed',
  2781. aux: 'big_fan1_speed',
  2782. aux2: 'left_aux_fan_speed',
  2783. chamber: 'big_fan2_speed',
  2784. }[fan];
  2785. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2786. old ? { ...old, [fanField]: speed } : old
  2787. );
  2788. return { previousStatus };
  2789. },
  2790. onSuccess: (result) => {
  2791. setStatusControlMenu(null);
  2792. showToast(result.message);
  2793. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2794. },
  2795. onError: (error: Error, _variables, context) => {
  2796. if (context?.previousStatus) {
  2797. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2798. }
  2799. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2800. },
  2801. });
  2802. const selectExtruderMutation = useMutation({
  2803. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2804. onMutate: async (extruder) => {
  2805. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2806. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2807. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2808. old ? { ...old, active_extruder: extruder } : old
  2809. );
  2810. return { previousStatus };
  2811. },
  2812. onSuccess: (result) => {
  2813. setStatusControlMenu(null);
  2814. showToast(result.message);
  2815. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2816. },
  2817. onError: (error: Error, _extruder, context) => {
  2818. if (context?.previousStatus) {
  2819. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2820. }
  2821. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2822. },
  2823. });
  2824. // Chamber light mutation with optimistic update
  2825. const chamberLightMutation = useMutation({
  2826. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2827. onMutate: async (on) => {
  2828. // Cancel any outgoing refetches
  2829. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2830. // Snapshot the previous value
  2831. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2832. // Optimistically update
  2833. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2834. ...old,
  2835. chamber_light: on,
  2836. }));
  2837. return { previousStatus };
  2838. },
  2839. onSuccess: (_, on) => {
  2840. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2841. },
  2842. onError: (error: Error, _, context) => {
  2843. // Rollback on error
  2844. if (context?.previousStatus) {
  2845. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2846. }
  2847. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2848. },
  2849. });
  2850. // Print speed mutation with optimistic update
  2851. const printSpeedMutation = useMutation({
  2852. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2853. onMutate: async (mode) => {
  2854. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2855. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2856. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2857. ...old,
  2858. speed_level: mode,
  2859. }));
  2860. return { previousStatus };
  2861. },
  2862. onError: (error: Error, _, context) => {
  2863. if (context?.previousStatus) {
  2864. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2865. }
  2866. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2867. },
  2868. });
  2869. const airductMutation = useMutation({
  2870. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2871. onMutate: async (mode) => {
  2872. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2873. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2874. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2875. ...old,
  2876. airduct_mode: mode === 'cooling' ? 0 : 1,
  2877. }));
  2878. return { previousStatus };
  2879. },
  2880. onError: (error: Error, _, context) => {
  2881. if (context?.previousStatus) {
  2882. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2883. }
  2884. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2885. },
  2886. });
  2887. const bedJogMutation = useMutation({
  2888. mutationFn: ({ distance }: { distance: number }) =>
  2889. api.bedJog(printer.id, distance),
  2890. onError: (error: Error) =>
  2891. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2892. });
  2893. const xyJogMutation = useMutation({
  2894. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2895. api.xyJog(printer.id, x, y),
  2896. onError: (error: Error) =>
  2897. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2898. });
  2899. const extruderJogMutation = useMutation({
  2900. mutationFn: (distance: number) =>
  2901. api.extruderJog(printer.id, distance),
  2902. onError: (error: Error) =>
  2903. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2904. });
  2905. const homeAxesMutation = useMutation({
  2906. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2907. onSuccess: () => {
  2908. showToast(t('printers.bedJog.homingStarted'));
  2909. },
  2910. onError: (error: Error) =>
  2911. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2912. });
  2913. // Plate detection setting mutation
  2914. const plateDetectionMutation = useMutation({
  2915. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2916. onSuccess: () => {
  2917. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2918. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2919. },
  2920. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2921. });
  2922. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2923. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2924. // metrics, and the print picker — so flipping this flag puts the printer
  2925. // out of service across every consumer in one place. Used from the
  2926. // overflow menu and EditPrinterModal.
  2927. const maintenanceMutation = useMutation({
  2928. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2929. onSuccess: (_data, isActive) => {
  2930. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2931. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2932. showToast(
  2933. isActive
  2934. ? t('printers.maintenance.toastExited', { name: printer.name })
  2935. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2936. 'success',
  2937. );
  2938. },
  2939. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2940. });
  2941. // Confirm before entering maintenance on a printing printer (entering mode
  2942. // disconnects MQTT, which stops progress tracking + completion notifications
  2943. // for the in-flight job).
  2944. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2945. const handleEnterMaintenance = () => {
  2946. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2947. setConfirmMaintenanceEnter(true);
  2948. } else {
  2949. maintenanceMutation.mutate(false);
  2950. }
  2951. };
  2952. // Query for printable objects (for skip functionality)
  2953. // Fetch when printing with 2+ objects OR when modal is open
  2954. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2955. const { data: objectsData } = useQuery({
  2956. queryKey: ['printableObjects', printer.id],
  2957. queryFn: () => api.getPrintableObjects(printer.id),
  2958. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2959. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2960. });
  2961. // State for tracking which AMS slot is being refreshed
  2962. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2963. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2964. const seenBusyStateRef = useRef<boolean>(false);
  2965. // Fallback timeout ref
  2966. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2967. // Minimum display time passed
  2968. const minTimePassedRef = useRef<boolean>(false);
  2969. // AMS slot refresh mutation
  2970. const refreshAmsSlotMutation = useMutation({
  2971. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2972. api.refreshAmsSlot(printer.id, amsId, slotId),
  2973. onMutate: ({ amsId, slotId }) => {
  2974. // Clear any existing timeout
  2975. if (refreshTimeoutRef.current) {
  2976. clearTimeout(refreshTimeoutRef.current);
  2977. }
  2978. // Reset state
  2979. seenBusyStateRef.current = false;
  2980. minTimePassedRef.current = false;
  2981. setRefreshingSlot({ amsId, slotId });
  2982. // Minimum display time (2 seconds)
  2983. setTimeout(() => {
  2984. minTimePassedRef.current = true;
  2985. }, 2000);
  2986. // Fallback timeout (30 seconds max)
  2987. refreshTimeoutRef.current = setTimeout(() => {
  2988. setRefreshingSlot(null);
  2989. }, 30000);
  2990. },
  2991. onSuccess: (data) => {
  2992. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2993. },
  2994. onError: (error: Error) => {
  2995. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2996. if (refreshTimeoutRef.current) {
  2997. clearTimeout(refreshTimeoutRef.current);
  2998. }
  2999. setRefreshingSlot(null);
  3000. },
  3001. });
  3002. // AMS load/unload mutations (#891)
  3003. const loadAmsTrayMutation = useMutation({
  3004. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  3005. api.loadAmsTray(printer.id, trayId, extruderId),
  3006. onSuccess: (data) => {
  3007. setFeedDirectionRequest(null);
  3008. showToast(data.message || t('printers.toast.loadInitiated'));
  3009. },
  3010. onError: (error: Error) => {
  3011. setFeedDirectionRequest(null);
  3012. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3013. },
  3014. });
  3015. const unloadAmsMutation = useMutation({
  3016. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3017. onSuccess: (data) => {
  3018. showToast(data.message || t('printers.toast.unloadInitiated'));
  3019. },
  3020. onError: (error: Error) => {
  3021. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3022. },
  3023. });
  3024. // Pending "which hotend?" question, non-null only while the dialog is open.
  3025. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3026. // load command has to name one — see FeedDirectionModal.
  3027. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3028. trayId: number;
  3029. amsId: number;
  3030. slotId: number;
  3031. slotLabel: string;
  3032. } | null>(null);
  3033. // Whether a load from this printer has to ask which hotend to feed.
  3034. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3035. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3036. // The external holder needs no question: its two tray ids name the side
  3037. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3038. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3039. // external spool, because it would occupy an extruder channel permanently.
  3040. // An AMS-HT behind the switch is asked like any AMS, as BambuStudio does.
  3041. const isExternal = amsId === 255;
  3042. if (!ftsNeedsFeedDirection || isExternal) {
  3043. loadAmsTrayMutation.mutate({ trayId });
  3044. return;
  3045. }
  3046. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3047. // front rather than sending a command the firmware will drop. BambuStudio
  3048. // shows the same message and returns without publishing anything.
  3049. if (!status?.fila_switch?.ready) {
  3050. showToast(t('printers.ams.switchNotReady'), 'warning');
  3051. return;
  3052. }
  3053. setFeedDirectionRequest({
  3054. trayId,
  3055. amsId,
  3056. slotId,
  3057. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3058. });
  3059. };
  3060. // Plate references state
  3061. const [plateReferences, setPlateReferences] = useState<{
  3062. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3063. max_references: number;
  3064. } | null>(null);
  3065. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3066. // Fetch plate references
  3067. const fetchPlateReferences = async () => {
  3068. try {
  3069. const data = await api.getPlateReferences(printer.id);
  3070. setPlateReferences(data);
  3071. } catch {
  3072. // Ignore errors - references will show as empty
  3073. }
  3074. };
  3075. // Toggle plate detection enabled/disabled
  3076. const handleTogglePlateDetection = () => {
  3077. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3078. };
  3079. // Open plate detection management modal (for calibration/references)
  3080. const handleOpenPlateManagement = async () => {
  3081. setIsCheckingPlate(true);
  3082. setPlateCheckResult(null);
  3083. // Auto-turn on light if it's off
  3084. const lightWasOff = status?.chamber_light === false;
  3085. setPlateCheckLightWasOff(lightWasOff);
  3086. if (lightWasOff) {
  3087. await api.setChamberLight(printer.id, true);
  3088. // Wait for light to physically turn on and camera to adjust exposure
  3089. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3090. await new Promise(resolve => setTimeout(resolve, 2500));
  3091. }
  3092. try {
  3093. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3094. setPlateCheckResult(result);
  3095. fetchPlateReferences();
  3096. } catch (error) {
  3097. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3098. // Restore light if check failed
  3099. if (lightWasOff) {
  3100. await api.setChamberLight(printer.id, false);
  3101. setPlateCheckLightWasOff(false);
  3102. }
  3103. } finally {
  3104. setIsCheckingPlate(false);
  3105. }
  3106. };
  3107. // Close plate check modal and restore light state
  3108. const closePlateCheckModal = useCallback(async () => {
  3109. setPlateCheckResult(null);
  3110. // Restore light to original state if we turned it on
  3111. if (plateCheckLightWasOff) {
  3112. await api.setChamberLight(printer.id, false);
  3113. setPlateCheckLightWasOff(false);
  3114. }
  3115. }, [plateCheckLightWasOff, printer.id]);
  3116. // Calibrate plate detection handler
  3117. const handleCalibratePlate = async (label?: string) => {
  3118. setIsCalibrating(true);
  3119. try {
  3120. const result = await api.calibratePlateDetection(printer.id, { label });
  3121. if (result.success) {
  3122. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3123. // Refresh references and re-check
  3124. fetchPlateReferences();
  3125. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3126. setPlateCheckResult(checkResult);
  3127. } else {
  3128. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3129. }
  3130. } catch (error) {
  3131. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3132. } finally {
  3133. setIsCalibrating(false);
  3134. }
  3135. };
  3136. // Update reference label
  3137. const handleUpdateRefLabel = async (index: number, label: string) => {
  3138. try {
  3139. await api.updatePlateReferenceLabel(printer.id, index, label);
  3140. setEditingRefLabel(null);
  3141. fetchPlateReferences();
  3142. } catch (error) {
  3143. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3144. }
  3145. };
  3146. // Delete reference
  3147. const handleDeleteRef = async (index: number) => {
  3148. try {
  3149. await api.deletePlateReference(printer.id, index);
  3150. showToast(t('printers.toast.referenceDeleted'), 'success');
  3151. fetchPlateReferences();
  3152. // Re-check to update counts
  3153. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3154. setPlateCheckResult(checkResult);
  3155. } catch (error) {
  3156. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3157. }
  3158. };
  3159. // Save ROI settings
  3160. const handleSaveRoi = async () => {
  3161. if (!editingRoi) return;
  3162. setIsSavingRoi(true);
  3163. try {
  3164. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3165. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3166. setEditingRoi(null);
  3167. // Re-check to see new ROI in action
  3168. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3169. setPlateCheckResult(checkResult);
  3170. } catch (error) {
  3171. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3172. } finally {
  3173. setIsSavingRoi(false);
  3174. }
  3175. };
  3176. // Close plate check modal on Escape key
  3177. useEffect(() => {
  3178. const handleEscape = (e: KeyboardEvent) => {
  3179. if (e.key === 'Escape' && plateCheckResult) {
  3180. closePlateCheckModal();
  3181. }
  3182. };
  3183. window.addEventListener('keydown', handleEscape);
  3184. return () => window.removeEventListener('keydown', handleEscape);
  3185. }, [plateCheckResult, closePlateCheckModal]);
  3186. // Watch ams_status_main to detect when RFID read completes
  3187. // ams_status_main: 0=idle, 2=rfid_identifying
  3188. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3189. useEffect(() => {
  3190. if (!refreshingSlot) return;
  3191. const amsStatus = status?.ams_status_main ?? 0;
  3192. // Track when we see non-idle state (printer is working)
  3193. if (amsStatus !== 0) {
  3194. seenBusyStateRef.current = true;
  3195. // Cancel any deferred clear since we're back to busy
  3196. if (deferredClearRef.current) {
  3197. clearTimeout(deferredClearRef.current);
  3198. deferredClearRef.current = null;
  3199. }
  3200. }
  3201. // When we've seen busy and now idle, clear (with min time check)
  3202. if (seenBusyStateRef.current && amsStatus === 0) {
  3203. if (minTimePassedRef.current) {
  3204. // Min time passed - clear now
  3205. if (refreshTimeoutRef.current) {
  3206. clearTimeout(refreshTimeoutRef.current);
  3207. }
  3208. setRefreshingSlot(null);
  3209. } else {
  3210. // Schedule clear after min time (2 seconds from start)
  3211. if (!deferredClearRef.current) {
  3212. deferredClearRef.current = setTimeout(() => {
  3213. if (refreshTimeoutRef.current) {
  3214. clearTimeout(refreshTimeoutRef.current);
  3215. }
  3216. setRefreshingSlot(null);
  3217. }, 2000);
  3218. }
  3219. }
  3220. }
  3221. return () => {
  3222. if (deferredClearRef.current) {
  3223. clearTimeout(deferredClearRef.current);
  3224. }
  3225. };
  3226. }, [status?.ams_status_main, refreshingSlot]);
  3227. useEffect(() => {
  3228. if (!showMenu) return;
  3229. const handleClickOutside = (event: MouseEvent) => {
  3230. const target = event.target as Node;
  3231. if (!printerActionsMenuRef.current?.contains(target)) {
  3232. setShowMenu(false);
  3233. }
  3234. };
  3235. document.addEventListener('mousedown', handleClickOutside);
  3236. return () => document.removeEventListener('mousedown', handleClickOutside);
  3237. }, [showMenu]);
  3238. if (shouldHide) {
  3239. return null;
  3240. }
  3241. // Size-based styling helpers
  3242. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3243. // width, its thumbnail and the printer name, but every label inside the
  3244. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3245. // S one -- the disparity was worst exactly where someone asking for more
  3246. // room ends up. These custom properties carry the scaled sizes into the
  3247. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3248. // unless they reach for a size that is already asking for more space.
  3249. // Plain computation rather than useMemo: this sits after the card's early
  3250. // returns, where a hook would break the rules-of-hooks ordering, and
  3251. // building ten strings per render costs nothing.
  3252. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3253. const getImageSize = () => {
  3254. switch (cardSize) {
  3255. case 1: return 'w-10 h-10';
  3256. case 2: return 'w-14 h-14';
  3257. case 3: return 'w-16 h-16';
  3258. case 4: return 'w-20 h-20';
  3259. default: return 'w-14 h-14';
  3260. }
  3261. };
  3262. const getTitleSize = () => {
  3263. switch (cardSize) {
  3264. case 1: return 'text-base truncate';
  3265. case 2: return 'text-lg';
  3266. case 3: return 'text-xl';
  3267. case 4: return 'text-2xl';
  3268. default: return 'text-lg';
  3269. }
  3270. };
  3271. const getSpacing = () => {
  3272. switch (cardSize) {
  3273. case 1: return 'mb-2';
  3274. case 2: return 'mb-4';
  3275. case 3: return 'mb-5';
  3276. case 4: return 'mb-6';
  3277. default: return 'mb-4';
  3278. }
  3279. };
  3280. // A dropped file always becomes a queue item, so a printer that is busy,
  3281. // offline or mid-drying is no reason to refuse the drop — it only means the
  3282. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3283. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3284. // what this would have done for them.
  3285. //
  3286. // What remains is what the flow actually performs: upload the file, then
  3287. // create a queue item. It never touches printers:control, which is what this
  3288. // used to check — so someone holding that but neither of these had the file
  3289. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3290. // button below has always checked this pair.
  3291. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3292. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3293. // and the modal's own "will start later" toast cannot disagree.
  3294. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3295. const handleCardDragEnter = (e: React.DragEvent) => {
  3296. e.preventDefault();
  3297. dragCounterRef.current++;
  3298. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3299. };
  3300. const handleCardDragOver = (e: React.DragEvent) => {
  3301. e.preventDefault();
  3302. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3303. };
  3304. const handleCardDragLeave = (e: React.DragEvent) => {
  3305. e.preventDefault();
  3306. dragCounterRef.current--;
  3307. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3308. };
  3309. const handleCardDrop = async (e: React.DragEvent) => {
  3310. e.preventDefault();
  3311. dragCounterRef.current = 0;
  3312. setIsDraggingFile(false);
  3313. if (!canDrop) return;
  3314. const droppedFiles = Array.from(e.dataTransfer.files);
  3315. const file = droppedFiles[0];
  3316. if (!file) return;
  3317. // Sliced files only. A plain .3mf can be sliced too (a Studio plate
  3318. // export), which only its content tells — checked after the upload.
  3319. if (!mayBeSlicedFileName(file.name)) {
  3320. showToast(t('printers.dropNotPrintable'), 'error');
  3321. return;
  3322. }
  3323. setIsDropUploading(true);
  3324. try {
  3325. const result = await api.uploadLibraryFile(file, null);
  3326. if (!isSlicedLibraryFile(result)) {
  3327. await api.deleteLibraryFile(result.id).catch(() => {});
  3328. showToast(t('printers.dropNotSliced'), 'error');
  3329. return;
  3330. }
  3331. // Check printer compatibility if sliced_for_model is available in metadata
  3332. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3333. const printerModel = mapModelCode(printer.model);
  3334. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3335. await api.deleteLibraryFile(result.id).catch(() => {});
  3336. showToast(
  3337. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3338. 'error'
  3339. );
  3340. return;
  3341. }
  3342. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3343. } catch {
  3344. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3345. } finally {
  3346. setIsDropUploading(false);
  3347. }
  3348. };
  3349. const handleCardClick = (e: React.MouseEvent) => {
  3350. if (viewMode !== 'compact' || selectionMode) return;
  3351. const target = e.target as HTMLElement;
  3352. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3353. onOpenCompactCard?.(printer.id);
  3354. };
  3355. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3356. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3357. // Opening a camera in a given mode, without touching which mode is remembered
  3358. // -- the split button's two halves want the same action but disagree about
  3359. // whether the choice was deliberate enough to keep.
  3360. const openCameraIn = (mode: CameraViewMode) => {
  3361. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3362. onOpenEmbeddedCamera(printer.id, printer.name);
  3363. } else {
  3364. openCameraWindow(printer.id);
  3365. }
  3366. };
  3367. // Picking a mode both opens the camera that way and makes it the mode the
  3368. // plain icon uses from now on. A menu that only changed a preference would
  3369. // leave the user with a second click to do the thing they already asked for.
  3370. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3371. [
  3372. {
  3373. mode: 'window' as const,
  3374. icon: <ExternalLink className="w-4 h-4" />,
  3375. label: t('settings.newWindow'),
  3376. title: t('settings.cameraWindowDescription'),
  3377. },
  3378. {
  3379. mode: 'embedded' as const,
  3380. icon: <PictureInPicture2 className="w-4 h-4" />,
  3381. label: t('settings.embeddedOverlay'),
  3382. title: t('settings.cameraOverlayDescription'),
  3383. },
  3384. ]
  3385. ).map(({ mode, icon, label, title }) => ({
  3386. icon,
  3387. // The remembered mode is marked in the label itself: the icon slot already
  3388. // carries the mode's own icon, and a separate tick column would push both
  3389. // entries out of line with every other card menu.
  3390. label: mode === cameraViewMode ? `${label} ✓` : label,
  3391. title,
  3392. onClick: () => {
  3393. onSelectCameraViewMode?.(mode);
  3394. openCameraIn(mode);
  3395. },
  3396. }));
  3397. const renderAmsSlotActions = ({
  3398. amsId,
  3399. slotId,
  3400. loadTrayId,
  3401. isRefreshing,
  3402. includeRfid = true,
  3403. }: {
  3404. amsId: number;
  3405. slotId: number;
  3406. loadTrayId: number;
  3407. isRefreshing?: boolean;
  3408. includeRfid?: boolean;
  3409. }) => {
  3410. const printerBusy = status?.state === 'RUNNING';
  3411. return (
  3412. <>
  3413. {includeRfid && (
  3414. <button
  3415. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3416. hasPermission('printers:ams_rfid')
  3417. ? 'text-white hover:bg-bambu-dark-tertiary'
  3418. : 'text-bambu-gray/50 cursor-not-allowed'
  3419. }`}
  3420. onClick={(e) => {
  3421. e.stopPropagation();
  3422. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3423. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3424. }}
  3425. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3426. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3427. >
  3428. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3429. {t('printers.rfid.reread')}
  3430. </button>
  3431. )}
  3432. <button
  3433. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3434. hasPermission('printers:control')
  3435. ? 'text-white hover:bg-bambu-dark-tertiary'
  3436. : 'text-bambu-gray/50 cursor-not-allowed'
  3437. }`}
  3438. onClick={(e) => {
  3439. e.stopPropagation();
  3440. if (printerBusy || !hasPermission('printers:control')) return;
  3441. startAmsLoad(amsId, slotId, loadTrayId);
  3442. }}
  3443. disabled={printerBusy || !hasPermission('printers:control')}
  3444. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3445. >
  3446. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3447. {t('printers.ams.load')}
  3448. </button>
  3449. <button
  3450. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3451. hasPermission('printers:control')
  3452. ? 'text-white hover:bg-bambu-dark-tertiary'
  3453. : 'text-bambu-gray/50 cursor-not-allowed'
  3454. }`}
  3455. onClick={(e) => {
  3456. e.stopPropagation();
  3457. if (printerBusy || !hasPermission('printers:control')) return;
  3458. unloadAmsMutation.mutate({ trayId: loadTrayId });
  3459. }}
  3460. disabled={printerBusy || !hasPermission('printers:control')}
  3461. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3462. >
  3463. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3464. {t('printers.ams.unload')}
  3465. </button>
  3466. </>
  3467. );
  3468. };
  3469. const printerActionsMenu = (
  3470. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3471. <Button
  3472. variant="secondary"
  3473. size="sm"
  3474. onClick={() => setShowMenu(!showMenu)}
  3475. title={t('common.more', 'More')}
  3476. className={footerIconButtonClass}
  3477. >
  3478. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3479. </Button>
  3480. {showMenu && (
  3481. <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">
  3482. <button
  3483. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3484. hasPermission('printers:update')
  3485. ? 'hover:bg-bambu-dark-tertiary'
  3486. : 'opacity-50 cursor-not-allowed'
  3487. }`}
  3488. onClick={() => {
  3489. if (!hasPermission('printers:update')) return;
  3490. setShowEditModal(true);
  3491. setShowMenu(false);
  3492. }}
  3493. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3494. >
  3495. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3496. {t('common.edit')}
  3497. </button>
  3498. <button
  3499. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3500. onClick={() => {
  3501. setShowPrinterInfo(true);
  3502. setShowMenu(false);
  3503. }}
  3504. >
  3505. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3506. {t('printers.printerInformation')}
  3507. </button>
  3508. {authEnabled && isAdmin && (
  3509. <button
  3510. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3511. onClick={() => {
  3512. setShowMenu(false);
  3513. navigate(`/settings?tab=users&sub=printer-access&view=printers&printer=${printer.id}`);
  3514. }}
  3515. >
  3516. <KeyRound className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3517. {t('printerAccess.whoHasAccess')}
  3518. </button>
  3519. )}
  3520. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3521. <button
  3522. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3523. hasPermission('printers:update')
  3524. ? 'hover:bg-bambu-dark-tertiary'
  3525. : 'opacity-50 cursor-not-allowed'
  3526. }`}
  3527. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3528. onClick={() => {
  3529. if (!hasPermission('printers:update')) return;
  3530. setShowMenu(false);
  3531. if (printer.is_active !== false) {
  3532. handleEnterMaintenance();
  3533. } else {
  3534. maintenanceMutation.mutate(true);
  3535. }
  3536. }}
  3537. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3538. >
  3539. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3540. {printer.is_active !== false
  3541. ? t('printers.maintenance.menuEnter')
  3542. : t('printers.maintenance.menuExit')}
  3543. </button>
  3544. <button
  3545. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3546. onClick={() => {
  3547. connectMutation.mutate();
  3548. setShowMenu(false);
  3549. }}
  3550. >
  3551. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3552. {t('printers.reconnect')}
  3553. </button>
  3554. <button
  3555. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3556. disabled={forceRefreshMutation.isPending}
  3557. onClick={() => {
  3558. forceRefreshMutation.mutate();
  3559. setShowMenu(false);
  3560. }}
  3561. >
  3562. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3563. {t('printers.forceRefresh')}
  3564. </button>
  3565. <button
  3566. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3567. onClick={() => {
  3568. setShowMQTTDebug(true);
  3569. setShowMenu(false);
  3570. }}
  3571. >
  3572. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3573. {t('printers.mqttDebug')}
  3574. </button>
  3575. <button
  3576. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3577. onClick={() => {
  3578. setShowDiagnostic(true);
  3579. setShowMenu(false);
  3580. }}
  3581. >
  3582. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3583. {t('diagnostic.runButton')}
  3584. </button>
  3585. <button
  3586. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3587. hasPermission('printers:delete')
  3588. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3589. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3590. }`}
  3591. onClick={() => {
  3592. if (!hasPermission('printers:delete')) return;
  3593. setShowDeleteConfirm(true);
  3594. setShowMenu(false);
  3595. }}
  3596. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3597. >
  3598. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3599. {t('common.delete')}
  3600. </button>
  3601. </div>
  3602. )}
  3603. </div>
  3604. );
  3605. return (
  3606. <Card
  3607. id={`printer-card-${printer.id}`}
  3608. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3609. style={cardScaleStyle}
  3610. onClick={handleCardClick}
  3611. onDragEnter={handleCardDragEnter}
  3612. onDragOver={handleCardDragOver}
  3613. onDragLeave={handleCardDragLeave}
  3614. onDrop={handleCardDrop}
  3615. >
  3616. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3617. {selectionMode && (
  3618. <div
  3619. className="absolute inset-0 z-20 flex items-start p-2"
  3620. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3621. >
  3622. {isSelected ? (
  3623. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3624. ) : (
  3625. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3626. )}
  3627. </div>
  3628. )}
  3629. {/* Drop zone overlay */}
  3630. {(isDraggingFile || isDropUploading) && (
  3631. <div
  3632. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3633. isDropUploading
  3634. ? 'bg-bambu-green/10 border-bambu-green/50'
  3635. : canDrop
  3636. ? 'bg-bambu-green/10 border-bambu-green'
  3637. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3638. }`}
  3639. >
  3640. <div className="text-center">
  3641. {isDropUploading ? (
  3642. <>
  3643. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3644. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3645. </>
  3646. ) : canDrop ? (
  3647. <>
  3648. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3649. <p className="text-sm font-medium text-bambu-green">
  3650. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3651. </p>
  3652. </>
  3653. ) : (
  3654. <>
  3655. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3656. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3657. {!hasPermission('library:upload')
  3658. ? t('fileManager.noPermissionUpload')
  3659. : t('fileManager.noPermissionAddToQueue')}
  3660. </p>
  3661. </>
  3662. )}
  3663. </div>
  3664. </div>
  3665. )}
  3666. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3667. {/* Header */}
  3668. <div className={getSpacing()}>
  3669. {/* Top row: Image, Name, Menu */}
  3670. <div className="flex items-start justify-between gap-2">
  3671. <div className="flex items-center gap-3 min-w-0 flex-1">
  3672. {/* Printer Model Image */}
  3673. <img
  3674. src={getPrinterImage(printer.model)}
  3675. alt={printer.model || t('common.printer')}
  3676. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3677. />
  3678. <div className="min-w-0 flex-1">
  3679. <div className="flex items-center justify-between gap-2">
  3680. <div className="flex min-w-0 items-center gap-2">
  3681. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3682. {/* Connection indicator dot for compact mode */}
  3683. {viewMode === 'compact' && (() => {
  3684. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3685. const hasSevere = hmsErrors.some(isSevereHMSError);
  3686. const hasWarning = hmsErrors.length > 0;
  3687. const pipColor = !status?.connected
  3688. ? 'bg-status-error'
  3689. : hasSevere
  3690. ? 'bg-status-error'
  3691. : hasWarning
  3692. ? 'bg-status-warning'
  3693. : 'bg-status-ok';
  3694. const pipTitle = !status?.connected
  3695. ? t('printers.connection.offline')
  3696. : hasWarning
  3697. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3698. : t('printers.connection.connected');
  3699. return (
  3700. <div
  3701. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3702. title={pipTitle}
  3703. />
  3704. );
  3705. })()}
  3706. </div>
  3707. {viewMode === 'compact' && showClearPlateButton && (
  3708. <button
  3709. type="button"
  3710. onClick={() => clearPlateMutation.mutate()}
  3711. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3712. aria-label={t('printers.plateStatus.markCleared')}
  3713. 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"
  3714. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3715. >
  3716. {clearPlateMutation.isPending ? (
  3717. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3718. ) : (
  3719. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3720. )}
  3721. </button>
  3722. )}
  3723. </div>
  3724. <p className="text-sm text-bambu-gray">
  3725. {printer.model || 'Unknown Model'}
  3726. {/* Nozzle Info - only in expanded. Every fitted size, not
  3727. just nozzles[0]: the array is indexed by extruder, so on a
  3728. dual-nozzle machine with two sizes fitted showing the
  3729. first entry alone named one hotend and implied it was the
  3730. whole printer. Deduplicated, so the usual matching pair
  3731. still reads as a single "0.4mm". */}
  3732. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3733. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3734. • {installedNozzleDiameters(status).join(' / ')}mm
  3735. </span>
  3736. )}
  3737. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3738. <span className="ml-2 text-bambu-gray">
  3739. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3740. {Math.round(maintenanceInfo.total_print_hours)}h
  3741. </span>
  3742. )}
  3743. </p>
  3744. </div>
  3745. </div>
  3746. </div>
  3747. {/* Badges row - only in expanded mode */}
  3748. {viewMode === 'expanded' && (
  3749. <div className="mt-2">
  3750. <div className="flex flex-wrap items-center gap-2">
  3751. {/* Connection status badge (or Maintenance pill when out of service).
  3752. Defensive: only swap when is_active is EXPLICITLY false. An
  3753. undefined / missing field defaults to "active" so the regular
  3754. pill renders — matches the backend default and prevents test
  3755. fixtures (or stale clients) from accidentally tripping the
  3756. maintenance UI. */}
  3757. {printer.is_active === false ? (
  3758. <span
  3759. 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"
  3760. title={t('printers.maintenance.subtitle')}
  3761. >
  3762. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3763. {t('printers.maintenance.pillLabel')}
  3764. </span>
  3765. ) : (
  3766. <span
  3767. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3768. status?.connected
  3769. ? 'bg-status-ok/20 text-status-ok'
  3770. : 'bg-status-error/20 text-status-error'
  3771. }`}
  3772. >
  3773. {status?.connected ? (
  3774. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3775. ) : (
  3776. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3777. )}
  3778. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3779. </span>
  3780. )}
  3781. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3782. {printer.is_active !== false && !status?.connected && (
  3783. <button
  3784. onClick={() => setShowDiagnostic(true)}
  3785. 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"
  3786. title={t('diagnostic.runButton')}
  3787. >
  3788. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3789. {t('diagnostic.runButton')}
  3790. </button>
  3791. )}
  3792. {/* Network connection indicator */}
  3793. {status?.connected && status?.wired_network && (
  3794. <span
  3795. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3796. title={t('printers.connection.ethernet', 'Ethernet')}
  3797. >
  3798. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3799. {t('printers.connection.ethernet', 'Ethernet')}
  3800. </span>
  3801. )}
  3802. {/* WiFi signal indicator */}
  3803. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3804. <span
  3805. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3806. wifiSignal >= -50
  3807. ? 'bg-status-ok/20 text-status-ok'
  3808. : wifiSignal >= -60
  3809. ? 'bg-status-ok/20 text-status-ok'
  3810. : wifiSignal >= -70
  3811. ? 'bg-status-warning/20 text-status-warning'
  3812. : wifiSignal >= -80
  3813. ? 'bg-orange-500/20 text-orange-600'
  3814. : 'bg-status-error/20 text-status-error'
  3815. }`}
  3816. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3817. >
  3818. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3819. {wifiSignal}dBm
  3820. </span>
  3821. )}
  3822. {/* HMS Status Indicator */}
  3823. {status?.connected && (() => {
  3824. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3825. return (
  3826. <button
  3827. onClick={() => setShowHMSModal(true)}
  3828. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3829. knownErrors.length > 0
  3830. ? knownErrors.some(isSevereHMSError)
  3831. ? 'bg-status-error/20 text-status-error'
  3832. : 'bg-status-warning/20 text-status-warning'
  3833. : 'bg-status-ok/20 text-status-ok'
  3834. }`}
  3835. title={t('printers.clickToViewHmsErrors')}
  3836. >
  3837. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3838. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3839. </button>
  3840. );
  3841. })()}
  3842. {/* AI failure detection badge (#1546) — always shown while detection
  3843. is enabled for this printer, like the other health badges. Gray
  3844. "Idle" outside a monitored print, class-colored during one. */}
  3845. {aiDetectionEnabled && (() => {
  3846. const cls = aiDetectionClass(aiDetection);
  3847. const colorClass =
  3848. cls === 'failure'
  3849. ? 'bg-status-error/20 text-status-error'
  3850. : cls === 'warning'
  3851. ? 'bg-status-warning/20 text-status-warning'
  3852. : cls === 'safe'
  3853. ? 'bg-status-ok/20 text-status-ok'
  3854. : cls === 'error'
  3855. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3856. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3857. // 'error' and 'unknown' have no score to quote — saying
  3858. // "Safe (0.000)" for a print nothing is looking at is the
  3859. // whole of #2952.
  3860. const title =
  3861. cls === 'error'
  3862. ? t('printers.aiDetection.tooltipError', {
  3863. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3864. })
  3865. : cls === 'unknown'
  3866. ? t('printers.aiDetection.tooltipUnknown')
  3867. : aiDetection
  3868. ? t('printers.aiDetection.tooltip', {
  3869. status: t(`printers.aiDetection.${cls}`),
  3870. score: aiDetection.score.toFixed(3),
  3871. })
  3872. : t('printers.aiDetection.tooltipIdle');
  3873. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3874. return (
  3875. <button
  3876. onClick={() => setShowAiModal(true)}
  3877. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3878. title={title}
  3879. >
  3880. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3881. {t(`printers.aiDetection.${cls}`)}
  3882. </button>
  3883. );
  3884. })()}
  3885. {/* Maintenance Status Indicator */}
  3886. {maintenanceInfo && (
  3887. <button
  3888. onClick={() => navigate('/maintenance')}
  3889. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3890. maintenanceInfo.due_count > 0
  3891. ? 'bg-status-error/20 text-status-error'
  3892. : maintenanceInfo.warning_count > 0
  3893. ? 'bg-status-warning/20 text-status-warning'
  3894. : 'bg-status-ok/20 text-status-ok'
  3895. }`}
  3896. title={
  3897. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3898. ? `${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`
  3899. : t('printers.maintenanceUpToDate')
  3900. }
  3901. >
  3902. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3903. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3904. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3905. : 'OK'}
  3906. </button>
  3907. )}
  3908. {/* Queue Count Badge */}
  3909. {queueCount > 0 && (
  3910. <button
  3911. onClick={() => navigate('/queue')}
  3912. 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"
  3913. title={t('printers.queue.inQueue', { count: queueCount })}
  3914. >
  3915. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3916. {queueCount}
  3917. </button>
  3918. )}
  3919. {/* Firmware Version Badge */}
  3920. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3921. <button
  3922. onClick={() => setShowFirmwareModal(true)}
  3923. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3924. firmwareInfo.update_available
  3925. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3926. : 'bg-status-ok/20 text-status-ok'
  3927. }`}
  3928. title={
  3929. firmwareInfo.update_available
  3930. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3931. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3932. }
  3933. >
  3934. {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)]" />}
  3935. {firmwareInfo.current_version}
  3936. </button>
  3937. ) : status?.firmware_version ? (
  3938. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3939. {status.firmware_version}
  3940. </span>
  3941. ) : null}
  3942. {/* Enclosure Door Badge — models with an actual door sensor.
  3943. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3944. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3945. <span
  3946. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3947. status.door_open
  3948. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3949. : 'bg-status-ok/20 text-status-ok'
  3950. }`}
  3951. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3952. >
  3953. {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)]" />}
  3954. </span>
  3955. )}
  3956. </div>
  3957. </div>
  3958. )}
  3959. </div>
  3960. {/* Delete Confirmation */}
  3961. {showDeleteConfirm && (
  3962. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3963. <Card className="w-full max-w-md mx-4">
  3964. <CardContent>
  3965. <div className="flex items-start gap-3 mb-4">
  3966. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3967. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3968. </div>
  3969. <div>
  3970. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3971. <p className="text-sm text-bambu-gray mt-1">
  3972. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3973. </p>
  3974. </div>
  3975. </div>
  3976. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3977. <label className="flex items-start gap-3 cursor-pointer">
  3978. <input
  3979. type="checkbox"
  3980. checked={deleteArchives}
  3981. onChange={(e) => setDeleteArchives(e.target.checked)}
  3982. 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"
  3983. />
  3984. <div>
  3985. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3986. <p className="text-xs text-bambu-gray mt-0.5">
  3987. {deleteArchives
  3988. ? t('printers.confirm.deleteArchivesNote')
  3989. : t('printers.confirm.keepArchivesNote')}
  3990. </p>
  3991. </div>
  3992. </label>
  3993. </div>
  3994. <div className="flex justify-end gap-2">
  3995. <Button
  3996. variant="secondary"
  3997. onClick={() => {
  3998. setShowDeleteConfirm(false);
  3999. setDeleteArchives(true);
  4000. }}
  4001. >
  4002. {t('common.cancel')}
  4003. </Button>
  4004. <Button
  4005. variant="danger"
  4006. onClick={() => {
  4007. deleteMutation.mutate({ deleteArchives });
  4008. setShowDeleteConfirm(false);
  4009. setDeleteArchives(true);
  4010. }}
  4011. >
  4012. Delete
  4013. </Button>
  4014. </div>
  4015. </CardContent>
  4016. </Card>
  4017. </div>
  4018. )}
  4019. {/* Status — see the equivalent defensive `=== false` check on the
  4020. header pill above for why this is not `!printer.is_active`. */}
  4021. {printer.is_active === false ? (
  4022. // Maintenance mode (#1476) — replaces the cover/progress container
  4023. // so the card keeps the same height. Renders for both compact and
  4024. // expanded view modes so the printer stays visible but plainly
  4025. // out-of-service.
  4026. <>
  4027. {viewMode === 'compact' ? (
  4028. <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">
  4029. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4030. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4031. {t('printers.maintenance.pillLabel')}
  4032. </span>
  4033. </div>
  4034. ) : (
  4035. <>
  4036. <div className="flex items-center gap-2 mb-2">
  4037. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4038. {t('printers.status.title', 'Status')}
  4039. </span>
  4040. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4041. </div>
  4042. <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">
  4043. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4044. <div className="flex-1 min-w-0">
  4045. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4046. {t('printers.maintenance.title')}
  4047. </p>
  4048. <p className="text-xs text-bambu-gray mt-0.5">
  4049. {t('printers.maintenance.subtitle')}
  4050. </p>
  4051. </div>
  4052. <Button
  4053. variant="secondary"
  4054. size="sm"
  4055. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4056. onClick={() => maintenanceMutation.mutate(true)}
  4057. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4058. >
  4059. {t('printers.maintenance.exitButton')}
  4060. </Button>
  4061. </div>
  4062. </>
  4063. )}
  4064. </>
  4065. ) : status?.connected && (
  4066. <>
  4067. {/* Compact: Simple status bar */}
  4068. {viewMode === 'compact' ? (
  4069. (() => {
  4070. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4071. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4072. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4073. ? Math.max(0, Math.min(100, status.progress || 0))
  4074. : showClearPlateButton
  4075. ? 100
  4076. : hasProblem
  4077. ? 100
  4078. : 0;
  4079. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4080. const compactProgressClass = hasProblem
  4081. ? 'bg-status-error'
  4082. : status.state === 'PAUSE'
  4083. ? 'bg-status-warning'
  4084. : 'bg-bambu-green';
  4085. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4086. const hasCompactLayers =
  4087. isActiveCompactPrint &&
  4088. status.layer_num != null &&
  4089. status.total_layers != null &&
  4090. status.total_layers > 0;
  4091. return (
  4092. <>
  4093. <div className="relative mt-2 flex items-center gap-2">
  4094. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4095. <div
  4096. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4097. style={{ width: `${compactProgress}%` }}
  4098. />
  4099. </div>
  4100. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4101. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4102. </span>
  4103. </div>
  4104. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4105. enough to answer "which printer finishes first", which is what a
  4106. wall-mounted fleet view is for. One line of the metrics the
  4107. expanded card already renders, using the same formatters and the
  4108. same ETA styling so S and M read alike. The row keeps its height
  4109. when idle so cards don't shift as prints start and stop. */}
  4110. <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">
  4111. {hasCompactEta && (
  4112. <>
  4113. <span className="flex shrink-0 items-center gap-1">
  4114. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4115. {formatDuration(status.remaining_time! * 60)}
  4116. </span>
  4117. <span
  4118. className="shrink-0 font-medium text-bambu-green"
  4119. title={t('printers.estimatedCompletion')}
  4120. >
  4121. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4122. </span>
  4123. </>
  4124. )}
  4125. {hasCompactLayers && (
  4126. <span className="flex min-w-0 items-center gap-1 truncate">
  4127. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4128. {status.layer_num}/{status.total_layers}
  4129. </span>
  4130. )}
  4131. </div>
  4132. </>
  4133. );
  4134. })()
  4135. ) : (
  4136. /* Expanded: Full status section */
  4137. <>
  4138. <div className="flex items-center gap-2 mb-2">
  4139. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4140. {t('printers.status.title', 'Status')}
  4141. </span>
  4142. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4143. </div>
  4144. {/* Current Print or Idle Placeholder */}
  4145. {(() => {
  4146. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4147. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4148. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4149. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4150. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4151. // A running print always has at least one object, so a count of
  4152. // zero means "not loaded", not "nothing to skip" — after a
  4153. // restart mid-print the list is empty until something rebuilds
  4154. // it. Treating that as nothing-to-skip disabled the only
  4155. // control that opens the modal, and the modal's own fetch is
  4156. // what rebuilds the list, so the print could never get it back.
  4157. // Exactly one object is the real nothing-to-skip case.
  4158. const objectCount = status.printable_objects_count ?? 0;
  4159. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4160. return (
  4161. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4162. <button
  4163. onClick={() => setShowSkipObjectsModal(true)}
  4164. disabled={!canSkipObjects}
  4165. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4166. canSkipObjects
  4167. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4168. : 'text-bambu-gray/30 cursor-not-allowed'
  4169. }`}
  4170. title={
  4171. !hasPermission('printers:control')
  4172. ? t('printers.permission.noControl')
  4173. : !isActivePrint
  4174. ? t('printers.skipObjects.onlyWhilePrinting')
  4175. : objectCount === 1
  4176. ? t('printers.skipObjects.requiresMultiple')
  4177. : t('printers.skipObjects.tooltip')
  4178. }
  4179. >
  4180. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4181. {objectsData && objectsData.skipped_count > 0 && (
  4182. <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">
  4183. {objectsData.skipped_count}
  4184. </span>
  4185. )}
  4186. </button>
  4187. <div className="flex items-stretch gap-2">
  4188. <CoverImage
  4189. url={coverUrl}
  4190. printName={printName || undefined}
  4191. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4192. />
  4193. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4194. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4195. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4196. {plateStatusPill}
  4197. </div>
  4198. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4199. {printName || t('printers.noActiveJob', 'No active job')}
  4200. </p>
  4201. <div className="flex h-3 items-center gap-2 text-sm">
  4202. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4203. <div
  4204. 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`}
  4205. style={{ width: `${progress}%` }}
  4206. />
  4207. </div>
  4208. <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>
  4209. </div>
  4210. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4211. {isActivePrint ? (
  4212. <>
  4213. {status.remaining_time != null && status.remaining_time > 0 && (
  4214. <>
  4215. <span className="flex items-center gap-1">
  4216. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4217. {formatDuration(status.remaining_time * 60)}
  4218. </span>
  4219. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4220. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4221. </span>
  4222. </>
  4223. )}
  4224. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4225. <span className="flex items-center gap-1">
  4226. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4227. {status.layer_num}/{status.total_layers}
  4228. </span>
  4229. )}
  4230. {currentPrintUser && (
  4231. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4232. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4233. {currentPrintUser}
  4234. </span>
  4235. )}
  4236. </>
  4237. ) : lastPrint ? (
  4238. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4239. Last: {lastPrint.print_name || lastPrint.filename}
  4240. {lastPrint.completed_at && (
  4241. <span className="ml-1 text-bambu-gray/60">
  4242. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4243. </span>
  4244. )}
  4245. </p>
  4246. ) : (
  4247. <span>{t('printers.readyToPrint')}</span>
  4248. )}
  4249. </div>
  4250. </div>
  4251. </div>
  4252. <PrinterQueueWidget
  4253. printerId={printer.id}
  4254. printerModel={printer.model}
  4255. loadedFilamentTypes={loadedFilamentTypes}
  4256. loadedFilaments={loadedFilaments}
  4257. loadedVariants={loadedVariants}
  4258. variant="panelExtension"
  4259. />
  4260. </div>
  4261. );
  4262. })()}
  4263. </>
  4264. )}
  4265. {/* Temperatures */}
  4266. {status.temperatures && viewMode === 'expanded' && (() => {
  4267. // Use actual heater states from MQTT stream
  4268. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4269. const bedHeating = status.temperatures.bed_heating || false;
  4270. const chamberHeating = status.temperatures.chamber_heating || false;
  4271. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4272. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4273. const kinds: HeaterSensorKind[] = ['nozzle'];
  4274. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4275. kinds.push('bed');
  4276. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4277. return kinds;
  4278. })();
  4279. // active_extruder: 0=right, 1=left
  4280. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4281. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4282. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4283. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4284. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4285. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4286. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4287. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4288. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4289. 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 ${
  4290. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4291. }`;
  4292. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4293. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4294. // the widget there is at best dead UI and at worst suggests a
  4295. // control that does nothing. Mirrors the enclosure-door badge
  4296. // gate above.
  4297. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4298. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4299. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4300. // show it only when the printer actually reports it (airduct part id 3,
  4301. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4302. // have a built-in chamber fan that's always present, so they keep the
  4303. // existing model-list gate and the "Chamber Fan" label.
  4304. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4305. const chamberFanLabel = isExhaustModel
  4306. ? t('printers.fans.exhaust')
  4307. : t('printers.fans.chamber');
  4308. // Composed rather than either/or so both lists stay live for
  4309. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4310. // where that fan is an add-on kit — actually report it. Written
  4311. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4312. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4313. // which reads as if removing them were safe.
  4314. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4315. const fanItems: {
  4316. key: string;
  4317. label: string;
  4318. value: number;
  4319. Icon: typeof Fan;
  4320. activeClass: string;
  4321. }[] = [
  4322. {
  4323. key: 'part',
  4324. label: t('printers.fans.partCooling'),
  4325. value: status.cooling_fan_speed ?? 0,
  4326. Icon: Fan,
  4327. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4328. },
  4329. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4330. // Only reported (non-null) when the firmware lists airduct part
  4331. // id 10, i.e. when the fan is physically installed. Placed
  4332. // before the right-hand auxiliary fan so the two aux badges read
  4333. // left-to-right in the same order as the physical hardware.
  4334. ...(status.left_aux_fan_speed != null
  4335. ? [
  4336. {
  4337. key: 'aux2',
  4338. label: t('printers.fans.leftAuxiliary'),
  4339. value: status.left_aux_fan_speed,
  4340. Icon: Wind,
  4341. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4342. },
  4343. ]
  4344. : []),
  4345. {
  4346. key: 'aux',
  4347. label: t('printers.fans.auxiliary'),
  4348. value: status.big_fan1_speed ?? 0,
  4349. Icon: Wind,
  4350. activeClass: 'text-blue-600 dark:text-blue-400',
  4351. },
  4352. ...(showChamberFan
  4353. ? [
  4354. {
  4355. key: 'chamber',
  4356. label: chamberFanLabel,
  4357. value: status.big_fan2_speed ?? 0,
  4358. Icon: AirVent,
  4359. activeClass: 'text-green-600 dark:text-green-400',
  4360. },
  4361. ]
  4362. : []),
  4363. ];
  4364. return (
  4365. <>
  4366. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4367. {/* Nozzle temp - combined for dual nozzle */}
  4368. <div
  4369. className={statusControlClass}
  4370. title={statusControlTitle}
  4371. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4372. >
  4373. <button
  4374. type="button"
  4375. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4376. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4377. onClick={(e) => {
  4378. e.stopPropagation();
  4379. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4380. }}
  4381. >
  4382. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4383. </button>
  4384. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4385. {status.temperatures.nozzle_2 !== undefined ? (
  4386. <>
  4387. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4388. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4389. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4390. </p>
  4391. </>
  4392. ) : singleNozzleSlot ? (
  4393. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4394. <div className="cursor-default">
  4395. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4396. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4397. {Math.round(status.temperatures.nozzle || 0)}°C
  4398. </p>
  4399. </div>
  4400. </NozzleSlotHoverCard>
  4401. ) : (
  4402. <>
  4403. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4404. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4405. {Math.round(status.temperatures.nozzle || 0)}°C
  4406. </p>
  4407. </>
  4408. )}
  4409. {statusControlMenu === 'nozzle-temp' && (
  4410. isDualNozzle ? (
  4411. <IndicatorControlPopover
  4412. title="Set Nozzle Temperatures"
  4413. widthClass="w-[300px]"
  4414. popoverWidth={300}
  4415. popoverHeight={260}
  4416. isPending={nozzleTemperatureMutation.isPending}
  4417. onClose={() => setStatusControlMenu(null)}
  4418. >
  4419. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4420. <NozzleTemperatureControlBox
  4421. label="Left Temp"
  4422. current={status.temperatures.nozzle}
  4423. target={status.temperatures.nozzle_target}
  4424. isActive={activeNozzle === 'L'}
  4425. isPending={nozzleTemperatureMutation.isPending}
  4426. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4427. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4428. />
  4429. <NozzleTemperatureControlBox
  4430. label="Right Temp"
  4431. current={status.temperatures.nozzle_2}
  4432. target={status.temperatures.nozzle_2_target}
  4433. isActive={activeNozzle === 'R'}
  4434. isPending={nozzleTemperatureMutation.isPending}
  4435. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4436. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4437. />
  4438. </div>
  4439. </IndicatorControlPopover>
  4440. ) : (
  4441. <IndicatorControlPopover
  4442. title="Set Nozzle Temperature"
  4443. unit="°C"
  4444. customMin={0}
  4445. customMax={320}
  4446. isPending={nozzleTemperatureMutation.isPending}
  4447. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4448. onClose={() => setStatusControlMenu(null)}
  4449. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4450. />
  4451. )
  4452. )}
  4453. </div>
  4454. <div
  4455. className={statusControlClass}
  4456. title={statusControlTitle}
  4457. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4458. >
  4459. <button
  4460. type="button"
  4461. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4462. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4463. onClick={(e) => {
  4464. e.stopPropagation();
  4465. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4466. }}
  4467. >
  4468. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4469. </button>
  4470. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4471. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4472. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4473. {Math.round(status.temperatures.bed || 0)}°C
  4474. </p>
  4475. {statusControlMenu === 'bed-temp' && (
  4476. <IndicatorControlPopover
  4477. title="Set Bed Temperature"
  4478. unit="°C"
  4479. customMin={0}
  4480. customMax={140}
  4481. isPending={bedTemperatureMutation.isPending}
  4482. options={buildPresetOptions(bedTempPresets, 'C')}
  4483. onClose={() => setStatusControlMenu(null)}
  4484. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4485. />
  4486. )}
  4487. </div>
  4488. {status.temperatures.chamber !== undefined && (() => {
  4489. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4490. // but can't act on M141, so we keep the card read-only there.
  4491. const hasChamberHeater = status.supports_chamber_heater === true;
  4492. return (
  4493. <div
  4494. className={hasChamberHeater
  4495. ? statusControlClass
  4496. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4497. title={hasChamberHeater ? statusControlTitle : undefined}
  4498. onClick={hasChamberHeater
  4499. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4500. : undefined}
  4501. >
  4502. <button
  4503. type="button"
  4504. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4505. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4506. onClick={(e) => {
  4507. e.stopPropagation();
  4508. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4509. }}
  4510. >
  4511. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4512. </button>
  4513. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4514. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4515. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4516. {Math.round(status.temperatures.chamber || 0)}°C
  4517. </p>
  4518. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4519. <IndicatorControlPopover
  4520. title="Set Chamber Temperature"
  4521. unit="°C"
  4522. customMin={0}
  4523. customMax={MAX_CHAMBER_TEMP_C}
  4524. isPending={chamberTemperatureMutation.isPending}
  4525. options={buildPresetOptions(chamberTempPresets, 'C')}
  4526. onClose={() => setStatusControlMenu(null)}
  4527. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4528. />
  4529. )}
  4530. </div>
  4531. );
  4532. })()}
  4533. {/* Active nozzle indicator for dual-nozzle printers */}
  4534. {isDualNozzle && (
  4535. <DualNozzleHoverCard
  4536. leftSlot={leftNozzleSlot}
  4537. rightSlot={rightNozzleSlot}
  4538. activeNozzle={activeNozzle}
  4539. filamentInfo={filamentInfo}
  4540. >
  4541. <div
  4542. 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 ${
  4543. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4544. }`}
  4545. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4546. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4547. >
  4548. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4549. <div className="flex items-center gap-2">
  4550. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4551. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4552. </span>
  4553. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4554. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4555. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4556. </span>
  4557. </div>
  4558. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4559. {statusControlMenu === 'nozzle-select' && (
  4560. <IndicatorControlPopover
  4561. title="Set Nozzle Selection"
  4562. widthClass="w-[300px]"
  4563. popoverWidth={300}
  4564. popoverHeight={140}
  4565. isPending={selectExtruderMutation.isPending}
  4566. options={[
  4567. { label: 'Left', value: 1 },
  4568. { label: 'Right', value: 0 },
  4569. ]}
  4570. onClose={() => setStatusControlMenu(null)}
  4571. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4572. />
  4573. )}
  4574. </div>
  4575. </DualNozzleHoverCard>
  4576. )}
  4577. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4578. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4579. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4580. )}
  4581. </div>
  4582. <div className="mt-2 flex items-center gap-1.5">
  4583. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4584. const active = value > 0;
  4585. return (
  4586. <div
  4587. key={key}
  4588. 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 ${
  4589. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4590. }`}
  4591. title={canUseStatusControls ? label : statusControlTitle}
  4592. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4593. >
  4594. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4595. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4596. {value}%
  4597. </span>
  4598. {statusControlMenu === `fan-${key}` && (
  4599. <IndicatorControlPopover
  4600. title={`Set ${label} Speed`}
  4601. unit="%"
  4602. customMin={0}
  4603. customMax={100}
  4604. isPending={fanSpeedMutation.isPending}
  4605. options={buildPresetOptions(fanSpeedPresets, '%')}
  4606. onClose={() => setStatusControlMenu(null)}
  4607. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4608. />
  4609. )}
  4610. </div>
  4611. );
  4612. })}
  4613. </div>
  4614. </>
  4615. );
  4616. })()}
  4617. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4618. {/* Controls */}
  4619. {viewMode === 'expanded' && (() => {
  4620. // Determine print state for control buttons
  4621. const isRunning = status.state === 'RUNNING';
  4622. const isPaused = status.state === 'PAUSE';
  4623. const isPrinting = isRunning || isPaused;
  4624. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4625. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4626. 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';
  4627. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4628. return (
  4629. <div className="mt-3">
  4630. {/* Section Header */}
  4631. <div className="flex items-center gap-2 mb-2">
  4632. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4633. {t('printers.controls')}
  4634. </span>
  4635. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4636. </div>
  4637. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4638. {/* Left: Secondary controls */}
  4639. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4640. <button
  4641. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4642. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4643. className={`${iconControlClass} ${
  4644. status.chamber_light
  4645. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4646. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4647. }`}
  4648. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4649. >
  4650. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4651. </button>
  4652. {/* Airduct Mode (P2S / X2D / H2*) */}
  4653. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4654. const isHeating = status.airduct_mode === 1;
  4655. const Icon = isHeating ? Flame : Snowflake;
  4656. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4657. 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';
  4658. return (
  4659. <div className="relative">
  4660. <button
  4661. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4662. disabled={!hasPermission('printers:control')}
  4663. className={`${iconControlClass} ${bg}`}
  4664. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4665. >
  4666. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4667. </button>
  4668. {showAirductMenu === printer.id && (
  4669. <>
  4670. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4671. <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]">
  4672. {([
  4673. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4674. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4675. ] as const).map(({ mode, label, modeId }) => (
  4676. <button
  4677. key={mode}
  4678. onClick={() => {
  4679. airductMutation.mutate(mode);
  4680. setShowAirductMenu(null);
  4681. }}
  4682. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4683. status.airduct_mode === modeId
  4684. ? 'text-bambu-green bg-bambu-green/10'
  4685. : 'text-white hover:bg-bambu-dark-tertiary'
  4686. }`}
  4687. >
  4688. {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)]" />}
  4689. {label}
  4690. </button>
  4691. ))}
  4692. </div>
  4693. </>
  4694. )}
  4695. </div>
  4696. );
  4697. })()}
  4698. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4699. {(() => {
  4700. const canControl = hasPermission('printers:control');
  4701. const disabled = isPrinting || !canControl;
  4702. 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';
  4703. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4704. // nozzle-bed gap that means the same thing on every printer, so the
  4705. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4706. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4707. // plate toward the nozzle and closes it.
  4708. const zMovesToolhead = isBedSlinger(printer.model);
  4709. const requestZJog = (arrow: 'up' | 'down') => {
  4710. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4711. // No not-homed gate here, and no endstop bypass to gate either:
  4712. // since #2579 the jog is a bare move that never touches M211. That
  4713. // does not make it clamped — the firmware ignores soft endstops on
  4714. // MQTT G-code entirely, which is what the banner above warns about.
  4715. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4716. };
  4717. const requestXyJog = (x: number, y: number) => {
  4718. xyJogMutation.mutate({ x, y });
  4719. };
  4720. const requestExtruderJog = (distance: number) => {
  4721. extruderJogMutation.mutate(distance);
  4722. };
  4723. return (
  4724. <div className="relative">
  4725. <button
  4726. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4727. disabled={disabled}
  4728. className={`${iconControlClass} ${
  4729. disabled
  4730. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4731. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4732. }`}
  4733. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4734. >
  4735. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4736. </button>
  4737. {showBedJogMenu === printer.id && (
  4738. <>
  4739. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4740. <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">
  4741. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4742. {t('printers.bedJog.title')}
  4743. </div>
  4744. <div className="h-px bg-bambu-dark-tertiary" />
  4745. {/* #2579: Bambu firmware does not enforce soft endstops on
  4746. G-code sent over MQTT, so manual moves can drive past the
  4747. travel limits and cause a collision. Not fixable from our
  4748. side — warn prominently. */}
  4749. <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">
  4750. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4751. <span>{t('printers.bedJog.limitWarning')}</span>
  4752. </div>
  4753. <div className="h-px bg-bambu-dark-tertiary" />
  4754. <div className="flex justify-center px-3 py-2.5">
  4755. <div className="flex items-center justify-center gap-3">
  4756. <div className="grid grid-cols-3 gap-1">
  4757. <div />
  4758. <button
  4759. onClick={() => requestXyJog(0, bedJogStep)}
  4760. disabled={xyJogMutation.isPending}
  4761. className={jogButtonClass}
  4762. aria-label="Move Y forward"
  4763. >
  4764. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4765. </button>
  4766. <div />
  4767. <button
  4768. onClick={() => requestXyJog(-bedJogStep, 0)}
  4769. disabled={xyJogMutation.isPending}
  4770. className={jogButtonClass}
  4771. aria-label="Move X left"
  4772. >
  4773. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4774. </button>
  4775. <button
  4776. onClick={() => {
  4777. setShowBedJogMenu(null);
  4778. homeAxesMutation.mutate('all');
  4779. }}
  4780. disabled={homeAxesMutation.isPending}
  4781. className={jogButtonClass}
  4782. aria-label={t('printers.bedJog.homeZ')}
  4783. >
  4784. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4785. </button>
  4786. <button
  4787. onClick={() => requestXyJog(bedJogStep, 0)}
  4788. disabled={xyJogMutation.isPending}
  4789. className={jogButtonClass}
  4790. aria-label="Move X right"
  4791. >
  4792. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4793. </button>
  4794. <div />
  4795. <button
  4796. onClick={() => requestXyJog(0, -bedJogStep)}
  4797. disabled={xyJogMutation.isPending}
  4798. className={jogButtonClass}
  4799. aria-label="Move Y back"
  4800. >
  4801. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4802. </button>
  4803. <div />
  4804. </div>
  4805. <div className="flex flex-col items-center gap-1">
  4806. <button
  4807. onClick={() => requestZJog('up')}
  4808. disabled={bedJogMutation.isPending}
  4809. className={jogButtonClass}
  4810. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4811. >
  4812. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4813. </button>
  4814. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4815. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4816. </div>
  4817. <button
  4818. onClick={() => requestZJog('down')}
  4819. disabled={bedJogMutation.isPending}
  4820. className={jogButtonClass}
  4821. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4822. >
  4823. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4824. </button>
  4825. </div>
  4826. <div className="flex flex-col items-center gap-1">
  4827. <button
  4828. onClick={() => requestExtruderJog(-bedJogStep)}
  4829. disabled={extruderJogMutation.isPending}
  4830. className={jogButtonClass}
  4831. aria-label="Retract filament"
  4832. >
  4833. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4834. </button>
  4835. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4836. <span className="text-sm font-semibold leading-none">E</span>
  4837. </div>
  4838. <button
  4839. onClick={() => requestExtruderJog(bedJogStep)}
  4840. disabled={extruderJogMutation.isPending}
  4841. className={jogButtonClass}
  4842. aria-label="Extrude filament"
  4843. >
  4844. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4845. </button>
  4846. </div>
  4847. </div>
  4848. </div>
  4849. <div className="h-px bg-bambu-dark-tertiary" />
  4850. <div className="px-3 pt-2.5 pb-3">
  4851. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4852. {t('printers.bedJog.step')}
  4853. </div>
  4854. <div className="flex gap-1">
  4855. {[1, 10, 50].map((step) => (
  4856. <button
  4857. key={step}
  4858. onClick={() => setBedJogStep(step)}
  4859. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4860. bedJogStep === step
  4861. ? 'bg-bambu-green/20 text-bambu-green'
  4862. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4863. }`}
  4864. >
  4865. {step}
  4866. </button>
  4867. ))}
  4868. </div>
  4869. </div>
  4870. </div>
  4871. </>
  4872. )}
  4873. </div>
  4874. );
  4875. })()}
  4876. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4877. <button
  4878. onClick={handleTogglePlateDetection}
  4879. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4880. className={`${iconControlClass} rounded-r-none ${
  4881. printer.plate_detection_enabled
  4882. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4883. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4884. }`}
  4885. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4886. >
  4887. {plateDetectionMutation.isPending ? (
  4888. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4889. ) : (
  4890. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4891. )}
  4892. </button>
  4893. <button
  4894. onClick={handleOpenPlateManagement}
  4895. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4896. 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 ${
  4897. printer.plate_detection_enabled
  4898. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4899. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4900. }`}
  4901. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4902. >
  4903. {isCheckingPlate ? (
  4904. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4905. ) : (
  4906. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4907. )}
  4908. </button>
  4909. </div>
  4910. {/* Print Speed */}
  4911. {(() => (
  4912. <div className="relative">
  4913. <button
  4914. data-testid="speed-control"
  4915. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4916. disabled={!isPrinting || !hasPermission('printers:control')}
  4917. className={`${iconControlClass} ${
  4918. isPrinting
  4919. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4920. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4921. }`}
  4922. title={isPrinting ? t('printers.speed.title') : undefined}
  4923. >
  4924. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4925. </button>
  4926. {showSpeedMenu === printer.id && (
  4927. <>
  4928. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4929. <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]">
  4930. {([
  4931. { mode: 1, label: t('printers.speed.silent') },
  4932. { mode: 2, label: t('printers.speed.standard') },
  4933. { mode: 3, label: t('printers.speed.sport') },
  4934. { mode: 4, label: t('printers.speed.ludicrous') },
  4935. ] as const).map(({ mode, label }) => (
  4936. <button
  4937. key={mode}
  4938. onClick={() => {
  4939. printSpeedMutation.mutate(mode);
  4940. setShowSpeedMenu(null);
  4941. }}
  4942. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4943. status.speed_level === mode
  4944. ? 'text-bambu-green bg-bambu-green/10'
  4945. : 'text-white hover:bg-bambu-dark-tertiary'
  4946. }`}
  4947. >
  4948. {label}
  4949. </button>
  4950. ))}
  4951. </div>
  4952. </>
  4953. )}
  4954. </div>
  4955. ))()}
  4956. </div>
  4957. {/* Right: Print Control Buttons */}
  4958. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4959. {/* Pause/Resume button */}
  4960. {(() => {
  4961. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4962. return (
  4963. <button
  4964. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4965. disabled={pauseUnavailable}
  4966. className={`
  4967. ${printControlClass}
  4968. ${pauseUnavailable
  4969. ? unavailablePrintActionClass
  4970. : isPaused
  4971. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4972. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4973. }
  4974. `}
  4975. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4976. >
  4977. {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)]" />}
  4978. {isPaused ? t('printers.resume') : t('printers.pause')}
  4979. </button>
  4980. );
  4981. })()}
  4982. {/* Stop button */}
  4983. {(() => {
  4984. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4985. return (
  4986. <button
  4987. onClick={() => setShowStopConfirm(true)}
  4988. disabled={stopUnavailable}
  4989. className={`
  4990. ${printControlClass}
  4991. ${stopUnavailable
  4992. ? unavailablePrintActionClass
  4993. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4994. }
  4995. `}
  4996. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4997. >
  4998. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4999. {t('printers.stop')}
  5000. </button>
  5001. );
  5002. })()}
  5003. </div>
  5004. </div>
  5005. </div>
  5006. );
  5007. })()}
  5008. {/* AMS Units - 2-Column Grid Layout */}
  5009. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  5010. // Separate regular AMS (4-tray) from HT AMS (1-tray), by unit id
  5011. const regularAms = amsData.filter(ams => !isAmsHtUnit(ams.id));
  5012. const htAms = amsData.filter(ams => isAmsHtUnit(ams.id));
  5013. // The external spool can only be hidden while some AMS remains to
  5014. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  5015. // filament section, so the toggle is not offered there and a stored
  5016. // preference from a printer that later lost its AMS cannot blank the
  5017. // row either — both read through canHideExternalSpool.
  5018. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  5019. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5020. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5021. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5022. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5023. // floating point, and that lands verbatim in the DOM.
  5024. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5025. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5026. // already grow to fill the row, so the 3.5rem is a floor they sit
  5027. // well above in practice -- raising it just costs a unit its place
  5028. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5029. // its line, and flex-grow stretches its single slot across the whole
  5030. // card. The AMS-HT's own width does scale, below, because its
  5031. // readings sit beside the slot rather than under it.
  5032. const slotMinWidth = '3.5rem';
  5033. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5034. // The AMS-HT holds a single spool, and its slot is the only thing
  5035. // on that row able to grow -- so it swallowed every spare pixel and
  5036. // shoved the temperature and humidity hard against the card's edge.
  5037. // Capping it at roughly two ordinary slots keeps the readings clear
  5038. // of the edge; the cap scales because the text inside the slot does.
  5039. const htSlotStyle: React.CSSProperties = {
  5040. minWidth: slotMinWidth,
  5041. maxWidth: scaledRem(7.25),
  5042. };
  5043. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5044. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5045. });
  5046. // #1762 (comment 2): while a print is running/paused, overlay a small
  5047. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5048. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5049. // staged to a printer with mismatched filament: the wrong-slot pill
  5050. // is visible the instant printing starts.
  5051. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5052. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5053. ? status.ams_mapping
  5054. : [];
  5055. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5056. const boundedSlotCount = Math.max(1, slotCount);
  5057. const gapCount = Math.max(0, boundedSlotCount - 1);
  5058. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5059. return {
  5060. flex: `1 1 ${minWidth}`,
  5061. minWidth,
  5062. };
  5063. };
  5064. return (
  5065. <div className="mt-3">
  5066. {/* Section Header */}
  5067. <div className="flex items-center gap-2 mb-2">
  5068. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5069. {t('printers.filaments')}
  5070. </span>
  5071. <AmsBackupBadge
  5072. state={status.ams_filament_backup}
  5073. onClick={() => setAmsBackupModalOpen(true)}
  5074. />
  5075. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5076. {/* Offered only when an AMS is present: on a printer that
  5077. feeds from the external spool alone, hiding it would
  5078. empty the row entirely (#1782). */}
  5079. {canHideExternalSpool && (
  5080. <>
  5081. <ExternalSpoolToggle
  5082. hidden={externalSpoolHidden}
  5083. onClick={toggleExternalSpool}
  5084. />
  5085. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5086. </>
  5087. )}
  5088. </div>
  5089. {/* AMS Content */}
  5090. <div className="flex flex-wrap gap-2">
  5091. {/* Regular AMS units */}
  5092. {regularAms.map((ams) => {
  5093. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5094. return (
  5095. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5096. {/* Header: Label + Stats (no icon) */}
  5097. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5098. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5099. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5100. <AmsNameHoverCard
  5101. ams={ams}
  5102. printerId={printer.id}
  5103. label={getAmsLabel(ams.id)}
  5104. amsLabels={amsLabels}
  5105. canEdit={hasPermission('printers:update')}
  5106. onSaved={refetchAmsLabels}
  5107. >
  5108. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5109. {amsLabels?.[ams.id] || getAmsLabel(ams.id)}
  5110. </span>
  5111. </AmsNameHoverCard>
  5112. {sideBadge?.kind === 'inlet' ? (
  5113. <InletBadge
  5114. inlet={sideBadge.inlet}
  5115. title={t('printers.amsSwitchInletTooltip', {
  5116. inlet: sideBadge.inlet,
  5117. side: FTS_INLET_SIDE[sideBadge.inlet],
  5118. })}
  5119. />
  5120. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5121. <NozzleBadge side={sideBadge.side} />
  5122. ) : null}
  5123. </div>
  5124. {(ams.humidity != null || ams.temp != null) && (
  5125. <div className="flex shrink-0 items-center gap-1.5">
  5126. {ams.humidity != null && (
  5127. <HumidityIndicator
  5128. humidity={ams.humidity}
  5129. goodThreshold={amsThresholds?.humidityGood}
  5130. fairThreshold={amsThresholds?.humidityFair}
  5131. onClick={() => setAmsHistoryModal({
  5132. amsId: ams.id,
  5133. amsLabel: getAmsLabel(ams.id),
  5134. mode: 'humidity',
  5135. })}
  5136. compact
  5137. />
  5138. )}
  5139. {ams.temp != null && (
  5140. <div className="mr-1">
  5141. <TemperatureIndicator
  5142. temp={ams.temp}
  5143. goodThreshold={amsThresholds?.tempGood}
  5144. fairThreshold={amsThresholds?.tempFair}
  5145. onClick={() => setAmsHistoryModal({
  5146. amsId: ams.id,
  5147. amsLabel: getAmsLabel(ams.id),
  5148. mode: 'temperature',
  5149. })}
  5150. compact
  5151. />
  5152. </div>
  5153. )}
  5154. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5155. Screen-only models (P1 series) keep the control but can't
  5156. be commanded: it stays disabled and says why (#2533). */}
  5157. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5158. <button
  5159. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5160. onClick={(e) => {
  5161. if (ams.dry_time > 0) {
  5162. stopDryingMutation.mutate(ams.id);
  5163. } else if (dryingPopoverAmsId === ams.id) {
  5164. setDryingPopoverAmsId(null);
  5165. } else {
  5166. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5167. }
  5168. }}
  5169. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5170. ams.dry_time > 0
  5171. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5172. : status.drying_screen_only || ams.dry_sf_reason?.length
  5173. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5174. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5175. }`}
  5176. 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')}
  5177. >
  5178. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5179. </button>
  5180. )}
  5181. </div>
  5182. )}
  5183. </div>
  5184. {/* Drying status bar. A dry_time whose countdown is not
  5185. ticking, with no active drying phase (a parked command —
  5186. e.g. an H2D mid-print already powering other drying — or
  5187. a paused cycle), is shown as "not running", not as an
  5188. active cycle: the amber badge claiming a running dry
  5189. that the AMS never began is how this was found. */}
  5190. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5191. <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')}>
  5192. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5193. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5194. {ams.dry_filament && (
  5195. <span className="text-slate-500/90 dark:text-slate-400/80">
  5196. {ams.dry_target_temp != null
  5197. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5198. : ams.dry_filament}
  5199. </span>
  5200. )}
  5201. {!status.drying_screen_only && (
  5202. <button
  5203. onClick={() => stopDryingMutation.mutate(ams.id)}
  5204. disabled={stopDryingMutation.isPending}
  5205. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5206. title={t('printers.drying.stop')}
  5207. >
  5208. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5209. </button>
  5210. )}
  5211. </div>
  5212. )}
  5213. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5214. <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)]">
  5215. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5216. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5217. {/* The temperature is only ever known from the target we
  5218. cached when sending the command — the filament can also
  5219. be read off a uniformly loaded unit, so it can outlive
  5220. the temperature (#2759). */}
  5221. {ams.dry_filament && (
  5222. <span className="text-amber-700/80 dark:text-amber-300/70">
  5223. {ams.dry_target_temp != null
  5224. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5225. : ams.dry_filament}
  5226. </span>
  5227. )}
  5228. <span className="text-amber-700/80 dark:text-amber-300/70">
  5229. {t('printers.drying.timeRemaining', {
  5230. time: ams.dry_time >= 60
  5231. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5232. : `${ams.dry_time}m`
  5233. })}
  5234. </span>
  5235. {/* A cycle on a screen-only model was started at the printer
  5236. and can only be stopped there (#2533). */}
  5237. {!status.drying_screen_only && (
  5238. <button
  5239. onClick={() => stopDryingMutation.mutate(ams.id)}
  5240. disabled={stopDryingMutation.isPending}
  5241. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5242. title={t('printers.drying.stop')}
  5243. >
  5244. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5245. </button>
  5246. )}
  5247. </div>
  5248. )}
  5249. {/* Slots grid: 4 columns - always render 4 slots */}
  5250. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5251. {[0, 1, 2, 3].map((slotIdx) => {
  5252. // Find tray data for this slot (may be undefined if data incomplete)
  5253. const tray = trayForSlot(ams.tray, slotIdx);
  5254. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5255. const isEmpty = !tray?.tray_type;
  5256. const emptyKind = getEmptySlotKind(tray);
  5257. // Check if this is the currently loaded tray
  5258. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5259. const globalTrayId = ams.id * 4 + slotIdx;
  5260. const isActive = effectiveTrayNow === globalTrayId;
  5261. // Runout guidance (#2587): the slot the paused print now
  5262. // expects filament in, and the slot that ran out.
  5263. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5264. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5265. // Get cloud preset info if available
  5266. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5267. // Get saved slot preset mapping (for user-configured slots)
  5268. const slotPreset = slotPresets?.[globalTrayId];
  5269. // Only trusted while it still describes what the printer reports in the
  5270. // slot: the row survives a spool swap, and the display chain below puts
  5271. // it ahead of the live filament id (see slotPresetDescribesTray).
  5272. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5273. ? slotPreset?.preset_name
  5274. : undefined;
  5275. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5276. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5277. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5278. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5279. // Slot-assigned-only spool fill (no tag link required)
  5280. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5281. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5282. : undefined;
  5283. const slotSpoolForFill = slotAssignmentForFill
  5284. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5285. : undefined;
  5286. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5287. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5288. : null;
  5289. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5290. const inventoryFill = (() => {
  5291. const sp = inventoryAssignment?.spool;
  5292. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5293. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5294. }
  5295. return null;
  5296. })();
  5297. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5298. // (inventory weight_used may be stale or over-counted — #676)
  5299. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5300. ? null : inventoryFill;
  5301. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5302. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5303. : resolvedInventoryFill !== null ? 'inventory' as const
  5304. : hasFillLevel ? 'ams' as const
  5305. : undefined;
  5306. // Build filament data for hover card
  5307. const filamentData = tray?.tray_type ? {
  5308. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5309. // Spoolman spool name wins over cloud lookup so a slot bound to
  5310. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5311. // Design PLA") instead of whatever the printer's filament_id
  5312. // resolves to in the cloud catalog (often "Generic PLA" for
  5313. // P-prefix local presets). Spoolman's filament.name is just the
  5314. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5315. // the hover card shows "Devil Design PLA Basic" rather than the
  5316. // vendor-less form. Strip the "@<printer>..." suffix that
  5317. // BambuStudio appends to user-preset names.
  5318. 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,
  5319. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5320. colorHex: tray.tray_color || null,
  5321. kFactor: formatKValue(tray.k),
  5322. fillLevel: effectiveFill,
  5323. trayUuid: tray.tray_uuid || null,
  5324. tagUid: tray.tag_uid || null,
  5325. fillSource,
  5326. } : null;
  5327. // Check if this specific slot is being refreshed
  5328. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5329. refreshingSlot?.slotId === slotIdx;
  5330. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5331. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5332. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5333. ? `P${activePrintSlotIdx + 1}`
  5334. : null;
  5335. // Slot visual content (goes inside hover card)
  5336. const slotVisual = (
  5337. <div
  5338. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5339. isExpectedSlot
  5340. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5341. : isRanOutSlot
  5342. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5343. : isActive
  5344. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5345. : ''
  5346. }`}
  5347. >
  5348. {isExpectedSlot && (
  5349. <span
  5350. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5351. title={t('printers.expectedSlot.title')}
  5352. 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"
  5353. >
  5354. ↓
  5355. </span>
  5356. )}
  5357. {activePrintSlotLabel && (
  5358. <span
  5359. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5360. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5361. 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"
  5362. >
  5363. {activePrintSlotLabel}
  5364. </span>
  5365. )}
  5366. {/* Filament color circle with 1-based slot number centered inside */}
  5367. <FilamentSlotCircle
  5368. trayColor={tray?.tray_color}
  5369. trayType={tray?.tray_type}
  5370. isEmpty={isEmpty}
  5371. emptyKind={emptyKind}
  5372. slotNumber={slotIdx + 1}
  5373. />
  5374. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5375. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5376. </div>
  5377. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5378. {/* Fill bar */}
  5379. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5380. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5381. <div
  5382. className="h-full rounded-full transition-all"
  5383. style={{
  5384. width: `${effectiveFill}%`,
  5385. backgroundColor: getFillBarColor(effectiveFill),
  5386. }}
  5387. />
  5388. )}
  5389. </div>
  5390. </div>
  5391. );
  5392. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5393. return (
  5394. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5395. {/* Loading overlay during RFID re-read */}
  5396. {isRefreshing && (
  5397. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5398. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5399. </div>
  5400. )}
  5401. {/* Hover card wraps only the visual content */}
  5402. {filamentData ? (
  5403. <FilamentHoverCard
  5404. data={filamentData}
  5405. actions={renderAmsSlotActions({
  5406. amsId: ams.id,
  5407. slotId: slotIdx,
  5408. loadTrayId: ams.id * 4 + slotIdx,
  5409. isRefreshing,
  5410. })}
  5411. spoolman={{
  5412. enabled: spoolmanEnabled,
  5413. // #1457: slot assignment is the user's most explicit action — it must
  5414. // outrank the tag-link, which can be stale when a non-RFID slot's
  5415. // fallback tag is still attached to a previous spool in Spoolman.
  5416. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5417. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5418. spoolmanUrl,
  5419. syncMode: spoolmanSyncMode,
  5420. // Suppress Link button when slot is already occupied by ANY assignment
  5421. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5422. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5423. // still appearing on slots with a local Devil Design PLA assigned.
  5424. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5425. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5426. setLinkSpoolModal({
  5427. tagUid: filamentData.tagUid || linkTag,
  5428. trayUuid: filamentData.trayUuid || '',
  5429. printerId: printer.id,
  5430. amsId: ams.id,
  5431. trayId: slotIdx,
  5432. });
  5433. } : undefined,
  5434. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5435. }}
  5436. inventory={(() => {
  5437. if (spoolmanEnabled) {
  5438. if (spoolmanLoading) return undefined;
  5439. const slotAssignment = slotAssignmentForFill;
  5440. const spoolmanSpool = slotSpoolForFill;
  5441. return {
  5442. assignedSpool: spoolmanSpool ? {
  5443. id: spoolmanSpool.id,
  5444. material: spoolmanSpool.material,
  5445. subtype: spoolmanSpool.subtype,
  5446. brand: spoolmanSpool.brand ?? null,
  5447. color_name: spoolmanSpool.color_name ?? null,
  5448. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5449. // The spool's own swatch (#2967). Spoolman carries the
  5450. // extra stops but has no effect field at all, so those
  5451. // rolls gradient and never shimmer.
  5452. rgba: spoolmanSpool.rgba ?? null,
  5453. extra_colors: spoolmanSpool.extra_colors ?? null,
  5454. effect_type: spoolmanSpool.effect_type ?? null,
  5455. remainingWeightGrams: spoolmanSpool.label_weight
  5456. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5457. : undefined,
  5458. } : null,
  5459. onAssignSpool: () => setAssignSpoolModal({
  5460. printerId: printer.id,
  5461. amsId: ams.id,
  5462. trayId: slotIdx,
  5463. trayInfo: {
  5464. type: tray?.tray_type || filamentData.profile,
  5465. material: tray?.tray_type ?? undefined,
  5466. profile: filamentData.profile,
  5467. color: filamentData.colorHex || '',
  5468. location: `${getAmsLabel(ams.id)} Slot ${slotIdx + 1}`,
  5469. },
  5470. }),
  5471. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5472. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5473. };
  5474. }
  5475. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5476. return {
  5477. assignedSpool: assignment?.spool ? {
  5478. id: assignment.spool.id,
  5479. material: assignment.spool.material,
  5480. subtype: assignment.spool.subtype,
  5481. brand: assignment.spool.brand,
  5482. color_name: assignment.spool.color_name,
  5483. // The spool's own swatch (#2967).
  5484. rgba: assignment.spool.rgba ?? null,
  5485. extra_colors: assignment.spool.extra_colors ?? null,
  5486. effect_type: assignment.spool.effect_type ?? null,
  5487. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5488. } : null,
  5489. onAssignSpool: () => setAssignSpoolModal({
  5490. printerId: printer.id,
  5491. amsId: ams.id,
  5492. trayId: slotIdx,
  5493. trayInfo: {
  5494. type: tray?.tray_type || filamentData.profile,
  5495. material: tray?.tray_type ?? undefined,
  5496. profile: filamentData.profile,
  5497. color: filamentData.colorHex || '',
  5498. location: `${getAmsLabel(ams.id)} Slot ${slotIdx + 1}`,
  5499. },
  5500. }),
  5501. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5502. isAssigned: !!assignment || isBambuLabSpool(tray),
  5503. };
  5504. })()}
  5505. configureSlot={{
  5506. enabled: hasPermission('printers:control'),
  5507. onConfigure: () => setConfigureSlotModal({
  5508. amsId: ams.id,
  5509. trayId: slotIdx,
  5510. trayType: tray?.tray_type || undefined,
  5511. trayColor: tray?.tray_color || undefined,
  5512. traySubBrands: tray?.tray_sub_brands || undefined,
  5513. trayInfoIdx: tray?.tray_info_idx || undefined,
  5514. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5515. caliIdx: tray?.cali_idx,
  5516. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5517. }),
  5518. }}
  5519. >
  5520. {slotVisual}
  5521. </FilamentHoverCard>
  5522. ) : (
  5523. <EmptySlotHoverCard
  5524. kind={emptyKind ?? undefined}
  5525. actions={renderAmsSlotActions({
  5526. amsId: ams.id,
  5527. slotId: slotIdx,
  5528. loadTrayId: ams.id * 4 + slotIdx,
  5529. isRefreshing,
  5530. })}
  5531. configureSlot={{
  5532. enabled: hasPermission('printers:control'),
  5533. onConfigure: () => setConfigureSlotModal({
  5534. amsId: ams.id,
  5535. trayId: slotIdx,
  5536. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5537. }),
  5538. }}
  5539. onAssignSpool={() => setAssignSpoolModal({
  5540. printerId: printer.id,
  5541. amsId: ams.id,
  5542. trayId: slotIdx,
  5543. trayInfo: {
  5544. type: '',
  5545. material: undefined,
  5546. profile: '',
  5547. color: '',
  5548. location: `${getAmsLabel(ams.id)} Slot ${slotIdx + 1}`,
  5549. },
  5550. })}
  5551. >
  5552. {slotVisual}
  5553. </EmptySlotHoverCard>
  5554. )}
  5555. </div>
  5556. );
  5557. })}
  5558. </div>
  5559. </div>
  5560. );
  5561. })}
  5562. {/* HT AMS units */}
  5563. {htAms.map((ams) => {
  5564. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5565. const tray = ams.tray[0];
  5566. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5567. const isEmpty = !tray?.tray_type;
  5568. const emptyKind = getEmptySlotKind(tray);
  5569. // Check if this is the currently loaded tray
  5570. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5571. const isActive = effectiveTrayNow === globalTrayId;
  5572. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5573. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5574. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5575. // Get cloud preset info if available
  5576. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5577. // Get saved slot preset mapping (for user-configured slots)
  5578. const slotPreset = slotPresets?.[globalTrayId];
  5579. // Only trusted while it still describes what the printer reports in the
  5580. // slot: the row survives a spool swap, and the display chain below puts
  5581. // it ahead of the live filament id (see slotPresetDescribesTray).
  5582. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5583. ? slotPreset?.preset_name
  5584. : undefined;
  5585. const htSlotId = tray?.id ?? 0;
  5586. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5587. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5588. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5589. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5590. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5591. const htInventoryFill = (() => {
  5592. const sp = htInventoryAssignment?.spool;
  5593. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5594. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5595. }
  5596. return null;
  5597. })();
  5598. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5599. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5600. ? null : htInventoryFill;
  5601. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5602. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5603. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5604. : undefined;
  5605. const htSlotSpoolForFill = htSlotAssignmentForFill
  5606. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5607. : undefined;
  5608. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5609. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5610. : null;
  5611. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5612. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5613. : htResolvedInventoryFill !== null ? 'inventory' as const
  5614. : hasFillLevel ? 'ams' as const
  5615. : undefined;
  5616. // Build filament data for hover card
  5617. const filamentData = tray?.tray_type ? {
  5618. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5619. 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,
  5620. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5621. colorHex: tray.tray_color || null,
  5622. kFactor: formatKValue(tray.k),
  5623. fillLevel: htEffectiveFill,
  5624. trayUuid: tray.tray_uuid || null,
  5625. tagUid: tray.tag_uid || null,
  5626. fillSource: htFillSource,
  5627. } : null;
  5628. // Check if this specific slot is being refreshed
  5629. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5630. refreshingSlot?.slotId === htSlotId;
  5631. // #1762 (comment 2): active print-slot index for this HT slot.
  5632. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5633. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5634. ? `P${htActivePrintSlotIdx + 1}`
  5635. : null;
  5636. // Slot visual content (goes inside hover card)
  5637. const slotVisual = (
  5638. <div
  5639. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5640. isExpectedSlot
  5641. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5642. : isRanOutSlot
  5643. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5644. : isActive
  5645. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5646. : ''
  5647. }`}
  5648. >
  5649. {isExpectedSlot && (
  5650. <span
  5651. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5652. title={t('printers.expectedSlot.title')}
  5653. 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"
  5654. >
  5655. ↓
  5656. </span>
  5657. )}
  5658. {htActivePrintSlotLabel && (
  5659. <span
  5660. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5661. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5662. 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"
  5663. >
  5664. {htActivePrintSlotLabel}
  5665. </span>
  5666. )}
  5667. {/* Filament color circle with 1-based slot number centered inside */}
  5668. <FilamentSlotCircle
  5669. trayColor={tray?.tray_color}
  5670. trayType={tray?.tray_type}
  5671. isEmpty={isEmpty}
  5672. emptyKind={emptyKind}
  5673. slotNumber={1}
  5674. />
  5675. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5676. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5677. </div>
  5678. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5679. {/* Fill bar */}
  5680. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5681. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5682. <div
  5683. className="h-full rounded-full transition-all"
  5684. style={{
  5685. width: `${htEffectiveFill}%`,
  5686. backgroundColor: getFillBarColor(htEffectiveFill),
  5687. }}
  5688. />
  5689. )}
  5690. </div>
  5691. </div>
  5692. );
  5693. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5694. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5695. // Without this override, the L view squishes HT into a sliver next to the
  5696. // 4-slot AMS neighbors.
  5697. // 11rem holds one slot plus the temperature/humidity
  5698. // column beside it; both grow with the body scale.
  5699. const htCardWidth = scaledRem(11);
  5700. const htCardStyle: React.CSSProperties = {
  5701. flex: `1 1 ${htCardWidth}`,
  5702. minWidth: htCardWidth,
  5703. // An AMS-HT is never wider than a full AMS. Without a
  5704. // ceiling, a unit that wraps onto a line of its own is
  5705. // the only flex item there and grow stretches its single
  5706. // slot across the entire card, leaving the readings
  5707. // stranded at the far edge.
  5708. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5709. };
  5710. return (
  5711. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5712. {/* Row 1: Label + Nozzle + Drying */}
  5713. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5714. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5715. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5716. <AmsNameHoverCard
  5717. ams={ams}
  5718. printerId={printer.id}
  5719. label={getAmsLabel(ams.id)}
  5720. amsLabels={amsLabels}
  5721. canEdit={hasPermission('printers:update')}
  5722. onSaved={refetchAmsLabels}
  5723. >
  5724. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5725. {amsLabels?.[ams.id] || getAmsLabel(ams.id)}
  5726. </span>
  5727. </AmsNameHoverCard>
  5728. {sideBadge?.kind === 'inlet' ? (
  5729. <InletBadge
  5730. inlet={sideBadge.inlet}
  5731. title={t('printers.amsSwitchInletTooltip', {
  5732. inlet: sideBadge.inlet,
  5733. side: FTS_INLET_SIDE[sideBadge.inlet],
  5734. })}
  5735. />
  5736. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5737. <NozzleBadge side={sideBadge.side} />
  5738. ) : null}
  5739. </div>
  5740. {/* Drying button for HT AMS */}
  5741. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5742. <div className="relative ml-auto">
  5743. <button
  5744. disabled={status.drying_screen_only}
  5745. onClick={(e) => {
  5746. if (ams.dry_time > 0) {
  5747. stopDryingMutation.mutate(ams.id);
  5748. } else if (dryingPopoverAmsId === ams.id) {
  5749. setDryingPopoverAmsId(null);
  5750. } else {
  5751. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5752. }
  5753. }}
  5754. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5755. ams.dry_time > 0
  5756. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5757. : status.drying_screen_only
  5758. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5759. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5760. }`}
  5761. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5762. >
  5763. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5764. </button>
  5765. </div>
  5766. )}
  5767. </div>
  5768. {/* HT AMS drying status bar. Same not-running split as the
  5769. standard-AMS bar above: a frozen countdown is not a
  5770. running cycle. */}
  5771. {ams.dry_time > 0 && (
  5772. <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}>
  5773. {ams.dry_countdown_stalled
  5774. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5775. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5776. {ams.dry_countdown_stalled && (
  5777. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5778. )}
  5779. {ams.dry_filament && (
  5780. <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`}>
  5781. {ams.dry_target_temp != null
  5782. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5783. : ams.dry_filament}
  5784. </span>
  5785. )}
  5786. {!ams.dry_countdown_stalled && (
  5787. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5788. {ams.dry_time >= 60
  5789. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5790. : `${ams.dry_time}m`}
  5791. </span>
  5792. )}
  5793. {!status.drying_screen_only && (
  5794. <button
  5795. onClick={() => stopDryingMutation.mutate(ams.id)}
  5796. disabled={stopDryingMutation.isPending}
  5797. 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"
  5798. title={t('printers.drying.stop')}
  5799. >
  5800. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5801. </button>
  5802. )}
  5803. </div>
  5804. )}
  5805. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5806. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5807. {/* Slot wrapper with loading overlay */}
  5808. <div className="relative group flex-1" style={htSlotStyle}>
  5809. {/* Loading overlay during RFID re-read */}
  5810. {isHtRefreshing && (
  5811. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5812. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5813. </div>
  5814. )}
  5815. {/* Hover card wraps only the visual content */}
  5816. {filamentData ? (
  5817. <FilamentHoverCard
  5818. data={filamentData}
  5819. actions={renderAmsSlotActions({
  5820. amsId: ams.id,
  5821. slotId: htSlotId,
  5822. // An AMS-HT holds one tray, numbered by its unit id (as tray_now).
  5823. loadTrayId: ams.id,
  5824. isRefreshing: isHtRefreshing,
  5825. })}
  5826. spoolman={{
  5827. enabled: spoolmanEnabled,
  5828. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5829. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5830. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5831. spoolmanUrl,
  5832. syncMode: spoolmanSyncMode,
  5833. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5834. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5835. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5836. setLinkSpoolModal({
  5837. tagUid: filamentData.tagUid || linkTag,
  5838. trayUuid: filamentData.trayUuid || '',
  5839. printerId: printer.id,
  5840. amsId: ams.id,
  5841. trayId: htSlotId,
  5842. });
  5843. } : undefined,
  5844. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5845. }}
  5846. inventory={(() => {
  5847. if (spoolmanEnabled) {
  5848. if (spoolmanLoading) return undefined;
  5849. const slotAssignment = htSlotAssignmentForFill;
  5850. const spoolmanSpool = htSlotSpoolForFill;
  5851. return {
  5852. assignedSpool: spoolmanSpool ? {
  5853. id: spoolmanSpool.id,
  5854. material: spoolmanSpool.material,
  5855. subtype: spoolmanSpool.subtype,
  5856. brand: spoolmanSpool.brand ?? null,
  5857. color_name: spoolmanSpool.color_name ?? null,
  5858. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5859. // The spool's own swatch (#2967). Spoolman carries the
  5860. // extra stops but has no effect field at all, so those
  5861. // rolls gradient and never shimmer.
  5862. rgba: spoolmanSpool.rgba ?? null,
  5863. extra_colors: spoolmanSpool.extra_colors ?? null,
  5864. effect_type: spoolmanSpool.effect_type ?? null,
  5865. remainingWeightGrams: spoolmanSpool.label_weight
  5866. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5867. : undefined,
  5868. } : null,
  5869. onAssignSpool: () => setAssignSpoolModal({
  5870. printerId: printer.id,
  5871. amsId: ams.id,
  5872. trayId: htSlotId,
  5873. trayInfo: {
  5874. type: tray?.tray_type || filamentData.profile,
  5875. material: tray?.tray_type ?? undefined,
  5876. profile: filamentData.profile,
  5877. color: filamentData.colorHex || '',
  5878. location: getAmsLabel(ams.id),
  5879. },
  5880. }),
  5881. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5882. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5883. };
  5884. }
  5885. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5886. return {
  5887. assignedSpool: assignment?.spool ? {
  5888. id: assignment.spool.id,
  5889. material: assignment.spool.material,
  5890. subtype: assignment.spool.subtype,
  5891. brand: assignment.spool.brand,
  5892. color_name: assignment.spool.color_name,
  5893. // The spool's own swatch (#2967).
  5894. rgba: assignment.spool.rgba ?? null,
  5895. extra_colors: assignment.spool.extra_colors ?? null,
  5896. effect_type: assignment.spool.effect_type ?? null,
  5897. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5898. } : null,
  5899. onAssignSpool: () => setAssignSpoolModal({
  5900. printerId: printer.id,
  5901. amsId: ams.id,
  5902. trayId: htSlotId,
  5903. trayInfo: {
  5904. type: tray?.tray_type || filamentData.profile,
  5905. material: tray?.tray_type ?? undefined,
  5906. profile: filamentData.profile,
  5907. color: filamentData.colorHex || '',
  5908. location: getAmsLabel(ams.id),
  5909. },
  5910. }),
  5911. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5912. isAssigned: !!assignment || isBambuLabSpool(tray),
  5913. };
  5914. })()}
  5915. configureSlot={{
  5916. enabled: hasPermission('printers:control'),
  5917. onConfigure: () => setConfigureSlotModal({
  5918. amsId: ams.id,
  5919. trayId: htSlotId,
  5920. trayType: tray?.tray_type || undefined,
  5921. trayColor: tray?.tray_color || undefined,
  5922. traySubBrands: tray?.tray_sub_brands || undefined,
  5923. trayInfoIdx: tray?.tray_info_idx || undefined,
  5924. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5925. caliIdx: tray?.cali_idx,
  5926. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5927. }),
  5928. }}
  5929. >
  5930. {slotVisual}
  5931. </FilamentHoverCard>
  5932. ) : (
  5933. <EmptySlotHoverCard
  5934. kind={emptyKind ?? undefined}
  5935. actions={renderAmsSlotActions({
  5936. amsId: ams.id,
  5937. slotId: htSlotId,
  5938. // An AMS-HT holds one tray, numbered by its unit id (as tray_now).
  5939. loadTrayId: ams.id,
  5940. isRefreshing: isHtRefreshing,
  5941. })}
  5942. configureSlot={{
  5943. enabled: hasPermission('printers:control'),
  5944. onConfigure: () => setConfigureSlotModal({
  5945. amsId: ams.id,
  5946. trayId: htSlotId,
  5947. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5948. }),
  5949. }}
  5950. onAssignSpool={() => setAssignSpoolModal({
  5951. printerId: printer.id,
  5952. amsId: ams.id,
  5953. trayId: htSlotId,
  5954. trayInfo: {
  5955. type: '',
  5956. material: undefined,
  5957. profile: '',
  5958. color: '',
  5959. location: getAmsLabel(ams.id),
  5960. },
  5961. })}
  5962. >
  5963. {slotVisual}
  5964. </EmptySlotHoverCard>
  5965. )}
  5966. </div>
  5967. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5968. {(ams.humidity != null || ams.temp != null) && (
  5969. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5970. {ams.temp != null && (
  5971. <TemperatureIndicator
  5972. temp={ams.temp}
  5973. goodThreshold={amsThresholds?.tempGood}
  5974. fairThreshold={amsThresholds?.tempFair}
  5975. onClick={() => setAmsHistoryModal({
  5976. amsId: ams.id,
  5977. amsLabel: getAmsLabel(ams.id),
  5978. mode: 'temperature',
  5979. })}
  5980. compact
  5981. />
  5982. )}
  5983. {ams.humidity != null && (
  5984. <HumidityIndicator
  5985. humidity={ams.humidity}
  5986. goodThreshold={amsThresholds?.humidityGood}
  5987. fairThreshold={amsThresholds?.humidityFair}
  5988. onClick={() => setAmsHistoryModal({
  5989. amsId: ams.id,
  5990. amsLabel: getAmsLabel(ams.id),
  5991. mode: 'humidity',
  5992. })}
  5993. compact
  5994. />
  5995. )}
  5996. </div>
  5997. )}
  5998. </div>
  5999. </div>
  6000. );
  6001. })}
  6002. {/* External spool(s) - grouped in one card like regular AMS */}
  6003. {status.vt_tray.length > 0 && showExternalSpool && (
  6004. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  6005. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  6006. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  6007. </div>
  6008. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  6009. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  6010. const extTrayId = extTray.id ?? 254;
  6011. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  6012. // generically — use active_extruder to determine L vs R:
  6013. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  6014. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  6015. ? (extTrayId === 254 && status.active_extruder === 1) ||
  6016. (extTrayId === 255 && status.active_extruder === 0)
  6017. : effectiveTrayNow === extTrayId;
  6018. const slotTrayId = extTrayId - 254; // 0 or 1
  6019. const extLabel = isDualNozzle
  6020. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6021. : '';
  6022. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6023. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6024. // Only trusted while it still describes what the printer reports in the
  6025. // slot: the row survives a spool swap, and the display chain below puts
  6026. // it ahead of the live filament id (see slotPresetDescribesTray).
  6027. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx)
  6028. ? extSlotPreset?.preset_name
  6029. : undefined;
  6030. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6031. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6032. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6033. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6034. const extInventoryFill = (() => {
  6035. const sp = extInventoryAssignment?.spool;
  6036. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6037. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6038. }
  6039. return null;
  6040. })();
  6041. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6042. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6043. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6044. ? null : extInventoryFill;
  6045. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6046. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6047. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6048. : undefined;
  6049. const extSlotSpoolForFill = extSlotAssignmentForFill
  6050. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6051. : undefined;
  6052. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6053. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6054. : null;
  6055. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6056. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6057. : extResolvedInventoryFill !== null ? 'inventory' as const
  6058. : extHasFillLevel ? 'ams' as const
  6059. : undefined;
  6060. const extFilamentData = {
  6061. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6062. 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',
  6063. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6064. colorHex: extTray.tray_color || null,
  6065. kFactor: formatKValue(extTray.k),
  6066. fillLevel: extEffectiveFill,
  6067. trayUuid: extTray.tray_uuid || null,
  6068. tagUid: extTray.tag_uid || null,
  6069. fillSource: extFillSource,
  6070. };
  6071. const isEmpty = !extTray.tray_type;
  6072. const emptyKind = getEmptySlotKind(extTray);
  6073. const extSlotContent = (
  6074. <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' : ''}`}>
  6075. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6076. the separate Ext-L/Ext-R caption that made the row taller than
  6077. regular AMS slots), 1-based slot number on single-nozzle. */}
  6078. <FilamentSlotCircle
  6079. trayColor={extTray.tray_color}
  6080. trayType={extTray.tray_type}
  6081. isEmpty={isEmpty}
  6082. emptyKind={emptyKind}
  6083. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6084. />
  6085. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6086. {extTray.tray_type || t('ams.slotEmpty')}
  6087. </div>
  6088. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6089. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6090. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6091. <div
  6092. className="h-full rounded-full transition-all"
  6093. style={{
  6094. width: `${extEffectiveFill}%`,
  6095. backgroundColor: getFillBarColor(extEffectiveFill),
  6096. }}
  6097. />
  6098. )}
  6099. </div>
  6100. </div>
  6101. );
  6102. return (
  6103. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6104. {!isEmpty ? (
  6105. <FilamentHoverCard
  6106. data={extFilamentData}
  6107. actions={renderAmsSlotActions({
  6108. amsId: 255,
  6109. slotId: slotTrayId,
  6110. loadTrayId: extTrayId,
  6111. includeRfid: false,
  6112. })}
  6113. spoolman={{
  6114. enabled: spoolmanEnabled,
  6115. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6116. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6117. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6118. spoolmanUrl,
  6119. syncMode: spoolmanSyncMode,
  6120. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6121. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6122. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6123. setLinkSpoolModal({
  6124. tagUid: extFilamentData.tagUid || linkTag,
  6125. trayUuid: extFilamentData.trayUuid || '',
  6126. printerId: printer.id,
  6127. amsId: 255,
  6128. trayId: slotTrayId,
  6129. });
  6130. } : undefined,
  6131. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6132. }}
  6133. inventory={(() => {
  6134. if (spoolmanEnabled) {
  6135. if (spoolmanLoading) return undefined;
  6136. const slotAssignment = extSlotAssignmentForFill;
  6137. const spoolmanSpool = extSlotSpoolForFill;
  6138. return {
  6139. assignedSpool: spoolmanSpool ? {
  6140. id: spoolmanSpool.id,
  6141. material: spoolmanSpool.material,
  6142. subtype: spoolmanSpool.subtype,
  6143. brand: spoolmanSpool.brand ?? null,
  6144. color_name: spoolmanSpool.color_name ?? null,
  6145. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6146. // The spool's own swatch (#2967). Spoolman carries the
  6147. // extra stops but has no effect field at all, so those
  6148. // rolls gradient and never shimmer.
  6149. rgba: spoolmanSpool.rgba ?? null,
  6150. extra_colors: spoolmanSpool.extra_colors ?? null,
  6151. effect_type: spoolmanSpool.effect_type ?? null,
  6152. remainingWeightGrams: spoolmanSpool.label_weight
  6153. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6154. : undefined,
  6155. } : null,
  6156. onAssignSpool: () => setAssignSpoolModal({
  6157. printerId: printer.id,
  6158. amsId: 255,
  6159. trayId: slotTrayId,
  6160. trayInfo: {
  6161. type: extTray.tray_type || extFilamentData.profile,
  6162. material: extTray.tray_type ?? undefined,
  6163. profile: extFilamentData.profile,
  6164. color: extFilamentData.colorHex || '',
  6165. location: extLabel || t('printers.external'),
  6166. },
  6167. }),
  6168. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6169. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6170. };
  6171. }
  6172. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6173. return {
  6174. assignedSpool: assignment?.spool ? {
  6175. id: assignment.spool.id,
  6176. material: assignment.spool.material,
  6177. subtype: assignment.spool.subtype,
  6178. brand: assignment.spool.brand,
  6179. color_name: assignment.spool.color_name,
  6180. // The spool's own swatch (#2967).
  6181. rgba: assignment.spool.rgba ?? null,
  6182. extra_colors: assignment.spool.extra_colors ?? null,
  6183. effect_type: assignment.spool.effect_type ?? null,
  6184. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6185. } : null,
  6186. onAssignSpool: () => setAssignSpoolModal({
  6187. printerId: printer.id,
  6188. amsId: 255,
  6189. trayId: slotTrayId,
  6190. trayInfo: {
  6191. type: extTray.tray_type || extFilamentData.profile,
  6192. material: extTray.tray_type ?? undefined,
  6193. profile: extFilamentData.profile,
  6194. color: extFilamentData.colorHex || '',
  6195. location: extLabel || t('printers.external'),
  6196. },
  6197. }),
  6198. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6199. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6200. };
  6201. })()}
  6202. configureSlot={{
  6203. enabled: hasPermission('printers:control'),
  6204. onConfigure: () => setConfigureSlotModal({
  6205. amsId: 255,
  6206. trayId: slotTrayId,
  6207. trayType: extTray.tray_type || undefined,
  6208. trayColor: extTray.tray_color || undefined,
  6209. traySubBrands: extTray.tray_sub_brands || undefined,
  6210. trayInfoIdx: extTray.tray_info_idx || undefined,
  6211. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6212. caliIdx: extTray.cali_idx,
  6213. savedPresetId: slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx) ? extSlotPreset?.preset_id : undefined,
  6214. }),
  6215. }}
  6216. >
  6217. {extSlotContent}
  6218. </FilamentHoverCard>
  6219. ) : (
  6220. <EmptySlotHoverCard
  6221. kind={emptyKind ?? undefined}
  6222. actions={renderAmsSlotActions({
  6223. amsId: 255,
  6224. slotId: slotTrayId,
  6225. loadTrayId: extTrayId,
  6226. includeRfid: false,
  6227. })}
  6228. configureSlot={{
  6229. enabled: hasPermission('printers:control'),
  6230. onConfigure: () => setConfigureSlotModal({
  6231. amsId: 255,
  6232. trayId: slotTrayId,
  6233. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6234. }),
  6235. }}
  6236. onAssignSpool={() => setAssignSpoolModal({
  6237. printerId: printer.id,
  6238. amsId: 255,
  6239. trayId: slotTrayId,
  6240. trayInfo: {
  6241. type: '',
  6242. material: undefined,
  6243. profile: '',
  6244. color: '',
  6245. location: `External Slot ${slotTrayId + 1}`,
  6246. },
  6247. })}
  6248. >
  6249. {extSlotContent}
  6250. </EmptySlotHoverCard>
  6251. )}
  6252. </div>
  6253. );
  6254. })}
  6255. </div>
  6256. </div>
  6257. )}
  6258. </div>
  6259. </div>
  6260. );
  6261. })()}
  6262. </>
  6263. )}
  6264. {/* Powered-down printer with a dirty plate: the status block above renders
  6265. nothing without a live connection, so the plate-clear control gets its own
  6266. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6267. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6268. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6269. expandedClearPlateButton
  6270. )}
  6271. {/* Bottom block (power row + action bar). Wrapped together so the
  6272. power row hugs the action bar at the card bottom instead of
  6273. floating up when there's less filament content above. */}
  6274. {viewMode === 'expanded' && (
  6275. <div className="mt-auto">
  6276. {smartPlug && (
  6277. <div className="pt-3">
  6278. <div className="flex items-center gap-2 mb-2">
  6279. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6280. {t('printers.power', 'Power')}
  6281. </span>
  6282. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6283. </div>
  6284. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6285. {/* Plug name + current power */}
  6286. <div className="flex items-center gap-2 min-w-0 pl-1">
  6287. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6288. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6289. <span
  6290. 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"
  6291. title={t('smartPlugs.power')}
  6292. >
  6293. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6294. </span>
  6295. </div>
  6296. {/* Spacer */}
  6297. <div className="flex-1" />
  6298. <div className="flex items-center gap-2">
  6299. {/* Auto-off */}
  6300. <button
  6301. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6302. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6303. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6304. 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 ${
  6305. !hasPermission('smart_plugs:control')
  6306. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6307. : smartPlug.auto_off || smartPlug.auto_off_executed
  6308. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6309. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6310. }`}
  6311. >
  6312. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6313. </button>
  6314. <button
  6315. onClick={() => {
  6316. if (plugStatus?.state === 'ON') {
  6317. setShowPowerOffConfirm(true);
  6318. } else {
  6319. setShowPowerOnConfirm(true);
  6320. }
  6321. }}
  6322. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6323. 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 ${
  6324. !hasPermission('smart_plugs:control')
  6325. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6326. : plugStatus?.state === 'ON'
  6327. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6328. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6329. }`}
  6330. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6331. >
  6332. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6333. </button>
  6334. </div>
  6335. </div>
  6336. {/* HA entity buttons row */}
  6337. {scriptPlugs && scriptPlugs.length > 0 && (
  6338. <div className="flex items-center gap-2 mt-2">
  6339. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6340. <span className="text-xs text-bambu-gray">HA:</span>
  6341. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6342. <div className="flex flex-wrap gap-1">
  6343. {scriptPlugs.map(script => {
  6344. const isScript = script.ha_entity_id?.startsWith('script.');
  6345. return (
  6346. <button
  6347. key={script.id}
  6348. onClick={() => {
  6349. if (isScript) {
  6350. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6351. } else {
  6352. setHaToggleConfirm(script);
  6353. }
  6354. }}
  6355. disabled={runScriptMutation.isPending}
  6356. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6357. 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"
  6358. >
  6359. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6360. {script.name}
  6361. </button>
  6362. );
  6363. })}
  6364. </div>
  6365. </div>
  6366. )}
  6367. </div>
  6368. )}
  6369. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6370. a printer can have an enclosure door contact without having a plug,
  6371. and nesting it there would hide the row on exactly those setups. */}
  6372. <PrinterHASensorRow printerId={printer.id} />
  6373. {/* Connection Info & Actions */}
  6374. <div className="pt-4">
  6375. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6376. <div className="flex items-center justify-between gap-2">
  6377. {printerActionsMenu}
  6378. <div className="flex items-center justify-end gap-2 flex-wrap">
  6379. {/* Camera split button: the icon opens whichever view was used
  6380. last, the caret picks between the two and remembers it.
  6381. Replaces the old Settings > General > Camera switch, which
  6382. made choosing between an overlay and a window a trip to
  6383. another page for something you decide per camera. */}
  6384. <div className="flex items-center flex-shrink-0">
  6385. <Button
  6386. variant="secondary"
  6387. size="sm"
  6388. onClick={() => openCameraIn(cameraViewMode)}
  6389. disabled={!status?.connected || !hasPermission('camera:view')}
  6390. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6391. className={`${footerIconButtonClass} !rounded-r-none`}
  6392. >
  6393. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6394. </Button>
  6395. <Button
  6396. variant="secondary"
  6397. size="sm"
  6398. onClick={(e) => {
  6399. // No open/close toggle: the menu's own outside-mousedown
  6400. // handler has already dismissed it by the time this lands.
  6401. const rect = e.currentTarget.getBoundingClientRect();
  6402. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6403. }}
  6404. disabled={!status?.connected || !hasPermission('camera:view')}
  6405. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6406. aria-label={t('settings.cameraViewMode')}
  6407. // Not footerIconButtonClass plus an override: both widths
  6408. // would carry !important and the stylesheet's own order,
  6409. // not this one, would decide which won.
  6410. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6411. >
  6412. <ChevronDown className="w-3 h-3" />
  6413. </Button>
  6414. </div>
  6415. {cameraMenuAnchor && (
  6416. <ContextMenu
  6417. x={cameraMenuAnchor.x}
  6418. y={cameraMenuAnchor.y}
  6419. items={cameraViewModeMenuItems}
  6420. onClose={() => setCameraMenuAnchor(null)}
  6421. />
  6422. )}
  6423. <Button
  6424. variant="secondary"
  6425. size="sm"
  6426. onClick={() => setShowFileManager(true)}
  6427. disabled={!hasPermission('printers:files')}
  6428. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6429. className={footerIconButtonClass}
  6430. >
  6431. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6432. </Button>
  6433. {/* Shown whatever the printer is doing (#2849): this uploads a
  6434. file and queues it, which a busy or offline printer is no
  6435. reason to refuse -- it only means the item waits. Hiding it
  6436. while the drop zone accepted the same file would have left
  6437. the two routes into this flow disagreeing. */}
  6438. <Button
  6439. size="sm"
  6440. onClick={() => setShowUploadForPrint(true)}
  6441. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6442. title={
  6443. !hasPermission('library:upload')
  6444. ? t('fileManager.noPermissionUpload')
  6445. : !hasPermission('queue:create')
  6446. ? t('fileManager.noPermissionAddToQueue')
  6447. : t('common.print')
  6448. }
  6449. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6450. >
  6451. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6452. {t('common.print')}
  6453. </Button>
  6454. </div>
  6455. </div>
  6456. </div>
  6457. </div>
  6458. )}
  6459. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6460. card's horizontal padding instead of running full-bleed into the
  6461. rounded bottom edge. */}
  6462. <ScheduledDryingBanner
  6463. printerId={printer.id}
  6464. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6465. timeFormat={timeFormat}
  6466. />
  6467. </CardContent>
  6468. {/* File Manager Modal */}
  6469. {showFileManager && (
  6470. <FileManagerModal
  6471. printerId={printer.id}
  6472. printerName={printer.name}
  6473. onClose={() => setShowFileManager(false)}
  6474. />
  6475. )}
  6476. {/* Upload for Print Modal */}
  6477. {showUploadForPrint && (
  6478. <FileUploadModal
  6479. folderId={null}
  6480. onClose={() => setShowUploadForPrint(false)}
  6481. onUploadComplete={() => {}}
  6482. autoUpload
  6483. accept=".gcode,.3mf"
  6484. validateFile={(file) => {
  6485. if (!mayBeSlicedFileName(file.name)) {
  6486. return t('printers.dropNotPrintable');
  6487. }
  6488. }}
  6489. onFileUploaded={(uploadedFile) => {
  6490. if (!isSlicedLibraryFile(uploadedFile)) {
  6491. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6492. return t('printers.dropNotSliced');
  6493. }
  6494. // Check printer compatibility if sliced_for_model is available in metadata
  6495. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6496. const printerModel = mapModelCode(printer.model);
  6497. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6498. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6499. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6500. }
  6501. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6502. }}
  6503. />
  6504. )}
  6505. {/* Print Modal (after upload) */}
  6506. {printAfterUpload && (
  6507. <PrintModal
  6508. mode="create"
  6509. libraryFileId={printAfterUpload.id}
  6510. archiveName={printAfterUpload.filename}
  6511. initialSelectedPrinterIds={[printer.id]}
  6512. onClose={() => setPrintAfterUpload(null)}
  6513. onSuccess={() => setPrintAfterUpload(null)}
  6514. cleanupLibraryAfterDispatch
  6515. />
  6516. )}
  6517. {/* MQTT Debug Modal */}
  6518. {showMQTTDebug && (
  6519. <MQTTDebugModal
  6520. printerId={printer.id}
  6521. printerName={printer.name}
  6522. onClose={() => setShowMQTTDebug(false)}
  6523. />
  6524. )}
  6525. {showDiagnostic && (
  6526. <ConnectionDiagnosticModal
  6527. printerId={printer.id}
  6528. printerName={printer.name}
  6529. onClose={() => setShowDiagnostic(false)}
  6530. />
  6531. )}
  6532. {showPrinterInfo && (
  6533. <PrinterInfoModal
  6534. printer={printer}
  6535. status={status}
  6536. totalPrintHours={maintenanceInfo?.total_print_hours}
  6537. onClose={closePrinterInfo}
  6538. />
  6539. )}
  6540. {/* Plate Check Result Modal */}
  6541. {plateCheckResult && (
  6542. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6543. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6544. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6545. <div className="flex items-center gap-2">
  6546. {plateCheckResult.needs_calibration ? (
  6547. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6548. ) : plateCheckResult.failure_reason ? (
  6549. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  6550. ) : plateCheckResult.is_empty ? (
  6551. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6552. ) : (
  6553. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6554. )}
  6555. <h2 className="text-lg font-semibold text-white">
  6556. Build Plate Check
  6557. </h2>
  6558. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6559. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6560. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6561. </span>
  6562. )}
  6563. </div>
  6564. <button
  6565. onClick={() => closePlateCheckModal()}
  6566. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6567. >
  6568. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6569. </button>
  6570. </div>
  6571. <div className="p-4 space-y-4">
  6572. {plateCheckResult.needs_calibration ? (
  6573. <>
  6574. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6575. <p className="font-medium text-blue-700 dark:text-blue-400">
  6576. {t('printers.plateDetection.calibrationRequired')}
  6577. </p>
  6578. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6579. </div>
  6580. <div className="text-sm text-bambu-gray space-y-2">
  6581. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6582. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6583. </div>
  6584. </>
  6585. ) : plateCheckResult.failure_reason ? (
  6586. <div className="p-3 rounded-lg bg-bambu-dark-tertiary border border-bambu-dark-tertiary">
  6587. <p className="font-medium text-white">{t('printers.plateDetection.couldNotRunTitle')}</p>
  6588. <p className="text-sm text-bambu-gray mt-1">{plateCheckFailureText(t, plateCheckResult.failure_reason)}</p>
  6589. </div>
  6590. ) : (
  6591. <>
  6592. <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'}`}>
  6593. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6594. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6595. </p>
  6596. <p className="text-sm text-bambu-gray mt-1">
  6597. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6598. </p>
  6599. </div>
  6600. {plateCheckResult.debug_image_url && (
  6601. <div>
  6602. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6603. <img
  6604. src={plateCheckResult.debug_image_url}
  6605. alt={t('printers.plateDetection.analysisPreview')}
  6606. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6607. />
  6608. <p className="text-xs text-bambu-gray mt-2">
  6609. {t('printers.plateDetection.analysisLegend')}
  6610. </p>
  6611. </div>
  6612. )}
  6613. <p className="text-xs text-bambu-gray">
  6614. {plateCheckResult.message}
  6615. </p>
  6616. </>
  6617. )}
  6618. {/* Saved References Grid */}
  6619. {plateReferences && plateReferences.references.length > 0 && (
  6620. <div className="mt-4">
  6621. <div className="flex items-center gap-2 mb-2">
  6622. <p className="text-sm font-medium text-white shrink-0">
  6623. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6624. </p>
  6625. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6626. </div>
  6627. <div className="grid grid-cols-5 gap-2">
  6628. {plateReferences.references.map((ref) => (
  6629. <div key={ref.index} className="relative group">
  6630. <img
  6631. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6632. alt={ref.label || `Reference ${ref.index + 1}`}
  6633. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6634. />
  6635. {/* Delete button */}
  6636. <button
  6637. onClick={() => handleDeleteRef(ref.index)}
  6638. 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"
  6639. title={t('printers.plateDetection.deleteReference')}
  6640. >
  6641. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6642. </button>
  6643. {/* Label */}
  6644. {editingRefLabel?.index === ref.index ? (
  6645. <input
  6646. type="text"
  6647. value={editingRefLabel.label}
  6648. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6649. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6650. onKeyDown={(e) => {
  6651. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6652. if (e.key === 'Escape') setEditingRefLabel(null);
  6653. }}
  6654. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6655. autoFocus
  6656. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6657. />
  6658. ) : (
  6659. <p
  6660. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6661. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6662. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6663. >
  6664. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6665. </p>
  6666. )}
  6667. {/* Timestamp */}
  6668. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6669. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6670. </p>
  6671. </div>
  6672. ))}
  6673. </div>
  6674. </div>
  6675. )}
  6676. {/* ROI Editor */}
  6677. {!plateCheckResult.needs_calibration && (
  6678. <div className="mt-4">
  6679. <div className="flex items-center justify-between mb-2">
  6680. <div className="flex min-w-0 flex-1 items-center gap-2">
  6681. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6682. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6683. </div>
  6684. {!editingRoi ? (
  6685. <Button
  6686. variant="ghost"
  6687. size="sm"
  6688. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6689. >
  6690. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6691. {t('common.edit')}
  6692. </Button>
  6693. ) : (
  6694. <div className="flex gap-1">
  6695. <Button
  6696. variant="ghost"
  6697. size="sm"
  6698. onClick={() => setEditingRoi(null)}
  6699. disabled={isSavingRoi}
  6700. >
  6701. {t('common.cancel')}
  6702. </Button>
  6703. <Button
  6704. size="sm"
  6705. onClick={handleSaveRoi}
  6706. disabled={isSavingRoi}
  6707. >
  6708. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6709. </Button>
  6710. </div>
  6711. )}
  6712. </div>
  6713. {editingRoi ? (
  6714. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6715. <div className="grid grid-cols-2 gap-3">
  6716. <div>
  6717. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6718. <input
  6719. type="range"
  6720. min="0"
  6721. max="0.9"
  6722. step="0.01"
  6723. value={editingRoi.x}
  6724. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6725. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6726. />
  6727. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6728. </div>
  6729. <div>
  6730. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6731. <input
  6732. type="range"
  6733. min="0"
  6734. max="0.9"
  6735. step="0.01"
  6736. value={editingRoi.y}
  6737. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6738. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6739. />
  6740. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6741. </div>
  6742. <div>
  6743. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6744. <input
  6745. type="range"
  6746. min="0.1"
  6747. max="1"
  6748. step="0.01"
  6749. value={editingRoi.w}
  6750. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6751. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6752. />
  6753. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6754. </div>
  6755. <div>
  6756. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6757. <input
  6758. type="range"
  6759. min="0.1"
  6760. max="1"
  6761. step="0.01"
  6762. value={editingRoi.h}
  6763. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6764. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6765. />
  6766. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6767. </div>
  6768. </div>
  6769. <p className="text-xs text-bambu-gray">
  6770. {t('printers.roi.instruction')}
  6771. </p>
  6772. </div>
  6773. ) : (
  6774. <p className="text-xs text-bambu-gray">
  6775. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6776. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6777. </p>
  6778. )}
  6779. </div>
  6780. )}
  6781. </div>
  6782. <div className="flex justify-end gap-2 p-4">
  6783. {plateCheckResult.needs_calibration ? (
  6784. <>
  6785. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6786. {t('common.cancel')}
  6787. </Button>
  6788. <Button
  6789. onClick={() => handleCalibratePlate()}
  6790. disabled={isCalibrating}
  6791. >
  6792. {isCalibrating ? (
  6793. <>
  6794. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6795. Calibrating...
  6796. </>
  6797. ) : (
  6798. 'Calibrate Empty Plate'
  6799. )}
  6800. </Button>
  6801. </>
  6802. ) : (
  6803. <>
  6804. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6805. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6806. </Button>
  6807. <Button onClick={() => closePlateCheckModal()}>
  6808. Close
  6809. </Button>
  6810. </>
  6811. )}
  6812. </div>
  6813. </div>
  6814. </div>
  6815. )}
  6816. {/* Power On Confirmation */}
  6817. {showPowerOnConfirm && smartPlug && (
  6818. <ConfirmModal
  6819. title={t('printers.confirm.powerOnTitle')}
  6820. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6821. confirmText={t('printers.confirm.powerOnButton')}
  6822. variant="default"
  6823. onConfirm={() => {
  6824. powerControlMutation.mutate('on');
  6825. setShowPowerOnConfirm(false);
  6826. }}
  6827. onCancel={() => setShowPowerOnConfirm(false)}
  6828. />
  6829. )}
  6830. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6831. disconnects MQTT, which stops progress tracking + completion
  6832. notifications for the in-flight job. Idle / FINISH / FAILED states
  6833. skip this dialog and toggle directly. */}
  6834. {confirmMaintenanceEnter && (
  6835. <ConfirmModal
  6836. title={t('printers.maintenance.confirmMidPrintTitle')}
  6837. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6838. confirmText={t('printers.maintenance.menuEnter')}
  6839. variant="danger"
  6840. onConfirm={() => {
  6841. maintenanceMutation.mutate(false);
  6842. setConfirmMaintenanceEnter(false);
  6843. }}
  6844. onCancel={() => setConfirmMaintenanceEnter(false)}
  6845. />
  6846. )}
  6847. {/* Power Off Confirmation */}
  6848. {showPowerOffConfirm && smartPlug && (
  6849. <ConfirmModal
  6850. title={t('printers.confirm.powerOffTitle')}
  6851. message={
  6852. status?.state === 'RUNNING'
  6853. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6854. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6855. }
  6856. confirmText={t('printers.confirm.powerOffButton')}
  6857. variant="danger"
  6858. onConfirm={() => {
  6859. powerControlMutation.mutate('off');
  6860. setShowPowerOffConfirm(false);
  6861. }}
  6862. onCancel={() => setShowPowerOffConfirm(false)}
  6863. />
  6864. )}
  6865. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6866. {haToggleConfirm && (
  6867. <ConfirmModal
  6868. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6869. message={
  6870. status?.state === 'RUNNING'
  6871. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6872. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6873. }
  6874. confirmText={t('printers.confirm.haToggleButton')}
  6875. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6876. onConfirm={() => {
  6877. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6878. setHaToggleConfirm(null);
  6879. }}
  6880. onCancel={() => setHaToggleConfirm(null)}
  6881. />
  6882. )}
  6883. {/* Stop Print Confirmation */}
  6884. {showStopConfirm && (
  6885. <ConfirmModal
  6886. title={t('printers.confirm.stopTitle')}
  6887. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6888. confirmText={t('printers.confirm.stopButton')}
  6889. variant="danger"
  6890. onConfirm={() => {
  6891. stopPrintMutation.mutate();
  6892. setShowStopConfirm(false);
  6893. }}
  6894. onCancel={() => setShowStopConfirm(false)}
  6895. />
  6896. )}
  6897. {/* Pause Print Confirmation */}
  6898. {showPauseConfirm && (
  6899. <ConfirmModal
  6900. title={t('printers.confirm.pauseTitle')}
  6901. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6902. confirmText={t('printers.confirm.pauseButton')}
  6903. variant="default"
  6904. onConfirm={() => {
  6905. pausePrintMutation.mutate();
  6906. setShowPauseConfirm(false);
  6907. }}
  6908. onCancel={() => setShowPauseConfirm(false)}
  6909. />
  6910. )}
  6911. {/* Resume Print Confirmation */}
  6912. {showResumeConfirm && (
  6913. <ConfirmModal
  6914. title={t('printers.confirm.resumeTitle')}
  6915. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6916. confirmText={t('printers.confirm.resumeButton')}
  6917. variant="default"
  6918. onConfirm={() => {
  6919. resumePrintMutation.mutate();
  6920. setShowResumeConfirm(false);
  6921. }}
  6922. onCancel={() => setShowResumeConfirm(false)}
  6923. />
  6924. )}
  6925. {/* Skip Objects Modal */}
  6926. <SkipObjectsModal
  6927. printerId={printer.id}
  6928. isOpen={showSkipObjectsModal}
  6929. onClose={() => setShowSkipObjectsModal(false)}
  6930. />
  6931. {/* HMS Error Modal */}
  6932. {showHMSModal && (
  6933. <HMSErrorModal
  6934. printerName={printer.name}
  6935. errors={status?.hms_errors || []}
  6936. onClose={() => setShowHMSModal(false)}
  6937. printerId={printer.id}
  6938. hasPermission={hasPermission}
  6939. runoutGuidance={runoutGuidance}
  6940. />
  6941. )}
  6942. {/* AI failure detection modal (#1546) */}
  6943. {showAiModal && (
  6944. <AiDetectionModal
  6945. printerName={printer.name}
  6946. detection={aiDetection}
  6947. lastError={aiLastError}
  6948. onClose={() => setShowAiModal(false)}
  6949. />
  6950. )}
  6951. {/* AMS Filament Backup status / control modal (#1762) */}
  6952. {amsBackupModalOpen && status && (
  6953. <AmsBackupModal
  6954. isOpen={amsBackupModalOpen}
  6955. state={status.ams_filament_backup}
  6956. amsUnits={status.ams}
  6957. amsExtruderMap={status.ams_extruder_map}
  6958. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6959. canToggle={hasPermission('printers:control')}
  6960. pending={setAmsBackupMutation.isPending}
  6961. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6962. onClose={() => setAmsBackupModalOpen(false)}
  6963. />
  6964. )}
  6965. {/* AMS History Modal */}
  6966. {amsHistoryModal && (
  6967. <AMSHistoryModal
  6968. isOpen={!!amsHistoryModal}
  6969. onClose={() => setAmsHistoryModal(null)}
  6970. printerId={printer.id}
  6971. printerName={printer.name}
  6972. amsId={amsHistoryModal.amsId}
  6973. amsLabel={amsHistoryModal.amsLabel}
  6974. initialMode={amsHistoryModal.mode}
  6975. thresholds={amsThresholds}
  6976. />
  6977. )}
  6978. {/* Heater History Modal (nozzle / bed / chamber) */}
  6979. {heaterHistoryModal && (
  6980. <HeaterHistoryModal
  6981. isOpen={!!heaterHistoryModal}
  6982. onClose={() => setHeaterHistoryModal(null)}
  6983. printerId={printer.id}
  6984. printerName={printer.name}
  6985. initialKind={heaterHistoryModal.initialKind}
  6986. availableKinds={heaterHistoryModal.availableKinds}
  6987. />
  6988. )}
  6989. {/* Link Spool Modal */}
  6990. {linkSpoolModal && (
  6991. <LinkSpoolModal
  6992. isOpen={!!linkSpoolModal}
  6993. onClose={() => setLinkSpoolModal(null)}
  6994. tagUid={linkSpoolModal.tagUid}
  6995. trayUuid={linkSpoolModal.trayUuid}
  6996. printerId={linkSpoolModal.printerId}
  6997. amsId={linkSpoolModal.amsId}
  6998. trayId={linkSpoolModal.trayId}
  6999. />
  7000. )}
  7001. {/* Assign Spool Modal */}
  7002. {assignSpoolModal && (
  7003. <AssignSpoolModal
  7004. isOpen={!!assignSpoolModal}
  7005. onClose={() => setAssignSpoolModal(null)}
  7006. printerId={assignSpoolModal.printerId}
  7007. amsId={assignSpoolModal.amsId}
  7008. trayId={assignSpoolModal.trayId}
  7009. trayInfo={assignSpoolModal.trayInfo}
  7010. spoolmanEnabled={!!spoolmanEnabled}
  7011. />
  7012. )}
  7013. {/* Configure AMS Slot Modal */}
  7014. {configureSlotModal && (
  7015. <ConfigureAmsSlotModal
  7016. isOpen={!!configureSlotModal}
  7017. onClose={() => setConfigureSlotModal(null)}
  7018. printerId={printer.id}
  7019. slotInfo={configureSlotModal}
  7020. printerModel={mapModelCode(printer.model) || undefined}
  7021. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  7022. onSuccess={() => {
  7023. // Refresh slot presets to show updated profile name
  7024. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7025. // Printer status will update automatically via WebSocket when AMS data changes
  7026. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7027. }}
  7028. />
  7029. )}
  7030. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7031. {feedDirectionRequest && (
  7032. <FeedDirectionModal
  7033. slotLabel={feedDirectionRequest.slotLabel}
  7034. amsId={feedDirectionRequest.amsId}
  7035. slotId={feedDirectionRequest.slotId}
  7036. extruderSlots={status?.extruder_slots ?? {}}
  7037. isLoading={loadAmsTrayMutation.isPending}
  7038. onConfirm={(extruderId) =>
  7039. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7040. }
  7041. onCancel={() => setFeedDirectionRequest(null)}
  7042. />
  7043. )}
  7044. {/* Edit Printer Modal */}
  7045. {showEditModal && (
  7046. <EditPrinterModal
  7047. printer={printer}
  7048. onClose={() => setShowEditModal(false)}
  7049. />
  7050. )}
  7051. {/* Firmware Update Modal */}
  7052. {showFirmwareModal && firmwareInfo && (
  7053. <FirmwareUpdateModal
  7054. printer={printer}
  7055. firmwareInfo={firmwareInfo}
  7056. onClose={() => setShowFirmwareModal(false)}
  7057. />
  7058. )}
  7059. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7060. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7061. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7062. const sliderMin = 35;
  7063. const sliderMax = maxTemp + 10;
  7064. return (
  7065. <>
  7066. {/* Backdrop */}
  7067. <div
  7068. className="fixed inset-0 z-[100]"
  7069. data-testid="drying-popover-backdrop"
  7070. onMouseDown={() => {
  7071. // The click that dismisses the native datetime picker lands
  7072. // here; it must not close the popover. The input is still
  7073. // focused at mousedown, so remember that and swallow the
  7074. // matching click.
  7075. dryingBackdropSkipCloseRef.current =
  7076. dryingAtTimeInputRef.current !== null &&
  7077. document.activeElement === dryingAtTimeInputRef.current;
  7078. }}
  7079. onClick={() => {
  7080. if (dryingBackdropSkipCloseRef.current) {
  7081. dryingBackdropSkipCloseRef.current = false;
  7082. return;
  7083. }
  7084. setDryingPopoverAmsId(null);
  7085. }}
  7086. />
  7087. {/* An 'above' popover is anchored by its bottom edge (CSS
  7088. bottom) so late-appearing content grows it upward, staying on
  7089. screen and glued to the trigger. maxHeight caps to the space
  7090. on the anchored side; when the viewport is too short the body
  7091. scrolls and the footer stays pinned. dvh so iOS Safari's
  7092. bottom toolbar doesn't clip the footer. */}
  7093. <div
  7094. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7095. style={{
  7096. left: dryingPopoverPos.left,
  7097. ...(dryingPopoverPos.placement === 'above'
  7098. ? {
  7099. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7100. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7101. }
  7102. : {
  7103. top: dryingPopoverPos.top,
  7104. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7105. }),
  7106. }}
  7107. onClick={e => e.stopPropagation()}
  7108. >
  7109. {/* Header */}
  7110. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7111. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7112. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7113. </div>
  7114. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7115. {/* Body */}
  7116. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7117. {/* Filament type select */}
  7118. <div>
  7119. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7120. <ToolbarDropdown
  7121. value={dryingFilament}
  7122. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7123. onChange={fil => {
  7124. setDryingFilament(fil);
  7125. const preset = dryingPresets[fil];
  7126. if (preset) {
  7127. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7128. setDryingTemp(preset[key]);
  7129. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7130. }
  7131. }}
  7132. fullWidth
  7133. />
  7134. </div>
  7135. {/* Temperature */}
  7136. <div>
  7137. <div className="flex items-center justify-between mb-1">
  7138. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7139. <div className="flex items-center gap-1">
  7140. <NumberInput
  7141. min={45}
  7142. max={maxTemp}
  7143. value={dryingTemp}
  7144. onChange={setDryingTemp}
  7145. fallback={45}
  7146. 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"
  7147. />
  7148. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7149. </div>
  7150. </div>
  7151. <input
  7152. type="range"
  7153. min={sliderMin}
  7154. max={sliderMax}
  7155. value={dryingTemp}
  7156. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7157. className="w-full h-1 accent-bambu-green cursor-pointer"
  7158. />
  7159. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7160. <span>45°C</span>
  7161. <span>{maxTemp}°C</span>
  7162. </div>
  7163. </div>
  7164. {/* Duration */}
  7165. <div>
  7166. <div className="flex items-center justify-between mb-1">
  7167. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7168. <div className="flex items-center gap-1">
  7169. <NumberInput
  7170. min={1}
  7171. max={24}
  7172. value={dryingDuration}
  7173. onChange={setDryingDuration}
  7174. fallback={1}
  7175. 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"
  7176. />
  7177. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7178. </div>
  7179. </div>
  7180. <input
  7181. type="range"
  7182. min={1}
  7183. max={24}
  7184. value={dryingDuration}
  7185. onChange={e => setDryingDuration(Number(e.target.value))}
  7186. className="w-full h-1 accent-bambu-green cursor-pointer"
  7187. />
  7188. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7189. <span>1h</span>
  7190. <span>24h</span>
  7191. </div>
  7192. </div>
  7193. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7194. filament threaded out into the feed tube. The whole AMS
  7195. rotates as one mechanism (all 4 spools turn together), so a
  7196. single loaded slot locks the entire unit. Bambu per-tray
  7197. `state`: 9 = empty, 10 = spool present but not loaded
  7198. (rotation possible), 11 = loaded into tube (rotation impossible).
  7199. Catches both mid-print (active feed) AND idle-with-threaded-
  7200. filament — the H2D's post-print state leaves filament in the
  7201. tube but tray_now resets to 255, which a tray_now-only check
  7202. would silently miss. The state code differs by firmware, so
  7203. the loaded slot (tray_now, extruder_slots) counts too. */}
  7204. {(() => {
  7205. const targetAms = dryingPopoverAmsId !== null
  7206. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7207. : undefined;
  7208. const trayLoadedInThisAms = amsHasLoadedTray(targetAms, status?.tray_now, status?.extruder_slots);
  7209. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7210. return (
  7211. <button
  7212. type="button"
  7213. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7214. aria-pressed={rotateChecked}
  7215. disabled={trayLoadedInThisAms}
  7216. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7217. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7218. rotateChecked
  7219. ? 'bg-bambu-green border-bambu-green text-white'
  7220. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7221. }`}
  7222. >
  7223. {t('printers.drying.rotateTray')}
  7224. </button>
  7225. );
  7226. })()}
  7227. {/* Start mode: now / after delay / at time (#2638) */}
  7228. <div>
  7229. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7230. <div className="grid grid-cols-3 gap-1">
  7231. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7232. <button
  7233. key={mode}
  7234. type="button"
  7235. onClick={() => setDryingStartMode(mode)}
  7236. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7237. dryingStartMode === mode
  7238. ? 'bg-bambu-green border-bambu-green text-white'
  7239. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7240. }`}
  7241. >
  7242. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7243. </button>
  7244. ))}
  7245. </div>
  7246. {dryingStartMode === 'delay' && (
  7247. // Inline chips: a dropdown menu would be clipped by
  7248. // the popover's scrollable body.
  7249. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7250. {DRYING_DELAY_OPTIONS.map(min => (
  7251. <button
  7252. key={min}
  7253. type="button"
  7254. aria-pressed={dryingDelayMinutes === min}
  7255. onClick={() => setDryingDelayMinutes(min)}
  7256. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7257. dryingDelayMinutes === min
  7258. ? 'bg-bambu-green border-bambu-green text-white'
  7259. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7260. }`}
  7261. >
  7262. {formatDurationFromHours(min / 60)}
  7263. </button>
  7264. ))}
  7265. </div>
  7266. )}
  7267. {dryingStartMode === 'at_time' && (
  7268. <input
  7269. ref={dryingAtTimeInputRef}
  7270. type="datetime-local"
  7271. data-testid="drying-start-at"
  7272. value={dryingStartAt}
  7273. onChange={e => setDryingStartAt(e.target.value)}
  7274. className="mt-1.5 w-full px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] focus:outline-none focus:border-bambu-green [color-scheme:dark]"
  7275. />
  7276. )}
  7277. </div>
  7278. </div>
  7279. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7280. {/* Footer */}
  7281. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7282. <button
  7283. onClick={() => {
  7284. if (dryingPopoverAmsId !== null) {
  7285. // Clamp rotateTray off when any tray in this AMS is loaded into
  7286. // the tube — the rotate UI is disabled there, but the state may
  7287. // linger as `true` from a previous AMS, or a print may have
  7288. // started while the popover was open. Without this clamp the
  7289. // Start payload would carry rotate_tray=true and firmware would
  7290. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7291. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7292. const trayLoadedInThisAms = amsHasLoadedTray(targetAms, status?.tray_now, status?.extruder_slots);
  7293. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7294. if (dryingStartMode === 'now') {
  7295. startDryingMutation.mutate({
  7296. amsId: dryingPopoverAmsId,
  7297. temp: dryingTemp,
  7298. duration: dryingDuration,
  7299. filament: dryingFilament,
  7300. rotateTray: rotate,
  7301. });
  7302. } else {
  7303. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7304. if (startAfter) {
  7305. scheduleDryingMutation.mutate({
  7306. amsId: dryingPopoverAmsId,
  7307. temp: dryingTemp,
  7308. duration: dryingDuration,
  7309. filament: dryingFilament,
  7310. rotateTray: rotate,
  7311. startAfter,
  7312. });
  7313. }
  7314. }
  7315. }
  7316. }}
  7317. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7318. data-testid="drying-start-confirm"
  7319. className="w-full py-1.5 bg-bambu-green hover:bg-bambu-green/80 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50"
  7320. >
  7321. {dryingStartMode === 'now'
  7322. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7323. : t('printers.drying.schedule')}
  7324. </button>
  7325. </div>
  7326. </div>
  7327. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7328. since the popover clips its own overflow. */}
  7329. <div
  7330. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7331. style={{
  7332. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7333. top: dryingPopoverPos.anchorY - 5,
  7334. ...(dryingPopoverPos.placement === 'above'
  7335. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7336. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7337. }}
  7338. />
  7339. </>
  7340. );
  7341. })()}
  7342. </Card>
  7343. );
  7344. }
  7345. export function AddPrinterModal({
  7346. onClose,
  7347. onAdd,
  7348. existingSerials,
  7349. }: {
  7350. onClose: () => void;
  7351. onAdd: (data: PrinterCreate) => void;
  7352. existingSerials: string[];
  7353. }) {
  7354. const { t } = useTranslation();
  7355. const [form, setForm] = useState<PrinterCreate>({
  7356. name: '',
  7357. serial_number: '',
  7358. ip_address: '',
  7359. access_code: '',
  7360. model: '',
  7361. location: '',
  7362. auto_archive: true,
  7363. });
  7364. // Discovery state
  7365. const [discovering, setDiscovering] = useState(false);
  7366. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7367. const [discoveryError, setDiscoveryError] = useState('');
  7368. const [hasScanned, setHasScanned] = useState(false);
  7369. const [isDocker, setIsDocker] = useState(false);
  7370. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7371. const [subnet, setSubnet] = useState('');
  7372. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7373. // text input so users can scan a subnet Bambuddy isn't directly on
  7374. // (printer behind a router on a different L3 segment — SSDP multicast
  7375. // won't cross that boundary, only an active unicast scan will). #1564
  7376. const [customSubnet, setCustomSubnet] = useState('');
  7377. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7378. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7379. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7380. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7381. // (not block) when checks fail, so the user doesn't add a printer that
  7382. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7383. // failed result awaiting an explicit "save anyway".
  7384. const [checkingSave, setCheckingSave] = useState(false);
  7385. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7386. // Fetch discovery info on mount + restore the last custom CIDR the user
  7387. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7388. // time they open this modal).
  7389. useEffect(() => {
  7390. discoveryApi.getInfo().then(info => {
  7391. setIsDocker(info.is_docker);
  7392. if (info.subnets.length > 0) {
  7393. setDetectedSubnets(info.subnets);
  7394. setSubnet(info.subnets[0]);
  7395. }
  7396. }).catch(() => {
  7397. // Ignore errors, assume not Docker
  7398. });
  7399. try {
  7400. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7401. if (saved) setCustomSubnet(saved);
  7402. } catch {
  7403. // localStorage unavailable (private mode, quota); recall is opportunistic
  7404. }
  7405. }, []);
  7406. // Filter out already-added printers
  7407. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7408. const handleAddSubmit = async (e: React.FormEvent) => {
  7409. e.preventDefault();
  7410. setCheckingSave(true);
  7411. try {
  7412. const result = await api.diagnoseConnection({
  7413. ip_address: form.ip_address.trim(),
  7414. serial_number: form.serial_number.trim() || undefined,
  7415. access_code: form.access_code || undefined,
  7416. });
  7417. if (result.checks.some((c) => c.status === 'fail')) {
  7418. setSaveWarning(result);
  7419. return;
  7420. }
  7421. } catch {
  7422. // Diagnostic infrastructure failed — never block the save on it.
  7423. } finally {
  7424. setCheckingSave(false);
  7425. }
  7426. onAdd(form);
  7427. };
  7428. const startDiscovery = async () => {
  7429. setDiscoveryError('');
  7430. setDiscovered([]);
  7431. setDiscovering(true);
  7432. setHasScanned(false);
  7433. setScanProgress({ scanned: 0, total: 0 });
  7434. // Native installs fall back to subnet scanning when the user picks
  7435. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7436. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7437. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7438. const wantsSubnetScan = isDocker || useCustomSubnet;
  7439. if (wantsSubnetScan && useCustomSubnet) {
  7440. try {
  7441. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7442. } catch {
  7443. // localStorage write best-effort; user just retypes next time
  7444. }
  7445. }
  7446. try {
  7447. if (wantsSubnetScan) {
  7448. await discoveryApi.startSubnetScan(scanCidr);
  7449. // Poll for scan status and results
  7450. const pollInterval = setInterval(async () => {
  7451. try {
  7452. const status = await discoveryApi.getScanStatus();
  7453. setScanProgress({ scanned: status.scanned, total: status.total });
  7454. const printers = await discoveryApi.getDiscoveredPrinters();
  7455. setDiscovered(printers);
  7456. if (!status.running) {
  7457. clearInterval(pollInterval);
  7458. setDiscovering(false);
  7459. setHasScanned(true);
  7460. }
  7461. } catch (e) {
  7462. console.error('Failed to get scan status:', e);
  7463. }
  7464. }, 500);
  7465. } else {
  7466. // Use SSDP discovery for native installs
  7467. await discoveryApi.startDiscovery(10);
  7468. // Poll for discovered printers every second
  7469. const pollInterval = setInterval(async () => {
  7470. try {
  7471. const printers = await discoveryApi.getDiscoveredPrinters();
  7472. setDiscovered(printers);
  7473. } catch (e) {
  7474. console.error('Failed to get discovered printers:', e);
  7475. }
  7476. }, 1000);
  7477. // Stop after 10 seconds
  7478. setTimeout(async () => {
  7479. clearInterval(pollInterval);
  7480. try {
  7481. await discoveryApi.stopDiscovery();
  7482. } catch {
  7483. // Ignore stop errors
  7484. }
  7485. setDiscovering(false);
  7486. setHasScanned(true);
  7487. // Final fetch
  7488. try {
  7489. const printers = await discoveryApi.getDiscoveredPrinters();
  7490. setDiscovered(printers);
  7491. } catch (e) {
  7492. console.error('Failed to get final discovered printers:', e);
  7493. }
  7494. }, 10000);
  7495. }
  7496. } catch (e) {
  7497. console.error('Failed to start discovery:', e);
  7498. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7499. setDiscovering(false);
  7500. setHasScanned(true);
  7501. }
  7502. };
  7503. // Reuse module-level mapModelCode
  7504. const selectPrinter = (printer: DiscoveredPrinter) => {
  7505. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7506. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7507. setForm({
  7508. ...form,
  7509. name: printer.name || '',
  7510. serial_number: serialNumber,
  7511. ip_address: printer.ip_address,
  7512. model: mapModelCode(printer.model),
  7513. });
  7514. // Clear discovery results after selection
  7515. setDiscovered([]);
  7516. };
  7517. // Cleanup discovery on unmount
  7518. useEffect(() => {
  7519. return () => {
  7520. discoveryApi.stopDiscovery().catch(() => {});
  7521. discoveryApi.stopSubnetScan().catch(() => {});
  7522. };
  7523. }, []);
  7524. // Close on Escape key
  7525. useEffect(() => {
  7526. const handleKeyDown = (e: KeyboardEvent) => {
  7527. if (e.key === 'Escape') onClose();
  7528. };
  7529. window.addEventListener('keydown', handleKeyDown);
  7530. return () => window.removeEventListener('keydown', handleKeyDown);
  7531. }, [onClose]);
  7532. return (
  7533. <>
  7534. <div
  7535. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7536. onClick={onClose}
  7537. >
  7538. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7539. <CardContent>
  7540. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7541. {/* Discovery Section */}
  7542. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7543. {/* Subnet picker — always visible. The dropdown lists detected
  7544. interface subnets and a "Custom..." sentinel that reveals
  7545. a CIDR text input for printers on a different L3 segment
  7546. (router, VLAN, etc.). #1564 */}
  7547. <div className="mb-3">
  7548. <label className="block text-sm text-bambu-gray mb-1">
  7549. {t('printers.discovery.subnetToScan')}
  7550. </label>
  7551. {detectedSubnets.length > 0 ? (
  7552. <select
  7553. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  7554. value={useCustomSubnet ? '__custom__' : subnet}
  7555. onChange={(e) => {
  7556. if (e.target.value === '__custom__') {
  7557. setUseCustomSubnet(true);
  7558. } else {
  7559. setUseCustomSubnet(false);
  7560. setSubnet(e.target.value);
  7561. }
  7562. }}
  7563. disabled={discovering}
  7564. >
  7565. {detectedSubnets.map(s => (
  7566. <option key={s} value={s}>{s}</option>
  7567. ))}
  7568. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7569. </select>
  7570. ) : (
  7571. <input
  7572. type="text"
  7573. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  7574. value={subnet}
  7575. onChange={(e) => setSubnet(e.target.value)}
  7576. placeholder="192.168.1.0/24"
  7577. disabled={discovering}
  7578. />
  7579. )}
  7580. {useCustomSubnet && (
  7581. <input
  7582. type="text"
  7583. aria-label={t('printers.discovery.customSubnetLabel')}
  7584. className="mt-2 w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  7585. value={customSubnet}
  7586. onChange={(e) => setCustomSubnet(e.target.value)}
  7587. placeholder="10.1.1.0/24"
  7588. disabled={discovering}
  7589. />
  7590. )}
  7591. <p className="mt-1 text-xs text-bambu-gray">
  7592. {isDocker
  7593. ? t('printers.discovery.dockerNote')
  7594. : t('printers.discovery.customSubnetNote')}
  7595. </p>
  7596. </div>
  7597. <Button
  7598. type="button"
  7599. variant="secondary"
  7600. onClick={startDiscovery}
  7601. disabled={discovering}
  7602. className="w-full"
  7603. >
  7604. {discovering ? (
  7605. <>
  7606. <Loader2 className="w-4 h-4 animate-spin" />
  7607. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7608. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7609. : t('printers.discovery.scanning')}
  7610. </>
  7611. ) : (
  7612. <>
  7613. <Search className="w-4 h-4" />
  7614. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7615. </>
  7616. )}
  7617. </Button>
  7618. {discoveryError && (
  7619. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7620. )}
  7621. {newPrinters.length > 0 && (
  7622. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7623. {newPrinters.map((printer) => (
  7624. <div
  7625. key={printer.serial}
  7626. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7627. onClick={() => selectPrinter(printer)}
  7628. >
  7629. <div className="min-w-0 flex-1">
  7630. <p className="font-medium text-white text-sm truncate">
  7631. {printer.name || printer.serial}
  7632. </p>
  7633. <p className="text-xs text-bambu-gray truncate">
  7634. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7635. {printer.serial.startsWith('unknown-') && (
  7636. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7637. )}
  7638. </p>
  7639. </div>
  7640. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7641. </div>
  7642. ))}
  7643. </div>
  7644. )}
  7645. {discovering && (
  7646. <p className="mt-2 text-sm text-bambu-gray text-center">
  7647. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7648. </p>
  7649. )}
  7650. {hasScanned && !discovering && discovered.length === 0 && (
  7651. <p className="mt-2 text-sm text-bambu-gray text-center">
  7652. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7653. </p>
  7654. )}
  7655. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7656. <p className="mt-2 text-sm text-bambu-gray text-center">
  7657. {t('printers.discovery.allConfigured')}
  7658. </p>
  7659. )}
  7660. </div>
  7661. <form onSubmit={handleAddSubmit} className="space-y-4">
  7662. <div>
  7663. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7664. <input
  7665. type="text"
  7666. required
  7667. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7668. value={form.name}
  7669. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7670. placeholder={t('printers.modal.myPrinter')}
  7671. />
  7672. </div>
  7673. <div>
  7674. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7675. <input
  7676. type="text"
  7677. required
  7678. pattern="(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)"
  7679. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7680. value={form.ip_address}
  7681. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7682. placeholder="192.168.1.100 or printer.local"
  7683. />
  7684. </div>
  7685. <div>
  7686. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7687. <input
  7688. type="text"
  7689. required
  7690. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7691. value={form.serial_number}
  7692. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7693. placeholder="01P00A000000000"
  7694. />
  7695. </div>
  7696. <div>
  7697. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7698. <input
  7699. type="password"
  7700. required
  7701. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7702. value={form.access_code}
  7703. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7704. placeholder={t('printers.modal.fromPrinterSettings')}
  7705. />
  7706. </div>
  7707. <div>
  7708. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7709. <select
  7710. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7711. value={form.model || ''}
  7712. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7713. >
  7714. <option value="">{t('printers.modal.selectModel')}</option>
  7715. <optgroup label="A1 Series">
  7716. <option value="A1">A1</option>
  7717. <option value="A1 Mini">A1 Mini</option>
  7718. </optgroup>
  7719. <optgroup label="A2 Series">
  7720. <option value="A2L">A2L</option>
  7721. </optgroup>
  7722. <optgroup label="H2 Series">
  7723. <option value="H2C">H2C</option>
  7724. <option value="H2D">H2D</option>
  7725. <option value="H2D Pro">H2D Pro</option>
  7726. <option value="H2S">H2S</option>
  7727. </optgroup>
  7728. <optgroup label="P Series">
  7729. <option value="P1P">P1P</option>
  7730. <option value="P1S">P1S</option>
  7731. <option value="P2S">P2S</option>
  7732. </optgroup>
  7733. <optgroup label="X1 Series">
  7734. <option value="X1">X1</option>
  7735. <option value="X1C">X1 Carbon</option>
  7736. <option value="X1E">X1E</option>
  7737. </optgroup>
  7738. <optgroup label="X2 Series">
  7739. <option value="X2D">X2D</option>
  7740. </optgroup>
  7741. </select>
  7742. </div>
  7743. <div>
  7744. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7745. <input
  7746. type="text"
  7747. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7748. value={form.location || ''}
  7749. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7750. placeholder={t('printers.modal.locationPlaceholder')}
  7751. maxLength={100}
  7752. />
  7753. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7754. </div>
  7755. <div className="flex items-center gap-2">
  7756. <input
  7757. type="checkbox"
  7758. id="auto_archive"
  7759. checked={form.auto_archive}
  7760. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7761. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7762. />
  7763. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7764. {t('printers.modal.autoArchiveLabel')}
  7765. </label>
  7766. </div>
  7767. <button
  7768. type="button"
  7769. onClick={() => setShowDiagnostic(true)}
  7770. disabled={!form.ip_address.trim()}
  7771. className="w-full flex items-center justify-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white disabled:opacity-40 disabled:cursor-not-allowed border border-bambu-dark-tertiary rounded-lg transition-colors"
  7772. >
  7773. <Stethoscope className="w-4 h-4" />
  7774. {t('diagnostic.runButton')}
  7775. </button>
  7776. {saveWarning ? (
  7777. <div className="rounded-lg bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 p-3 space-y-3">
  7778. <div className="flex items-start gap-2">
  7779. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7780. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7781. </div>
  7782. <DiagnosticChecklist result={saveWarning} />
  7783. <div className="flex gap-3">
  7784. <Button
  7785. type="button"
  7786. variant="secondary"
  7787. onClick={() => setSaveWarning(null)}
  7788. className="flex-1"
  7789. >
  7790. {t('printers.addPreflight.back')}
  7791. </Button>
  7792. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7793. {t('printers.addPreflight.saveAnyway')}
  7794. </Button>
  7795. </div>
  7796. </div>
  7797. ) : (
  7798. <div className="flex gap-3 pt-2">
  7799. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7800. {t('common.cancel')}
  7801. </Button>
  7802. <Button type="submit" disabled={checkingSave} className="flex-1">
  7803. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7804. </Button>
  7805. </div>
  7806. )}
  7807. </form>
  7808. </CardContent>
  7809. </Card>
  7810. </div>
  7811. {showDiagnostic && (
  7812. <ConnectionDiagnosticModal
  7813. connection={{
  7814. ip_address: form.ip_address.trim(),
  7815. serial_number: form.serial_number.trim() || undefined,
  7816. access_code: form.access_code || undefined,
  7817. }}
  7818. printerName={form.name || null}
  7819. onClose={() => setShowDiagnostic(false)}
  7820. />
  7821. )}
  7822. </>
  7823. );
  7824. }
  7825. function FirmwareUpdateModal({
  7826. printer,
  7827. firmwareInfo,
  7828. onClose,
  7829. }: {
  7830. printer: Printer;
  7831. firmwareInfo: FirmwareUpdateInfo;
  7832. onClose: () => void;
  7833. }) {
  7834. const { t } = useTranslation();
  7835. const queryClient = useQueryClient();
  7836. const { showToast } = useToast();
  7837. const { hasPermission } = useAuth();
  7838. const canUpdate = hasPermission('firmware:update');
  7839. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7840. const [isUploading, setIsUploading] = useState(false);
  7841. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7842. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7843. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7844. );
  7845. // Prepare check query — runs when a version is selected and user can update
  7846. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7847. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7848. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7849. staleTime: 30000,
  7850. enabled: !!selectedVersion && canUpdate && !isUploading,
  7851. });
  7852. // Start upload mutation
  7853. const uploadMutation = useMutation({
  7854. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7855. onSuccess: () => {
  7856. setIsUploading(true);
  7857. // Start polling for status
  7858. const interval = setInterval(async () => {
  7859. try {
  7860. const status = await firmwareApi.getUploadStatus(printer.id);
  7861. setUploadStatus(status);
  7862. if (status.status === 'complete' || status.status === 'error') {
  7863. clearInterval(interval);
  7864. setPollInterval(null);
  7865. setIsUploading(false);
  7866. if (status.status === 'complete') {
  7867. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7868. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7869. }
  7870. }
  7871. } catch {
  7872. // Ignore errors during polling
  7873. }
  7874. }, 2000);
  7875. setPollInterval(interval);
  7876. },
  7877. onError: (error: Error) => {
  7878. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7879. setIsUploading(false);
  7880. },
  7881. });
  7882. // Cleanup on unmount
  7883. useEffect(() => {
  7884. return () => {
  7885. if (pollInterval) clearInterval(pollInterval);
  7886. };
  7887. }, [pollInterval]);
  7888. const handleStartUpload = () => {
  7889. setUploadStatus(null);
  7890. uploadMutation.mutate();
  7891. };
  7892. return (
  7893. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7894. <Card className="w-full max-w-md mx-4">
  7895. <CardContent>
  7896. <div className="flex items-start gap-3 mb-4">
  7897. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7898. {firmwareInfo.update_available
  7899. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7900. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7901. </div>
  7902. <div className="flex-1">
  7903. <h3 className="text-lg font-semibold text-white">
  7904. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7905. </h3>
  7906. <p className="text-sm text-bambu-gray mt-1">
  7907. {printer.name}
  7908. </p>
  7909. </div>
  7910. </div>
  7911. {/* Version Info */}
  7912. {(() => {
  7913. const selectedEntry = selectedVersion
  7914. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7915. : null;
  7916. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7917. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7918. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7919. return (
  7920. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7921. <div className="flex justify-between items-center text-sm">
  7922. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7923. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7924. {firmwareInfo.current_version || t('common.unknown')}
  7925. </span>
  7926. </div>
  7927. {showSecondLine && (
  7928. <div className="flex justify-between items-center text-sm mt-1">
  7929. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7930. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7931. </div>
  7932. )}
  7933. {displayNotes && (
  7934. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7935. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7936. {t('printers.firmwareModal.releaseNotes')}
  7937. </summary>
  7938. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7939. {displayNotes}
  7940. </div>
  7941. </details>
  7942. )}
  7943. </div>
  7944. );
  7945. })()}
  7946. {/* Available versions list */}
  7947. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7948. <div className="mb-4">
  7949. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7950. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7951. {firmwareInfo.available_versions.map((v) => {
  7952. const isCurrent = firmwareInfo.current_version === v.version;
  7953. const isSelected = selectedVersion === v.version;
  7954. const cmp = firmwareInfo.current_version
  7955. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7956. : 0;
  7957. const relLabel = isCurrent
  7958. ? t('printers.firmwareModal.currentBadge')
  7959. : cmp > 0
  7960. ? t('printers.firmwareModal.newerBadge')
  7961. : t('printers.firmwareModal.olderBadge');
  7962. const relClass = isCurrent
  7963. ? 'text-bambu-gray'
  7964. : cmp > 0
  7965. ? 'text-orange-700 dark:text-orange-400'
  7966. : 'text-blue-700 dark:text-blue-400';
  7967. return (
  7968. <button
  7969. key={v.version}
  7970. type="button"
  7971. disabled={!v.file_available || !canUpdate || isCurrent}
  7972. onClick={() => setSelectedVersion(v.version)}
  7973. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7974. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7975. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7976. >
  7977. <div className="flex items-center gap-2 min-w-0">
  7978. <span className="font-mono text-white">{v.version}</span>
  7979. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7980. </div>
  7981. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7982. isCurrent
  7983. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7984. : v.file_available
  7985. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7986. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7987. }`}>
  7988. {isCurrent
  7989. ? t('printers.firmwareModal.installed')
  7990. : v.file_available
  7991. ? t('printers.firmwareModal.usable')
  7992. : t('printers.firmwareModal.unavailable')}
  7993. </span>
  7994. </button>
  7995. );
  7996. })}
  7997. </div>
  7998. </div>
  7999. )}
  8000. {/* Status / Progress (only when a version is selected) */}
  8001. {!selectedVersion ? null : isPreparing ? (
  8002. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  8003. <Loader2 className="w-4 h-4 animate-spin" />
  8004. {t('printers.firmwareModal.checkingPrereqs')}
  8005. </div>
  8006. ) : prepareInfo && !isUploading && !uploadStatus ? (
  8007. <div className="mb-4">
  8008. {prepareInfo.can_proceed ? (
  8009. <div className="flex items-center gap-2 text-bambu-green text-sm">
  8010. <Box className="w-4 h-4" />
  8011. {t('printers.firmwareModal.sdCardReady')}
  8012. </div>
  8013. ) : (
  8014. <div className="space-y-1">
  8015. {prepareInfo.errors.map((error, i) => (
  8016. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  8017. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  8018. {error}
  8019. </div>
  8020. ))}
  8021. </div>
  8022. )}
  8023. </div>
  8024. ) : null}
  8025. {/* Upload Progress */}
  8026. {(isUploading || uploadStatus) && uploadStatus && (
  8027. <div className="mb-4">
  8028. <div className="flex items-center justify-between text-sm mb-1">
  8029. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8030. <span className="text-white">{uploadStatus.progress}%</span>
  8031. </div>
  8032. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8033. <div
  8034. className={`h-2 rounded-full transition-all ${
  8035. uploadStatus.status === 'error' ? 'bg-status-error' :
  8036. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8037. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8038. style={{ width: `${uploadStatus.progress}%` }}
  8039. />
  8040. </div>
  8041. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8042. {uploadStatus.error && (
  8043. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8044. )}
  8045. </div>
  8046. )}
  8047. {/* Success Message */}
  8048. {uploadStatus?.status === 'complete' && (
  8049. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8050. <p className="text-sm text-bambu-green font-medium mb-2">
  8051. {t('printers.firmwareModal.uploadedSuccess')}
  8052. </p>
  8053. <p className="text-xs text-bambu-gray">
  8054. {t('printers.firmwareModal.applyInstructions')}
  8055. </p>
  8056. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8057. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8058. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8059. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8060. <li>{t('printers.firmwareModal.step4')}</li>
  8061. </ol>
  8062. </div>
  8063. )}
  8064. {/* Buttons */}
  8065. <div className="flex gap-2 justify-end">
  8066. <Button variant="secondary" onClick={onClose}>
  8067. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8068. </Button>
  8069. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8070. <Button
  8071. onClick={handleStartUpload}
  8072. disabled={uploadMutation.isPending}
  8073. >
  8074. {uploadMutation.isPending ? (
  8075. <>
  8076. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8077. {t('printers.firmwareModal.starting')}
  8078. </>
  8079. ) : (
  8080. <>
  8081. <Download className="w-4 h-4 mr-2" />
  8082. {t('printers.firmwareModal.uploadFirmware')}
  8083. </>
  8084. )}
  8085. </Button>
  8086. )}
  8087. </div>
  8088. </CardContent>
  8089. </Card>
  8090. </div>
  8091. );
  8092. }
  8093. function EditPrinterModal({
  8094. printer,
  8095. onClose,
  8096. }: {
  8097. printer: Printer;
  8098. onClose: () => void;
  8099. }) {
  8100. const { t } = useTranslation();
  8101. const queryClient = useQueryClient();
  8102. const { showToast } = useToast();
  8103. const { authEnabled, isAdmin } = useAuth();
  8104. const [form, setForm] = useState({
  8105. name: printer.name,
  8106. ip_address: printer.ip_address,
  8107. access_code: '',
  8108. model: printer.model || '',
  8109. location: printer.location || '',
  8110. auto_archive: printer.auto_archive,
  8111. is_active: printer.is_active,
  8112. wear_cost_per_hour: printer.wear_cost_per_hour ? String(printer.wear_cost_per_hour) : '',
  8113. });
  8114. const { data: settings } = useUiSettings();
  8115. const currency = getCurrencySymbol(settings?.currency || 'USD');
  8116. // Groups can be given a location (#1727), so a move changes who can use the
  8117. // printer. Non-admins can't read groups; the server refuses their move instead.
  8118. const { data: groups } = useQuery({
  8119. queryKey: ['groups'],
  8120. queryFn: () => api.getGroups(),
  8121. enabled: authEnabled && isAdmin,
  8122. });
  8123. const newLocation = form.location.trim();
  8124. const accessChangedFor =
  8125. newLocation !== (printer.location || '')
  8126. ? (groups ?? [])
  8127. .filter(
  8128. (g) =>
  8129. g.restrict_printers &&
  8130. (g.locations ?? []).some((loc) => loc === printer.location || loc === newLocation)
  8131. )
  8132. .map((g) => g.name)
  8133. : [];
  8134. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8135. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8136. const [checkingSave, setCheckingSave] = useState(false);
  8137. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8138. const updateMutation = useMutation({
  8139. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8140. onSuccess: () => {
  8141. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8142. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8143. onClose();
  8144. },
  8145. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8146. });
  8147. // Close on Escape key
  8148. useEffect(() => {
  8149. const handleKeyDown = (e: KeyboardEvent) => {
  8150. if (e.key === 'Escape') onClose();
  8151. };
  8152. window.addEventListener('keydown', handleKeyDown);
  8153. return () => window.removeEventListener('keydown', handleKeyDown);
  8154. }, [onClose]);
  8155. const doSave = () => {
  8156. const data: Partial<PrinterCreate> = {
  8157. name: form.name,
  8158. ip_address: form.ip_address,
  8159. model: form.model || undefined,
  8160. // null clears it; leaving it out kept the old location
  8161. location: form.location.trim() || null,
  8162. auto_archive: form.auto_archive,
  8163. is_active: form.is_active,
  8164. // Empty or 0 turns wear cost off for this printer (#694)
  8165. wear_cost_per_hour: Number(form.wear_cost_per_hour) > 0 ? Number(form.wear_cost_per_hour) : null,
  8166. };
  8167. // Only include access_code if it was changed
  8168. if (form.access_code) {
  8169. data.access_code = form.access_code;
  8170. }
  8171. updateMutation.mutate(data);
  8172. };
  8173. const handleSubmit = async (e: React.FormEvent) => {
  8174. e.preventDefault();
  8175. setCheckingSave(true);
  8176. try {
  8177. const result = await api.diagnoseConnection({
  8178. ip_address: form.ip_address.trim(),
  8179. serial_number: printer.serial_number,
  8180. access_code: form.access_code || undefined,
  8181. });
  8182. if (result.checks.some((c) => c.status === 'fail')) {
  8183. setSaveWarning(result);
  8184. return;
  8185. }
  8186. } catch {
  8187. // Diagnostic infrastructure failed — never block the save on it.
  8188. } finally {
  8189. setCheckingSave(false);
  8190. }
  8191. doSave();
  8192. };
  8193. return (
  8194. <div
  8195. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8196. onClick={onClose}
  8197. >
  8198. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8199. <CardContent>
  8200. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8201. <form onSubmit={handleSubmit} className="space-y-4">
  8202. <div>
  8203. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8204. <input
  8205. type="text"
  8206. required
  8207. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8208. value={form.name}
  8209. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8210. placeholder={t('printers.modal.myPrinter')}
  8211. />
  8212. </div>
  8213. <div>
  8214. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8215. <input
  8216. type="text"
  8217. required
  8218. pattern="(\d{1,3}(\.\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)"
  8219. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8220. value={form.ip_address}
  8221. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8222. placeholder="192.168.1.100 or printer.local"
  8223. />
  8224. </div>
  8225. <div>
  8226. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8227. <input
  8228. type="text"
  8229. disabled
  8230. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8231. value={printer.serial_number}
  8232. />
  8233. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8234. </div>
  8235. <div>
  8236. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8237. <input
  8238. type="password"
  8239. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8240. value={form.access_code}
  8241. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8242. placeholder={t('printers.accessCodePlaceholder')}
  8243. />
  8244. </div>
  8245. <div>
  8246. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8247. <select
  8248. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8249. value={form.model}
  8250. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8251. >
  8252. <option value="">{t('printers.modal.selectModel')}</option>
  8253. <optgroup label="A1 Series">
  8254. <option value="A1">A1</option>
  8255. <option value="A1 Mini">A1 Mini</option>
  8256. </optgroup>
  8257. <optgroup label="A2 Series">
  8258. <option value="A2L">A2L</option>
  8259. </optgroup>
  8260. <optgroup label="H2 Series">
  8261. <option value="H2C">H2C</option>
  8262. <option value="H2D">H2D</option>
  8263. <option value="H2D Pro">H2D Pro</option>
  8264. <option value="H2S">H2S</option>
  8265. </optgroup>
  8266. <optgroup label="P Series">
  8267. <option value="P1P">P1P</option>
  8268. <option value="P1S">P1S</option>
  8269. <option value="P2S">P2S</option>
  8270. </optgroup>
  8271. <optgroup label="X1 Series">
  8272. <option value="X1">X1</option>
  8273. <option value="X1C">X1 Carbon</option>
  8274. <option value="X1E">X1E</option>
  8275. </optgroup>
  8276. <optgroup label="X2 Series">
  8277. <option value="X2D">X2D</option>
  8278. </optgroup>
  8279. </select>
  8280. </div>
  8281. <div>
  8282. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8283. <input
  8284. type="text"
  8285. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8286. value={form.location}
  8287. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8288. placeholder={t('printers.modal.locationPlaceholder')}
  8289. maxLength={100}
  8290. />
  8291. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8292. {accessChangedFor.length > 0 && (
  8293. <p className="flex items-start gap-1.5 text-xs text-yellow-700 dark:text-yellow-400 mt-1">
  8294. <AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-px" />
  8295. {t('printerAccess.moveWarning', { groups: accessChangedFor.join(', ') })}
  8296. </p>
  8297. )}
  8298. </div>
  8299. <div className="flex items-center gap-2">
  8300. <input
  8301. type="checkbox"
  8302. id="edit_auto_archive"
  8303. checked={form.auto_archive}
  8304. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8305. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8306. />
  8307. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8308. {t('printers.modal.autoArchiveLabel')}
  8309. </label>
  8310. </div>
  8311. <div>
  8312. <label htmlFor="edit_wear_cost" className="block text-sm text-bambu-gray mb-1">
  8313. {t('printers.modal.wearCostLabel', { currency })}
  8314. </label>
  8315. <input
  8316. id="edit_wear_cost"
  8317. type="number"
  8318. min={0}
  8319. step="0.01"
  8320. inputMode="decimal"
  8321. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8322. value={form.wear_cost_per_hour}
  8323. onChange={(e) => setForm({ ...form, wear_cost_per_hour: e.target.value })}
  8324. placeholder="0.00"
  8325. />
  8326. <p className="text-xs text-bambu-gray mt-1">{t('printers.modal.wearCostHelp')}</p>
  8327. </div>
  8328. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8329. is_active because the user-facing concept is "is this printer
  8330. in maintenance" not "is it active". */}
  8331. <div>
  8332. <div className="flex items-center gap-2">
  8333. <input
  8334. type="checkbox"
  8335. id="edit_maintenance_mode"
  8336. checked={!form.is_active}
  8337. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8338. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8339. />
  8340. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8341. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8342. {t('printers.maintenance.editFieldLabel')}
  8343. </label>
  8344. </div>
  8345. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8346. {t('printers.maintenance.editFieldHelp')}
  8347. </p>
  8348. </div>
  8349. {saveWarning ? (
  8350. <div className="rounded-lg bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 p-3 space-y-3">
  8351. <div className="flex items-start gap-2">
  8352. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8353. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8354. </div>
  8355. <DiagnosticChecklist result={saveWarning} />
  8356. <div className="flex gap-3">
  8357. <Button
  8358. type="button"
  8359. variant="secondary"
  8360. onClick={() => setSaveWarning(null)}
  8361. className="flex-1"
  8362. >
  8363. {t('printers.addPreflight.back')}
  8364. </Button>
  8365. <Button
  8366. type="button"
  8367. onClick={doSave}
  8368. className="flex-1"
  8369. disabled={updateMutation.isPending}
  8370. >
  8371. {t('printers.addPreflight.saveAnyway')}
  8372. </Button>
  8373. </div>
  8374. </div>
  8375. ) : (
  8376. <div className="flex gap-3 pt-4">
  8377. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8378. {t('common.cancel')}
  8379. </Button>
  8380. <Button
  8381. type="submit"
  8382. className="flex-1"
  8383. disabled={updateMutation.isPending || checkingSave}
  8384. >
  8385. {checkingSave
  8386. ? t('printers.addPreflight.checking')
  8387. : updateMutation.isPending
  8388. ? t('common.saving')
  8389. : t('printers.modal.saveChanges')}
  8390. </Button>
  8391. </div>
  8392. )}
  8393. </form>
  8394. </CardContent>
  8395. </Card>
  8396. </div>
  8397. );
  8398. }
  8399. // Component to check if a printer is offline (for power dropdown)
  8400. function usePrinterOfflineStatus(printerId: number) {
  8401. const { data: status } = useQuery({
  8402. queryKey: ['printerStatus', printerId],
  8403. queryFn: () => api.getPrinterStatus(printerId),
  8404. refetchInterval: 30000,
  8405. });
  8406. return !status?.connected;
  8407. }
  8408. // Power dropdown item for an offline printer
  8409. function PowerDropdownItem({
  8410. printer,
  8411. plug,
  8412. onPowerOn,
  8413. isPowering,
  8414. }: {
  8415. printer: Printer;
  8416. plug: { id: number; name: string };
  8417. onPowerOn: (plugId: number) => void;
  8418. isPowering: boolean;
  8419. }) {
  8420. const isOffline = usePrinterOfflineStatus(printer.id);
  8421. // Fetch plug status
  8422. const { data: plugStatus } = useQuery({
  8423. queryKey: ['smartPlugStatus', plug.id],
  8424. queryFn: () => api.getSmartPlugStatus(plug.id),
  8425. refetchInterval: 10000,
  8426. });
  8427. // Only show if printer is offline
  8428. if (!isOffline) {
  8429. return null;
  8430. }
  8431. return (
  8432. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8433. <div className="flex items-center gap-2 min-w-0">
  8434. <span className="text-sm text-white truncate">{printer.name}</span>
  8435. {plugStatus && (
  8436. <span
  8437. className={`text-xs px-1.5 py-0.5 rounded ${
  8438. plugStatus.state === 'ON'
  8439. ? 'bg-bambu-green/20 text-bambu-green'
  8440. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8441. }`}
  8442. >
  8443. {plugStatus.state || '?'}
  8444. </span>
  8445. )}
  8446. </div>
  8447. <button
  8448. onClick={() => onPowerOn(plug.id)}
  8449. disabled={isPowering || plugStatus?.state === 'ON'}
  8450. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8451. plugStatus?.state === 'ON'
  8452. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8453. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8454. }`}
  8455. >
  8456. <Power className="w-3 h-3" />
  8457. {isPowering ? '...' : 'On'}
  8458. </button>
  8459. </div>
  8460. );
  8461. }
  8462. export function PrintersPage() {
  8463. const { t } = useTranslation();
  8464. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8465. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8466. const accentButtonClass = {
  8467. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8468. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8469. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8470. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8471. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8472. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8473. }[activeAccent];
  8474. const [showAddModal, setShowAddModal] = useState(false);
  8475. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8476. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8477. });
  8478. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8479. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8480. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8481. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8482. });
  8483. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8484. return localStorage.getItem('printerSortAsc') !== 'false';
  8485. });
  8486. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8487. const [cardSize, setCardSize] = useState<number>(() => {
  8488. const saved = localStorage.getItem('printerCardSize');
  8489. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8490. });
  8491. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8492. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8493. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8494. });
  8495. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8496. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8497. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8498. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8499. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8500. });
  8501. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8502. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8503. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8504. });
  8505. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8506. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8507. // Defaulting to 'full' because the cards already show this info — users who
  8508. // pick cam-wall view still want to glance the same details without flipping.
  8509. // Kept apart from the card size: S on the cards also means the compact
  8510. // layout, and a wall of 2 cameras wants big tiles next to small cards (#2735).
  8511. const [camWallTileSize, setCamWallTileSize] = useState<number>(() => {
  8512. const saved = parseInt(localStorage.getItem('camWallTileSize') || '', 10);
  8513. return saved >= 1 && saved <= 4 ? saved : DEFAULT_CAM_WALL_TILE_SIZE;
  8514. });
  8515. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8516. const saved = localStorage.getItem('camWallStatusMode');
  8517. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8518. });
  8519. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8520. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8521. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8522. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8523. requestAnimationFrame(() => {
  8524. requestAnimationFrame(() => {
  8525. const card = document.getElementById(`printer-card-${printerId}`);
  8526. if (!card) return;
  8527. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8528. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8529. window.scrollTo({
  8530. top: Math.max(0, top),
  8531. behavior: 'smooth',
  8532. });
  8533. });
  8534. });
  8535. }, []);
  8536. const openCompactCard = useCallback((printerId: number) => {
  8537. setCompactDrilldownPrinterId(printerId);
  8538. setCardSize(2);
  8539. localStorage.setItem('printerCardSize', '2');
  8540. scrollPrinterIntoView(printerId);
  8541. }, [scrollPrinterIntoView]);
  8542. const returnToCompactCards = useCallback(() => {
  8543. const printerId = compactDrilldownPrinterId;
  8544. setCompactDrilldownPrinterId(null);
  8545. setCardSize(1);
  8546. localStorage.setItem('printerCardSize', '1');
  8547. if (printerId != null) {
  8548. scrollPrinterIntoView(printerId);
  8549. }
  8550. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8551. const [search, setSearch] = useState('');
  8552. // Both filters persist like every other preference on this page (#2833).
  8553. // `search` deliberately does not: a box that silently refills itself on
  8554. // return is more surprising than a dropdown that remembers.
  8555. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8556. // Validated on read: a value the dropdown no longer offers would filter
  8557. // every printer out, and nothing would explain why.
  8558. const saved = localStorage.getItem('printerStatusFilter');
  8559. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8560. });
  8561. const [locationFilter, setLocationFilter] = useState<string>(
  8562. () => localStorage.getItem('printerLocationFilter') || 'all'
  8563. );
  8564. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8565. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8566. try {
  8567. const saved = localStorage.getItem('printerCollapsedSections');
  8568. return saved ? JSON.parse(saved) : {};
  8569. } catch { return {}; }
  8570. });
  8571. const queryClient = useQueryClient();
  8572. const { showToast } = useToast();
  8573. const { hasPermission } = useAuth();
  8574. // Which way the camera buttons open a stream. Chosen per click from the
  8575. // button's own menu; null until this browser has made a choice, so the
  8576. // stored setting below can act as the default a fresh browser starts from.
  8577. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8578. () => readStoredCameraViewMode()
  8579. );
  8580. // Embedded camera viewer state - supports multiple simultaneous viewers
  8581. // Persisted to localStorage so cameras reopen after navigation
  8582. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8583. const saved = localStorage.getItem('openEmbeddedCameras');
  8584. if (saved) {
  8585. try {
  8586. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8587. return new Map(cameras.map(c => [c.id, c]));
  8588. } catch {
  8589. return new Map();
  8590. }
  8591. }
  8592. return new Map();
  8593. });
  8594. // Persist open cameras to localStorage when they change
  8595. useEffect(() => {
  8596. const cameras = Array.from(embeddedCameraPrinters.values());
  8597. if (cameras.length > 0) {
  8598. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8599. } else {
  8600. localStorage.removeItem('openEmbeddedCameras');
  8601. }
  8602. }, [embeddedCameraPrinters]);
  8603. const { data: printers, isLoading } = useQuery({
  8604. queryKey: ['printers'],
  8605. queryFn: api.getPrinters,
  8606. });
  8607. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8608. // so users with printers:read but no settings:read still get the values needed
  8609. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8610. const { data: settings } = useQuery({
  8611. queryKey: ['ui-preferences'],
  8612. queryFn: api.getUiPreferences,
  8613. });
  8614. // Only once the preferences are in: deciding on `undefined` meant a check
  8615. // switched off still went out once per printer on every page load.
  8616. const firmwareChecksOn = settings !== undefined && settings.check_printer_firmware !== false;
  8617. // Parse user-configured temperature/fan presets once, with defensive fallback
  8618. // to built-in defaults on parse failure (validators on the backend already
  8619. // reject malformed writes, so this is just forward-compat).
  8620. const effectiveNozzleTempPresets = useMemo(
  8621. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8622. [settings?.nozzle_temp_presets],
  8623. );
  8624. const effectiveBedTempPresets = useMemo(
  8625. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8626. [settings?.bed_temp_presets],
  8627. );
  8628. const effectiveChamberTempPresets = useMemo(
  8629. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8630. [settings?.chamber_temp_presets],
  8631. );
  8632. const effectiveFanSpeedPresets = useMemo(
  8633. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8634. [settings?.fan_speed_presets],
  8635. );
  8636. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8637. const effectiveDryingPresets = useMemo(() => {
  8638. if (settings?.drying_presets) {
  8639. try {
  8640. const userPresets = JSON.parse(settings.drying_presets);
  8641. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8642. return { ...DRYING_PRESETS, ...userPresets };
  8643. }
  8644. } catch { /* ignore parse errors, use defaults */ }
  8645. }
  8646. return DRYING_PRESETS;
  8647. }, [settings?.drying_presets]);
  8648. // The local choice wins over the stored one: someone without settings:update
  8649. // cannot write their pick back, and a preference that silently reverted on
  8650. // the next render would be worse than none at all.
  8651. const cameraViewMode: CameraViewMode =
  8652. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8653. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8654. storeCameraViewMode(mode);
  8655. setChosenCameraViewMode(mode);
  8656. // Best effort, and only a default for other browsers -- the choice is
  8657. // already in effect here. Users below settings:update simply keep theirs
  8658. // locally, which is why the failure is logged rather than surfaced.
  8659. if (hasPermission('settings:update')) {
  8660. api.updateSettings({ camera_view_mode: mode })
  8661. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8662. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8663. }
  8664. }, [hasPermission, queryClient]);
  8665. // Fetch all smart plugs to know which printers have them
  8666. const { data: smartPlugs } = useQuery({
  8667. queryKey: ['smart-plugs'],
  8668. queryFn: api.getSmartPlugs,
  8669. });
  8670. // Fetch maintenance overview for all printers to show badges
  8671. const { data: maintenanceOverview } = useQuery({
  8672. queryKey: ['maintenanceOverview'],
  8673. queryFn: api.getMaintenanceOverview,
  8674. staleTime: 60 * 1000, // 1 minute
  8675. });
  8676. // Live AI failure detection state for the card badges (#1546). Matches the
  8677. // 10s refetch of the Failure Detection settings panel.
  8678. const { data: obicoPrinterStatus } = useQuery({
  8679. queryKey: ['obico-printer-status'],
  8680. queryFn: api.getObicoPrinterStatus,
  8681. refetchInterval: 10000,
  8682. });
  8683. // Badge visibility: detection enabled AND this printer in the monitored set
  8684. // (monitored_printers null = all). Live per-print state is passed separately.
  8685. const isAiMonitored = useCallback(
  8686. (printerId: number) =>
  8687. obicoPrinterStatus?.enabled === true &&
  8688. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8689. [obicoPrinterStatus],
  8690. );
  8691. // Fetch Spoolman status to enable link spool feature
  8692. const { data: spoolmanStatus } = useQuery({
  8693. queryKey: ['spoolman-status'],
  8694. queryFn: api.getSpoolmanStatus,
  8695. staleTime: 60 * 1000, // 1 minute
  8696. });
  8697. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8698. // Fetch Spoolman settings to get sync mode
  8699. const { data: spoolmanSettings } = useQuery({
  8700. queryKey: ['spoolman-settings'],
  8701. queryFn: api.getSpoolmanSettings,
  8702. enabled: !!spoolmanEnabled,
  8703. staleTime: 60 * 1000, // 1 minute
  8704. });
  8705. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8706. // Fetch unlinked spools to know if link button should be enabled
  8707. const { data: unlinkedSpools } = useQuery({
  8708. queryKey: ['unlinked-spools'],
  8709. queryFn: api.getUnlinkedSpools,
  8710. enabled: !!spoolmanEnabled,
  8711. staleTime: 30 * 1000, // 30 seconds
  8712. });
  8713. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8714. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8715. const { data: linkedSpoolsData } = useQuery({
  8716. queryKey: ['linked-spools'],
  8717. queryFn: api.getLinkedSpools,
  8718. enabled: !!spoolmanEnabled,
  8719. staleTime: 30 * 1000, // 30 seconds
  8720. });
  8721. const linkedSpools = linkedSpoolsData?.linked;
  8722. // Fetch spool assignments for inventory feature
  8723. const { data: spoolAssignments } = useQuery({
  8724. queryKey: ['spool-assignments'],
  8725. queryFn: () => api.getAssignments(),
  8726. enabled: hasPermission('inventory:view_assignments'),
  8727. staleTime: 30 * 1000,
  8728. });
  8729. const unassignMutation = useMutation({
  8730. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8731. api.unassignSpool(printerId, amsId, trayId),
  8732. onSuccess: () => {
  8733. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8734. },
  8735. // Called fire-and-forget from the card: without this a failure is silent
  8736. // and the spool simply stays assigned.
  8737. onError: (error: Error) => showToast(error.message || t('spoolman.unlinkFailed'), 'error'),
  8738. });
  8739. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8740. queryKey: ['spoolman-inventory-spools'],
  8741. queryFn: () => api.getSpoolmanInventorySpools(false),
  8742. enabled: !!spoolmanEnabled,
  8743. staleTime: 30 * 1000,
  8744. });
  8745. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8746. queryKey: ['spoolman-slot-assignments'],
  8747. queryFn: () => api.getSpoolmanSlotAssignments(),
  8748. enabled: !!spoolmanEnabled,
  8749. staleTime: 30 * 1000,
  8750. });
  8751. const unassignSpoolmanMutation = useMutation({
  8752. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8753. onSuccess: () => {
  8754. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8755. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8756. },
  8757. onError: (error: Error) => showToast(error.message || t('spoolman.unlinkFailed'), 'error'),
  8758. });
  8759. // Helper to find assignment for a specific slot
  8760. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8761. return spoolAssignments?.find(
  8762. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8763. );
  8764. };
  8765. // Create a map of printer_id -> maintenance info for quick lookup
  8766. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8767. (acc, overview) => {
  8768. acc[overview.printer_id] = {
  8769. due_count: overview.due_count,
  8770. warning_count: overview.warning_count,
  8771. total_print_hours: overview.total_print_hours,
  8772. };
  8773. return acc;
  8774. },
  8775. {} as Record<number, PrinterMaintenanceInfo>
  8776. ) || {};
  8777. // Create a map of printer_id -> smart plug
  8778. const smartPlugByPrinter = smartPlugs?.reduce(
  8779. (acc, plug) => {
  8780. if (plug.printer_id) {
  8781. acc[plug.printer_id] = plug;
  8782. }
  8783. return acc;
  8784. },
  8785. {} as Record<number, typeof smartPlugs[0]>
  8786. ) || {};
  8787. const addMutation = useMutation({
  8788. mutationFn: api.createPrinter,
  8789. onSuccess: () => {
  8790. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8791. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8792. setShowAddModal(false);
  8793. },
  8794. onError: (error: Error) => {
  8795. // Localized message when the backend returns a stable error code;
  8796. // the raw message is an English fallback for non-UI clients.
  8797. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8798. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8799. return;
  8800. }
  8801. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8802. },
  8803. });
  8804. const powerOnMutation = useMutation({
  8805. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8806. onSuccess: () => {
  8807. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8808. setPoweringOn(null);
  8809. },
  8810. onError: () => {
  8811. setPoweringOn(null);
  8812. },
  8813. });
  8814. // Bulk selection state
  8815. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8816. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8817. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8818. const [bulkActionPending, setBulkActionPending] = useState(false);
  8819. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8820. const toggleSelect = useCallback((id: number) => {
  8821. setSelectedPrinterIds(prev => {
  8822. const next = new Set(prev);
  8823. if (next.has(id)) next.delete(id);
  8824. else next.add(id);
  8825. return next;
  8826. });
  8827. }, []);
  8828. const clearSelection = useCallback(() => {
  8829. setSelectedPrinterIds(new Set());
  8830. setIsSelectionMode(false);
  8831. }, []);
  8832. // Escape key exits selection mode
  8833. useEffect(() => {
  8834. const handleKeyDown = (e: KeyboardEvent) => {
  8835. if (e.key === 'Escape' && selectionMode) {
  8836. clearSelection();
  8837. }
  8838. };
  8839. window.addEventListener('keydown', handleKeyDown);
  8840. return () => window.removeEventListener('keydown', handleKeyDown);
  8841. }, [selectionMode, clearSelection]);
  8842. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8843. setBulkActionPending(true);
  8844. const ids = Array.from(selectedPrinterIds);
  8845. // Filter to only applicable printers based on cached state
  8846. const applicableIds = ids.filter(id => {
  8847. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8848. // clearPlate is checked before the connection filter: it only releases a
  8849. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8850. // down — every other action here needs to reach the machine (#2864).
  8851. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8852. if (!status?.connected) return false;
  8853. switch (action) {
  8854. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8855. case 'pause': return status.state === 'RUNNING';
  8856. case 'resume': return status.state === 'PAUSE';
  8857. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8858. default: return false;
  8859. }
  8860. });
  8861. if (applicableIds.length === 0) {
  8862. showToast(t('printers.bulk.noneApplicable'), 'error');
  8863. setBulkActionPending(false);
  8864. setBulkConfirmAction(null);
  8865. return;
  8866. }
  8867. const apiCall = {
  8868. stop: api.stopPrint,
  8869. pause: api.pausePrint,
  8870. resume: api.resumePrint,
  8871. clearPlate: api.clearPlate,
  8872. clearHMS: api.clearHMSErrors,
  8873. }[action];
  8874. const results = await Promise.allSettled(
  8875. applicableIds.map(id => apiCall(id))
  8876. );
  8877. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8878. const failed = results.filter(r => r.status === 'rejected').length;
  8879. if (failed === 0) {
  8880. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8881. } else {
  8882. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8883. }
  8884. // Invalidate status queries for affected printers
  8885. applicableIds.forEach(id => {
  8886. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8887. });
  8888. setBulkActionPending(false);
  8889. setBulkConfirmAction(null);
  8890. }, [selectedPrinterIds, queryClient, showToast, t]);
  8891. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8892. // Actions that need confirmation
  8893. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8894. setBulkConfirmAction(action);
  8895. } else {
  8896. executeBulkAction(action);
  8897. }
  8898. }, [executeBulkAction]);
  8899. const toggleHideDisconnected = () => {
  8900. const newValue = !hideDisconnected;
  8901. setHideDisconnected(newValue);
  8902. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8903. };
  8904. const handleSortChange = (newSort: SortOption) => {
  8905. setSortBy(newSort);
  8906. localStorage.setItem('printerSortBy', newSort);
  8907. };
  8908. const handleStatusFilterChange = (value: string) => {
  8909. setStatusFilter(value);
  8910. localStorage.setItem('printerStatusFilter', value);
  8911. };
  8912. const handleLocationFilterChange = (value: string) => {
  8913. setLocationFilter(value);
  8914. localStorage.setItem('printerLocationFilter', value);
  8915. };
  8916. const toggleSortDirection = () => {
  8917. const newAsc = !sortAsc;
  8918. setSortAsc(newAsc);
  8919. localStorage.setItem('printerSortAsc', String(newAsc));
  8920. };
  8921. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8922. const getGridClasses = () => {
  8923. switch (cardSize) {
  8924. 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
  8925. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8926. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8927. case 4: return 'grid-cols-1'; // XL: single column, full width
  8928. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8929. }
  8930. };
  8931. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8932. // Increment version counter whenever a printer status cache entry is updated so
  8933. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8934. useEffect(() => {
  8935. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8936. if (
  8937. event.type === 'updated' &&
  8938. Array.isArray(event.query.queryKey) &&
  8939. event.query.queryKey[0] === 'printerStatus'
  8940. ) {
  8941. setStatusCacheVersion(v => v + 1);
  8942. }
  8943. });
  8944. return unsubscribe;
  8945. }, [queryClient]);
  8946. // Filter printers by search term, status, and location
  8947. const filteredPrinters = useMemo(() => {
  8948. if (!printers) return [];
  8949. let result = printers;
  8950. // Text search
  8951. if (search.trim()) {
  8952. const q = search.trim().toLowerCase();
  8953. result = result.filter(p =>
  8954. p.name.toLowerCase().includes(q) ||
  8955. (p.model || '').toLowerCase().includes(q) ||
  8956. (p.location || '').toLowerCase().includes(q) ||
  8957. (p.serial_number || '').toLowerCase().includes(q)
  8958. );
  8959. }
  8960. // Location filter
  8961. if (locationFilter !== 'all') {
  8962. result = result.filter(p => (p.location || '') === locationFilter);
  8963. }
  8964. // Status filter
  8965. if (statusFilter !== 'all') {
  8966. result = result.filter(p => {
  8967. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8968. if (!status?.connected) return statusFilter === 'offline';
  8969. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8970. switch (statusFilter) {
  8971. case 'printing': return status.state === 'RUNNING';
  8972. case 'paused': return status.state === 'PAUSE';
  8973. case 'finished': return status.state === 'FINISH';
  8974. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8975. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8976. case 'offline': return false; // Connected printers are never offline
  8977. default: return true;
  8978. }
  8979. });
  8980. }
  8981. return result;
  8982. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8983. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8984. // Derive unique locations for the location filter dropdown
  8985. const availableLocations = useMemo(() => {
  8986. if (!printers) return [];
  8987. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8988. }, [printers]);
  8989. // A saved location can outlive what it matched -- renamed, cleared, or the
  8990. // only printer that had it deleted. The dropdown is rendered only while some
  8991. // printer has a location, so a stale one would hide every printer *and* the
  8992. // control to undo it, leaving an empty page and no way back (#2833).
  8993. // Deliberately waits for `printers`: it is undefined while the query is in
  8994. // flight, and acting on the empty list that produces would throw the saved
  8995. // filter away every time the page loads.
  8996. useEffect(() => {
  8997. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8998. setLocationFilter('all');
  8999. localStorage.setItem('printerLocationFilter', 'all');
  9000. }, [printers, availableLocations, locationFilter]);
  9001. // Sort printers based on selected option
  9002. const sortedPrinters = useMemo(() => {
  9003. const sorted = [...filteredPrinters];
  9004. switch (sortBy) {
  9005. case 'name':
  9006. sorted.sort((a, b) => a.name.localeCompare(b.name));
  9007. break;
  9008. case 'model':
  9009. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  9010. break;
  9011. case 'location':
  9012. // Sort by location, with ungrouped printers last
  9013. sorted.sort((a, b) => {
  9014. const locA = a.location || '';
  9015. const locB = b.location || '';
  9016. if (!locA && locB) return 1;
  9017. if (locA && !locB) return -1;
  9018. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  9019. });
  9020. break;
  9021. case 'status':
  9022. // Sort by status: HMS errors > printing > idle > offline
  9023. sorted.sort((a, b) => {
  9024. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  9025. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  9026. const getPriority = (s: typeof statusA) => {
  9027. if (!s?.connected) return 3; // offline
  9028. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  9029. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  9030. if (s.state === 'RUNNING') return 1; // printing
  9031. return 2; // idle
  9032. };
  9033. return getPriority(statusA) - getPriority(statusB);
  9034. });
  9035. break;
  9036. case 'eta':
  9037. sorted.sort((a, b) => {
  9038. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  9039. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  9040. const tier = (s: typeof statusA) => {
  9041. if (!s?.connected) return 3; // offline last
  9042. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  9043. if (s.state === 'RUNNING') return 1; // printing without ETA
  9044. return 2; // idle
  9045. };
  9046. const ta = tier(statusA);
  9047. const tb = tier(statusB);
  9048. if (ta !== tb) return ta - tb;
  9049. if (ta === 0) {
  9050. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  9051. if (diff !== 0) return diff;
  9052. }
  9053. return a.name.localeCompare(b.name);
  9054. });
  9055. break;
  9056. }
  9057. // Apply ascending/descending
  9058. if (!sortAsc) {
  9059. sorted.reverse();
  9060. }
  9061. return sorted;
  9062. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  9063. const selectAll = useCallback(() => {
  9064. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  9065. setIsSelectionMode(true);
  9066. }, [sortedPrinters]);
  9067. const selectByState = useCallback((state: PrinterState) => {
  9068. setSelectedPrinterIds(prev => {
  9069. const next = new Set(prev);
  9070. sortedPrinters.forEach(p => {
  9071. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  9072. if (classifyPrinterStatus(status) === state) next.add(p.id);
  9073. });
  9074. return next;
  9075. });
  9076. setIsSelectionMode(true);
  9077. }, [sortedPrinters, queryClient]);
  9078. const selectByLocation = useCallback((location: string) => {
  9079. setSelectedPrinterIds(prev => {
  9080. const next = new Set(prev);
  9081. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9082. return next;
  9083. });
  9084. setIsSelectionMode(true);
  9085. }, [sortedPrinters]);
  9086. const selectByModel = useCallback((model: string) => {
  9087. setSelectedPrinterIds(prev => {
  9088. const next = new Set(prev);
  9089. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9090. return next;
  9091. });
  9092. setIsSelectionMode(true);
  9093. }, [sortedPrinters]);
  9094. const toggleSectionCollapse = useCallback((key: string) => {
  9095. setCollapsedSections(prev => {
  9096. const next = { ...prev, [key]: !prev[key] };
  9097. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9098. return next;
  9099. });
  9100. }, []);
  9101. // Group printers when sorted by location, status, or model
  9102. const groupedPrinters = useMemo(() => {
  9103. if (sortBy === 'name' || sortBy === 'eta') return null;
  9104. const groups: Record<string, typeof sortedPrinters> = {};
  9105. if (sortBy === 'location') {
  9106. sortedPrinters.forEach(printer => {
  9107. const location = printer.location || 'Ungrouped';
  9108. if (!groups[location]) groups[location] = [];
  9109. groups[location].push(printer);
  9110. });
  9111. } else if (sortBy === 'model') {
  9112. sortedPrinters.forEach(printer => {
  9113. const model = printer.model || 'Unknown';
  9114. if (!groups[model]) groups[model] = [];
  9115. groups[model].push(printer);
  9116. });
  9117. } else if (sortBy === 'status') {
  9118. sortedPrinters.forEach(printer => {
  9119. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9120. const group = classifyPrinterStatus(status);
  9121. if (!groups[group]) groups[group] = [];
  9122. groups[group].push(printer);
  9123. });
  9124. }
  9125. return groups;
  9126. // 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
  9127. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9128. const toolbarRef = useRef<HTMLDivElement>(null);
  9129. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9130. const expandedToolbarWidthRef = useRef(0);
  9131. const [compactToolbar, setCompactToolbar] = useState(false);
  9132. const measureToolbar = useCallback(() => {
  9133. const toolbar = toolbarRef.current;
  9134. if (!toolbar) return;
  9135. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9136. if (measuredControlsWidth) {
  9137. expandedToolbarWidthRef.current = measuredControlsWidth;
  9138. }
  9139. const searchMinimumWidth = 220;
  9140. const gapWidth = 8;
  9141. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9142. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9143. }, []);
  9144. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9145. useLayoutEffect(() => {
  9146. measureToolbar();
  9147. const toolbar = toolbarRef.current;
  9148. if (!toolbar) return;
  9149. if (typeof ResizeObserver === 'undefined') {
  9150. window.addEventListener('resize', measureToolbar);
  9151. return () => window.removeEventListener('resize', measureToolbar);
  9152. }
  9153. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9154. resizeObserver.observe(toolbar);
  9155. window.addEventListener('resize', measureToolbar);
  9156. return () => {
  9157. resizeObserver.disconnect();
  9158. window.removeEventListener('resize', measureToolbar);
  9159. };
  9160. }, [
  9161. measureToolbar,
  9162. printers?.length,
  9163. availableLocations.length,
  9164. hideDisconnected,
  9165. smartPlugCount,
  9166. ]);
  9167. const renderFilterControls = (inMenu = false) => (
  9168. <>
  9169. {/* Status filter */}
  9170. {printers && printers.length > 0 && (
  9171. <ToolbarDropdown
  9172. value={statusFilter}
  9173. onChange={handleStatusFilterChange}
  9174. fullWidth={inMenu}
  9175. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9176. />
  9177. )}
  9178. {/* Location filter — only shown when at least one printer has a location */}
  9179. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9180. <ToolbarDropdown
  9181. value={locationFilter}
  9182. onChange={handleLocationFilterChange}
  9183. fullWidth={inMenu}
  9184. options={[
  9185. { value: 'all', label: t('printers.filter.allLocations') },
  9186. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9187. ]}
  9188. />
  9189. )}
  9190. <button
  9191. type="button"
  9192. onClick={toggleHideDisconnected}
  9193. aria-pressed={hideDisconnected}
  9194. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9195. hideDisconnected
  9196. ? 'bg-bambu-green border-bambu-green text-white'
  9197. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9198. }`}
  9199. >
  9200. {t('printers.hideOffline')}
  9201. </button>
  9202. </>
  9203. );
  9204. const renderViewControls = (inMenu = false) => (
  9205. <>
  9206. {/* Sort dropdown */}
  9207. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9208. <ToolbarDropdown<SortOption>
  9209. value={sortBy}
  9210. onChange={handleSortChange}
  9211. fullWidth={inMenu}
  9212. options={[
  9213. { value: 'name', label: t('printers.sort.name') },
  9214. { value: 'status', label: t('printers.sort.status') },
  9215. { value: 'model', label: t('printers.sort.model') },
  9216. { value: 'location', label: t('printers.sort.location') },
  9217. { value: 'eta', label: t('printers.sort.eta') },
  9218. ]}
  9219. />
  9220. <button
  9221. onClick={toggleSortDirection}
  9222. 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"
  9223. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9224. >
  9225. {sortAsc ? (
  9226. <ArrowUp className="w-4 h-4 text-white" />
  9227. ) : (
  9228. <ArrowDown className="w-4 h-4 text-white" />
  9229. )}
  9230. </button>
  9231. <RouterLink
  9232. to="/printer-locations"
  9233. 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"
  9234. title={t('printers.locations.title')}
  9235. aria-label={t('printers.locations.title')}
  9236. >
  9237. <Box className="w-4 h-4 text-bambu-green" />
  9238. </RouterLink>
  9239. </div>
  9240. {/* Page view toggle: Cards / Cam Wall */}
  9241. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9242. <button
  9243. type="button"
  9244. onClick={() => {
  9245. setPageView('cards');
  9246. localStorage.setItem('printerPageView', 'cards');
  9247. }}
  9248. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9249. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9250. }`}
  9251. title={t('printers.pageView.cards')}
  9252. aria-pressed={pageView === 'cards'}
  9253. >
  9254. <LayoutGrid className="w-3.5 h-3.5" />
  9255. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9256. </button>
  9257. <button
  9258. type="button"
  9259. onClick={() => {
  9260. setPageView('camwall');
  9261. localStorage.setItem('printerPageView', 'camwall');
  9262. }}
  9263. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9264. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9265. }`}
  9266. title={t('printers.pageView.camWall')}
  9267. aria-pressed={pageView === 'camwall'}
  9268. disabled={!hasPermission('camera:view')}
  9269. >
  9270. <MonitorPlay className="w-3.5 h-3.5" />
  9271. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9272. </button>
  9273. </div>
  9274. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9275. view, and the page a kiosk token points at. Only offered once the wall
  9276. is the active view, so it doesn't compete with the toggle above. */}
  9277. {pageView === 'camwall' && hasPermission('camera:view') && (
  9278. <RouterLink
  9279. to="/camwall"
  9280. 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' : ''}`}
  9281. title={t('printers.pageView.openCamWallPage')}
  9282. >
  9283. <ExternalLink className="w-3.5 h-3.5" />
  9284. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9285. </RouterLink>
  9286. )}
  9287. {/* Card size selector */}
  9288. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9289. {cardSizeLabels.map((label, index) => {
  9290. const size = index + 1;
  9291. const isSelected = (pageView === 'camwall' ? camWallTileSize : cardSize) === size;
  9292. return (
  9293. <button
  9294. key={label}
  9295. onClick={() => {
  9296. if (pageView === 'camwall') {
  9297. setCamWallTileSize(size);
  9298. localStorage.setItem('camWallTileSize', String(size));
  9299. return;
  9300. }
  9301. setCompactDrilldownPrinterId(null);
  9302. setCardSize(size);
  9303. localStorage.setItem('printerCardSize', String(size));
  9304. }}
  9305. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9306. index === 0 ? 'rounded-l-lg' : ''
  9307. } ${
  9308. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9309. } ${
  9310. isSelected
  9311. ? 'bg-bambu-green text-white'
  9312. : 'text-white hover:bg-bambu-dark-tertiary'
  9313. }`}
  9314. title={t(`printers.${pageView === 'camwall' ? 'camWall.tileSize' : 'cardSize'}.${['small', 'medium', 'large', 'extraLarge'][index]}`)}
  9315. >
  9316. {label}
  9317. </button>
  9318. );
  9319. })}
  9320. </div>
  9321. </>
  9322. );
  9323. const renderActionControls = (inMenu = false) => (
  9324. <>
  9325. {/* Bulk select toggle */}
  9326. <button
  9327. onClick={() => {
  9328. if (selectionMode) clearSelection();
  9329. else setIsSelectionMode(true);
  9330. }}
  9331. 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' : ''} ${
  9332. selectionMode
  9333. ? 'bg-bambu-green border-bambu-green text-white'
  9334. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9335. }`}
  9336. title={t('printers.bulk.select')}
  9337. disabled={!hasPermission('printers:control')}
  9338. >
  9339. <CheckSquare className="w-4 h-4" />
  9340. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9341. </button>
  9342. {/* Power dropdown for offline printers with smart plugs */}
  9343. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9344. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9345. <button
  9346. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9347. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9348. inMenu
  9349. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9350. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9351. }`}
  9352. >
  9353. <span className="flex items-center gap-1.5">
  9354. <Power className="w-4 h-4" />
  9355. {t('printers.powerOn')}
  9356. </span>
  9357. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9358. </button>
  9359. {showPowerDropdown && (
  9360. <>
  9361. {/* Backdrop to close dropdown */}
  9362. <div
  9363. className="fixed inset-0 z-10"
  9364. onClick={() => setShowPowerDropdown(false)}
  9365. />
  9366. <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">
  9367. <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">
  9368. {t('printers.offlinePrintersWithPlugs')}
  9369. </div>
  9370. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9371. <PowerDropdownItem
  9372. key={printer.id}
  9373. printer={printer}
  9374. plug={smartPlugByPrinter[printer.id]}
  9375. onPowerOn={(plugId) => {
  9376. setPoweringOn(plugId);
  9377. powerOnMutation.mutate(plugId);
  9378. }}
  9379. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9380. />
  9381. ))}
  9382. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9383. <div className="px-3 py-2 text-sm text-bambu-gray">
  9384. No printers with smart plugs
  9385. </div>
  9386. )}
  9387. </div>
  9388. </>
  9389. )}
  9390. </div>
  9391. )}
  9392. <Button
  9393. onClick={() => setShowAddModal(true)}
  9394. disabled={!hasPermission('printers:create')}
  9395. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9396. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9397. >
  9398. <Plus className="w-4 h-4" />
  9399. {t('printers.addPrinter')}
  9400. </Button>
  9401. </>
  9402. );
  9403. return (
  9404. <div className="p-4 md:p-8">
  9405. <div className="space-y-3 mb-6">
  9406. <div>
  9407. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9408. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9409. {t('printers.title')}
  9410. </h1>
  9411. <StatusSummaryBar printers={printers} />
  9412. </div>
  9413. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9414. {/* Only show search bar when printers exist */}
  9415. {printers && printers.length > 0 && (
  9416. <div className="relative min-w-0 flex-1">
  9417. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9418. <input
  9419. type="search"
  9420. name="printer-search"
  9421. autoComplete="off"
  9422. data-1p-ignore
  9423. data-lpignore="true"
  9424. value={search}
  9425. onChange={(e) => setSearch(e.target.value)}
  9426. placeholder={t('printers.search')}
  9427. aria-label={t('printers.search')}
  9428. 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"
  9429. />
  9430. {search && (
  9431. <button
  9432. type="button"
  9433. aria-label={t('common.clear')}
  9434. onClick={() => setSearch('')}
  9435. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9436. >
  9437. <X className="w-4 h-4" />
  9438. </button>
  9439. )}
  9440. </div>
  9441. )}
  9442. <div
  9443. ref={expandedToolbarControlsRef}
  9444. aria-hidden={compactToolbar}
  9445. inert={compactToolbar}
  9446. 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`}
  9447. >
  9448. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9449. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9450. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9451. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9452. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9453. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9454. </div>
  9455. {compactToolbar && (
  9456. <div className="ml-auto flex items-center justify-end gap-1">
  9457. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9458. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9459. </ToolbarMenu>
  9460. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9461. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9462. </ToolbarMenu>
  9463. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9464. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9465. </ToolbarMenu>
  9466. </div>
  9467. )}
  9468. </div>
  9469. </div>
  9470. {isLoading ? (
  9471. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9472. ) : printers?.length === 0 ? (
  9473. <Card>
  9474. <CardContent className="text-center py-12">
  9475. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9476. <Button
  9477. onClick={() => setShowAddModal(true)}
  9478. disabled={!hasPermission('printers:create')}
  9479. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9480. >
  9481. <Plus className="w-4 h-4" />
  9482. {t('printers.addPrinter')}
  9483. </Button>
  9484. </CardContent>
  9485. </Card>
  9486. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9487. <Card>
  9488. <CardContent className="text-center py-12">
  9489. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9490. </CardContent>
  9491. </Card>
  9492. ) : pageView === 'camwall' ? (
  9493. <CameraWall
  9494. printers={sortedPrinters}
  9495. maxLive={camWallMaxLive}
  9496. snapshotIntervalSec={camWallSnapshotSec}
  9497. tileSize={camWallTileSize}
  9498. onTileClick={(id, name) => {
  9499. // A wall tile has no room for a split button, so it follows the
  9500. // mode the card buttons last chose.
  9501. if (cameraViewMode === 'embedded') {
  9502. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9503. } else {
  9504. openCameraWindow(id);
  9505. }
  9506. }}
  9507. statusMode={camWallStatusMode}
  9508. onChangeMaxLive={(next) => {
  9509. setCamWallMaxLive(next);
  9510. localStorage.setItem('camWallMaxLive', String(next));
  9511. }}
  9512. onChangeSnapshotIntervalSec={(next) => {
  9513. setCamWallSnapshotSec(next);
  9514. localStorage.setItem('camWallSnapshotSec', String(next));
  9515. }}
  9516. onChangeStatusMode={(next) => {
  9517. setCamWallStatusMode(next);
  9518. localStorage.setItem('camWallStatusMode', next);
  9519. }}
  9520. />
  9521. ) : groupedPrinters ? (
  9522. /* Grouped view (location, status, or model) */
  9523. <div className="space-y-6">
  9524. {(() => {
  9525. const keys = sortBy === 'status'
  9526. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9527. : Object.keys(groupedPrinters);
  9528. // For status grouping, asc/desc flips the fixed priority order
  9529. // (asc = error→offline, desc = offline→error). This matches the
  9530. // sort-toggle behaviour for other groupings.
  9531. return (sortAsc ? keys : [...keys].reverse());
  9532. })().map((groupKey) => {
  9533. const groupPrinters = groupedPrinters[groupKey];
  9534. const collapseKey = `${sortBy}:${groupKey}`;
  9535. const isOpen = !collapsedSections[collapseKey];
  9536. const dot = sortBy === 'status'
  9537. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9538. : 'bg-bambu-green';
  9539. const label = sortBy === 'status'
  9540. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9541. : groupKey;
  9542. return (
  9543. <Collapsible
  9544. key={groupKey}
  9545. open={isOpen}
  9546. onToggle={() => toggleSectionCollapse(collapseKey)}
  9547. summaryClassName="py-1"
  9548. summary={
  9549. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9550. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9551. {label}
  9552. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9553. {selectionMode && (
  9554. <button
  9555. onClick={(e) => {
  9556. e.stopPropagation();
  9557. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9558. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9559. else if (sortBy === 'model') selectByModel(groupKey);
  9560. }}
  9561. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9562. >
  9563. {t('printers.bulk.selectAll')}
  9564. </button>
  9565. )}
  9566. </h2>
  9567. }
  9568. >
  9569. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9570. {groupPrinters.map((printer) => (
  9571. <PrinterCard
  9572. key={printer.id}
  9573. printer={printer}
  9574. hideIfDisconnected={hideDisconnected}
  9575. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9576. viewMode={viewMode}
  9577. cardSize={cardSize}
  9578. amsThresholds={settings ? {
  9579. humidityGood: Number(settings.ams_humidity_good) || 40,
  9580. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9581. tempGood: Number(settings.ams_temp_good) || 28,
  9582. tempFair: Number(settings.ams_temp_fair) || 35,
  9583. } : undefined}
  9584. spoolmanEnabled={spoolmanEnabled}
  9585. hasUnlinkedSpools={hasUnlinkedSpools}
  9586. linkedSpools={linkedSpools}
  9587. spoolmanUrl={spoolmanStatus?.url}
  9588. spoolmanSyncMode={spoolmanSyncMode}
  9589. onGetAssignment={getAssignment}
  9590. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9591. spoolmanSpools={spoolmanSpools}
  9592. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9593. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9594. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9595. timeFormat={settings?.time_format || 'system'}
  9596. cameraViewMode={cameraViewMode}
  9597. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9598. onSelectCameraViewMode={selectCameraViewMode}
  9599. checkPrinterFirmware={firmwareChecksOn}
  9600. dryingPresets={effectiveDryingPresets}
  9601. nozzleTempPresets={effectiveNozzleTempPresets}
  9602. bedTempPresets={effectiveBedTempPresets}
  9603. chamberTempPresets={effectiveChamberTempPresets}
  9604. fanSpeedPresets={effectiveFanSpeedPresets}
  9605. requirePlateClear={settings?.require_plate_clear === true}
  9606. selectionMode={selectionMode}
  9607. isSelected={selectedPrinterIds.has(printer.id)}
  9608. onToggleSelect={toggleSelect}
  9609. onOpenCompactCard={openCompactCard}
  9610. aiDetectionEnabled={isAiMonitored(printer.id)}
  9611. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9612. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9613. />
  9614. ))}
  9615. </div>
  9616. </Collapsible>
  9617. );
  9618. })}
  9619. </div>
  9620. ) : (
  9621. /* Regular grid view */
  9622. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9623. {sortedPrinters.map((printer) => (
  9624. <PrinterCard
  9625. key={printer.id}
  9626. printer={printer}
  9627. hideIfDisconnected={hideDisconnected}
  9628. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9629. viewMode={viewMode}
  9630. cardSize={cardSize}
  9631. spoolmanEnabled={spoolmanEnabled}
  9632. hasUnlinkedSpools={hasUnlinkedSpools}
  9633. linkedSpools={linkedSpools}
  9634. spoolmanUrl={spoolmanStatus?.url}
  9635. spoolmanSyncMode={spoolmanSyncMode}
  9636. onGetAssignment={getAssignment}
  9637. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9638. spoolmanSpools={spoolmanSpools}
  9639. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9640. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9641. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9642. amsThresholds={settings ? {
  9643. humidityGood: Number(settings.ams_humidity_good) || 40,
  9644. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9645. tempGood: Number(settings.ams_temp_good) || 28,
  9646. tempFair: Number(settings.ams_temp_fair) || 35,
  9647. } : undefined}
  9648. timeFormat={settings?.time_format || 'system'}
  9649. cameraViewMode={cameraViewMode}
  9650. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9651. onSelectCameraViewMode={selectCameraViewMode}
  9652. checkPrinterFirmware={firmwareChecksOn}
  9653. dryingPresets={effectiveDryingPresets}
  9654. nozzleTempPresets={effectiveNozzleTempPresets}
  9655. bedTempPresets={effectiveBedTempPresets}
  9656. chamberTempPresets={effectiveChamberTempPresets}
  9657. fanSpeedPresets={effectiveFanSpeedPresets}
  9658. requirePlateClear={settings?.require_plate_clear === true}
  9659. selectionMode={selectionMode}
  9660. isSelected={selectedPrinterIds.has(printer.id)}
  9661. onToggleSelect={toggleSelect}
  9662. onOpenCompactCard={openCompactCard}
  9663. aiDetectionEnabled={isAiMonitored(printer.id)}
  9664. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9665. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9666. />
  9667. ))}
  9668. </div>
  9669. )}
  9670. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9671. <button
  9672. type="button"
  9673. onClick={returnToCompactCards}
  9674. 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}`}
  9675. title={t('common.back', 'Back')}
  9676. >
  9677. <ArrowLeft className="w-4 h-4" />
  9678. {t('common.back', 'Back')}
  9679. </button>
  9680. )}
  9681. {showAddModal && (
  9682. <AddPrinterModal
  9683. onClose={() => setShowAddModal(false)}
  9684. onAdd={(data) => addMutation.mutate(data)}
  9685. existingSerials={printers?.map(p => p.serial_number) || []}
  9686. />
  9687. )}
  9688. {/* Bulk selection toolbar */}
  9689. {selectionMode && printers && (
  9690. <BulkPrinterToolbar
  9691. selectedIds={selectedPrinterIds}
  9692. printers={printers}
  9693. onClose={clearSelection}
  9694. onSelectAll={selectAll}
  9695. onSelectByLocation={selectByLocation}
  9696. onSelectByState={selectByState}
  9697. onAction={handleBulkAction}
  9698. actionPending={bulkActionPending}
  9699. />
  9700. )}
  9701. {/* Bulk action confirmation modals */}
  9702. {bulkConfirmAction === 'stop' && (
  9703. <ConfirmModal
  9704. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9705. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9706. confirmText={t('printers.bulk.confirm.stopButton')}
  9707. variant="danger"
  9708. isLoading={bulkActionPending}
  9709. onConfirm={() => executeBulkAction('stop')}
  9710. onCancel={() => setBulkConfirmAction(null)}
  9711. />
  9712. )}
  9713. {bulkConfirmAction === 'pause' && (
  9714. <ConfirmModal
  9715. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9716. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9717. confirmText={t('printers.bulk.confirm.pauseButton')}
  9718. isLoading={bulkActionPending}
  9719. onConfirm={() => executeBulkAction('pause')}
  9720. onCancel={() => setBulkConfirmAction(null)}
  9721. />
  9722. )}
  9723. {bulkConfirmAction === 'clearPlate' && (
  9724. <ConfirmModal
  9725. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9726. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9727. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9728. isLoading={bulkActionPending}
  9729. onConfirm={() => executeBulkAction('clearPlate')}
  9730. onCancel={() => setBulkConfirmAction(null)}
  9731. />
  9732. )}
  9733. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9734. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9735. <EmbeddedCameraViewer
  9736. key={camera.id}
  9737. printerId={camera.id}
  9738. printerName={camera.name}
  9739. viewerIndex={index}
  9740. onClose={() => setEmbeddedCameraPrinters(prev => {
  9741. const next = new Map(prev);
  9742. next.delete(camera.id);
  9743. return next;
  9744. })}
  9745. />
  9746. ))}
  9747. </div>
  9748. );
  9749. }