PrintersPage.tsx 500 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216
  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 { getAmsLabel, getEmptySlotKind, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  193. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  194. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  195. import { Collapsible } from '../components/Collapsible';
  196. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  197. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  198. import { NumberInput } from '../components/NumberInput';
  199. import { getCurrencySymbol } from '../utils/currency';
  200. // The status filter's options, and the only values it may hold. One list so a
  201. // saved filter cannot be validated against a set the dropdown has since moved
  202. // on from (#2833). Labels stay literal so they remain greppable.
  203. const STATUS_FILTER_OPTIONS = [
  204. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  205. { value: 'printing', labelKey: 'printers.status.printing' },
  206. { value: 'paused', labelKey: 'printers.status.paused' },
  207. { value: 'idle', labelKey: 'printers.status.idle' },
  208. { value: 'finished', labelKey: 'printers.status.finished' },
  209. { value: 'error', labelKey: 'printers.status.error' },
  210. { value: 'offline', labelKey: 'printers.status.offline' },
  211. ] as const;
  212. function isKnownStatusFilter(value: string | null): boolean {
  213. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  214. }
  215. export interface SpoolmanSlotAssignmentRow {
  216. printer_id: number;
  217. ams_id: number;
  218. tray_id: number;
  219. spoolman_spool_id: number;
  220. }
  221. // Color names resolve via getColorName() which reads the backend color_catalog
  222. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  223. // Format K value with 3 decimal places, default to 0.020 if null
  224. function formatKValue(k: number | null | undefined): string {
  225. const value = k ?? 0.020;
  226. return value.toFixed(3);
  227. }
  228. // K-profile value shown on the slot card itself (#2532) rather than only inside
  229. // the hover popup, the way BambuStudio shows it per slot.
  230. //
  231. // `k` arrives already gated on the slot being loaded; falsy means the printer
  232. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  233. // missing value, which is captioned inside the hover card but would read as a
  234. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  235. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  236. // reported 0 makes that expression evaluate to the number 0, and React renders
  237. // numbers, putting a bare "0" under the material name.
  238. //
  239. // `reserve` holds the row's height open on the slots without a value whenever
  240. // some other slot on the same card has one, so every fill bar stays on one line.
  241. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  242. const { t } = useTranslation();
  243. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  244. if (!k) {
  245. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  246. }
  247. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  248. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  249. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  250. // family per browser and so measured differently in Safari.
  251. return (
  252. <div className={className} title={t('ams.kFactor')}>
  253. {t('ams.kFactorShort')} {formatKValue(k)}
  254. </div>
  255. );
  256. }
  257. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  258. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  259. const { mode } = useTheme();
  260. const { t } = useTranslation();
  261. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  262. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  263. return (
  264. <span
  265. 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"
  266. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  267. title={side === 'L' ? t('common.left') : t('common.right')}
  268. >
  269. {side}
  270. </span>
  271. );
  272. }
  273. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  274. // deliberately a different colour, because it means something different: this
  275. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  276. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  277. const { mode } = useTheme();
  278. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  279. return (
  280. <span
  281. 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"
  282. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  283. title={title}
  284. >
  285. {FTS_INLET_SIDE[inlet]}
  286. </span>
  287. );
  288. }
  289. /**
  290. * Which side indicator, if any, belongs on an AMS card header.
  291. *
  292. * Three sources, in descending authority:
  293. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  294. * through the switch, so the inlet is the only meaningful label.
  295. * 2. A real extruder id from ams_extruder_map.
  296. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  297. * never reported a map. This one is only a guess, and it is suppressed
  298. * when a switch is installed: with an FTS every unit reports extruder
  299. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  300. * nothing but their unit numbers.
  301. */
  302. function amsSideBadge(
  303. amsId: number,
  304. amsExtruderMap: Record<string, number>,
  305. amsSwitchInlet: Record<string, 'A' | 'B'>,
  306. ftsInstalled: boolean
  307. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  308. const inlet = amsSwitchInlet[String(amsId)];
  309. if (inlet) return { kind: 'inlet', inlet };
  310. const mapped = amsExtruderMap[String(amsId)];
  311. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  312. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  313. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  314. return null;
  315. }
  316. // Expand nozzle type codes to material names
  317. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  318. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  319. function nozzleTypeName(type: string, t: (key: string) => string): string {
  320. if (!type) return '';
  321. // Full text names (from main nozzle info)
  322. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  323. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  324. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  325. // 4-char codes (e.g. "HS01"): last 2 digits = material
  326. if (type.length >= 4) {
  327. const material = type.slice(2, 4);
  328. if (material === '00') return t('printers.nozzleStainlessSteel');
  329. if (material === '01') return t('printers.nozzleHardenedSteel');
  330. if (material === '05') return t('printers.nozzleTungstenCarbide');
  331. }
  332. // 2-digit numeric codes
  333. if (type === '00') return t('printers.nozzleStainlessSteel');
  334. if (type === '01') return t('printers.nozzleHardenedSteel');
  335. if (type === '05') return t('printers.nozzleTungstenCarbide');
  336. // 2-char alpha codes: H prefix = hardened steel
  337. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  338. return type;
  339. }
  340. // Parse flow type from nozzle type code
  341. // HH = high flow, HS = standard/normal
  342. function nozzleFlowName(type: string, t: (key: string) => string): string {
  343. if (!type) return '';
  344. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  345. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  346. return '';
  347. }
  348. // Per-slot hover card for nozzle rack
  349. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  350. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  351. slot: import('../api/client').NozzleRackSlot;
  352. index: number;
  353. activeStatus?: boolean;
  354. filamentName?: string;
  355. children: React.ReactNode;
  356. }) {
  357. const { t } = useTranslation();
  358. const [isVisible, setIsVisible] = useState(false);
  359. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  360. const triggerRef = useRef<HTMLDivElement>(null);
  361. const cardRef = useRef<HTMLDivElement>(null);
  362. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  363. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  364. const isMounted = slot.stat === 1;
  365. useEffect(() => {
  366. if (isVisible && triggerRef.current && cardRef.current) {
  367. const triggerRect = triggerRef.current.getBoundingClientRect();
  368. const cardHeight = cardRef.current.offsetHeight;
  369. const headerHeight = 56;
  370. const spaceAbove = triggerRect.top - headerHeight;
  371. const spaceBelow = window.innerHeight - triggerRect.bottom;
  372. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  373. setPosition('bottom');
  374. } else {
  375. setPosition('top');
  376. }
  377. }
  378. }, [isVisible]);
  379. const handleMouseEnter = () => {
  380. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  381. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  382. };
  383. const handleMouseLeave = () => {
  384. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  385. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  386. };
  387. useEffect(() => {
  388. return () => {
  389. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  390. };
  391. }, []);
  392. const filamentCss = parseFilamentColor(slot.filament_color);
  393. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  394. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  395. return (
  396. <div
  397. ref={triggerRef}
  398. className="relative"
  399. onMouseEnter={handleMouseEnter}
  400. onMouseLeave={handleMouseLeave}
  401. >
  402. {children}
  403. {isVisible && (
  404. <div
  405. ref={cardRef}
  406. className={`
  407. absolute left-1/2 -translate-x-1/2 z-50
  408. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  409. animate-in fade-in-0 zoom-in-95 duration-150
  410. `}
  411. style={{ maxWidth: 'calc(100vw - 24px)' }}
  412. >
  413. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  414. {isEmpty ? (
  415. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  416. Slot {index + 1} — Empty
  417. </div>
  418. ) : (
  419. <div className="p-2.5 space-y-1.5">
  420. {/* Diameter */}
  421. <div className="flex items-center justify-between">
  422. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  423. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  424. </div>
  425. {/* Type */}
  426. {typeFull && (
  427. <div className="flex items-center justify-between">
  428. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  429. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  430. </div>
  431. )}
  432. {/* Flow (hide if empty) */}
  433. {flowFull && (
  434. <div className="flex items-center justify-between">
  435. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  436. <span className="text-xs text-white font-semibold">{flowFull}</span>
  437. </div>
  438. )}
  439. {/* Status badge */}
  440. <div className="flex items-center justify-between">
  441. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  442. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  443. activeStatus || isMounted
  444. ? 'bg-green-900/50 text-green-400'
  445. : 'bg-bambu-dark-tertiary text-bambu-gray'
  446. }`}>
  447. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  448. </span>
  449. </div>
  450. {/* Wear (hide if null) */}
  451. {slot.wear != null && (
  452. <div className="flex items-center justify-between">
  453. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  454. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  455. </div>
  456. )}
  457. {/* Max Temp (hide if 0) */}
  458. {slot.max_temp > 0 && (
  459. <div className="flex items-center justify-between">
  460. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  461. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  462. </div>
  463. )}
  464. {/* Serial (hide if empty) */}
  465. {slot.serial_number && (
  466. <div className="flex items-center justify-between">
  467. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  468. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  469. </div>
  470. )}
  471. {/* Filament: material type + color swatch (hide if no color) */}
  472. {(filamentCss || slot.filament_type) && (
  473. <div className="flex items-center justify-between">
  474. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  475. <div className="flex items-center gap-1">
  476. {filamentCss && (
  477. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  478. )}
  479. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  480. </div>
  481. </div>
  482. )}
  483. </div>
  484. )}
  485. </div>
  486. {/* Arrow pointer */}
  487. <div
  488. className={`
  489. absolute left-1/2 -translate-x-1/2 w-0 h-0
  490. border-l-[6px] border-l-transparent
  491. border-r-[6px] border-r-transparent
  492. ${position === 'top'
  493. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  494. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  495. `}
  496. />
  497. </div>
  498. )}
  499. </div>
  500. );
  501. }
  502. // Dual-nozzle hover card showing L and R nozzle details side by side
  503. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  504. leftSlot?: import('../api/client').NozzleRackSlot;
  505. rightSlot?: import('../api/client').NozzleRackSlot;
  506. activeNozzle: 'L' | 'R';
  507. filamentInfo?: Record<string, { name: string; k: number | null }>;
  508. children: React.ReactNode;
  509. }) {
  510. const { t } = useTranslation();
  511. const [isVisible, setIsVisible] = useState(false);
  512. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  513. const triggerRef = useRef<HTMLDivElement>(null);
  514. const cardRef = useRef<HTMLDivElement>(null);
  515. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  516. useEffect(() => {
  517. if (isVisible && triggerRef.current && cardRef.current) {
  518. const triggerRect = triggerRef.current.getBoundingClientRect();
  519. const cardHeight = cardRef.current.offsetHeight;
  520. const headerHeight = 56;
  521. const spaceAbove = triggerRect.top - headerHeight;
  522. const spaceBelow = window.innerHeight - triggerRect.bottom;
  523. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  524. setPosition('bottom');
  525. } else {
  526. setPosition('top');
  527. }
  528. }
  529. }, [isVisible]);
  530. const handleMouseEnter = () => {
  531. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  532. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  533. };
  534. const handleMouseLeave = () => {
  535. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  536. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  537. };
  538. useEffect(() => {
  539. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  540. }, []);
  541. if (!leftSlot && !rightSlot) return <>{children}</>;
  542. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  543. const isActive = activeNozzle === side;
  544. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  545. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  546. const filamentCss = parseFilamentColor(slot.filament_color);
  547. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  548. return (
  549. <div className="flex-1 space-y-1.5">
  550. <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'}`}>
  551. {side === 'L' ? t('common.left') : t('common.right')}
  552. </div>
  553. {slot.nozzle_diameter && (
  554. <div className="flex items-center justify-between">
  555. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  556. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  557. </div>
  558. )}
  559. {typeFull && (
  560. <div className="flex items-center justify-between">
  561. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  562. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  563. </div>
  564. )}
  565. {flowFull && (
  566. <div className="flex items-center justify-between">
  567. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  568. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  569. </div>
  570. )}
  571. <div className="flex items-center justify-between">
  572. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  573. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  574. isActive
  575. ? 'bg-green-900/50 text-green-400'
  576. : 'bg-bambu-dark-tertiary text-bambu-gray'
  577. }`}>
  578. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  579. </span>
  580. </div>
  581. {slot.wear != null && (
  582. <div className="flex items-center justify-between">
  583. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  584. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  585. </div>
  586. )}
  587. {/* Serial and max temp only available on the right (removable) nozzle */}
  588. {side === 'R' && slot.max_temp > 0 && (
  589. <div className="flex items-center justify-between">
  590. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  591. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  592. </div>
  593. )}
  594. {side === 'R' && slot.serial_number && (
  595. <div className="flex items-center justify-between">
  596. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  597. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  598. </div>
  599. )}
  600. {(filamentCss || slot.filament_type || slot.filament_id) && (
  601. <div className="flex items-center justify-between">
  602. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  603. <div className="flex items-center gap-1">
  604. {filamentCss && (
  605. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  606. )}
  607. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  608. {filamentName || slot.filament_type || slot.filament_id || ''}
  609. </span>
  610. </div>
  611. </div>
  612. )}
  613. </div>
  614. );
  615. };
  616. return (
  617. <div
  618. ref={triggerRef}
  619. className="relative flex-1"
  620. onMouseEnter={handleMouseEnter}
  621. onMouseLeave={handleMouseLeave}
  622. >
  623. {children}
  624. {isVisible && (
  625. <div
  626. ref={cardRef}
  627. className={`
  628. absolute left-1/2 -translate-x-1/2 z-50
  629. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  630. animate-in fade-in-0 zoom-in-95 duration-150
  631. `}
  632. style={{ maxWidth: 'calc(100vw - 24px)' }}
  633. >
  634. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  635. <div className="p-2.5 flex gap-3">
  636. {leftSlot && renderColumn(leftSlot, 'L')}
  637. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  638. {rightSlot && renderColumn(rightSlot, 'R')}
  639. </div>
  640. </div>
  641. {/* Arrow pointer */}
  642. <div
  643. className={`
  644. absolute left-1/2 -translate-x-1/2 w-0 h-0
  645. border-l-[6px] border-l-transparent
  646. border-r-[6px] border-r-transparent
  647. ${position === 'top'
  648. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  649. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  650. `}
  651. />
  652. </div>
  653. )}
  654. </div>
  655. );
  656. }
  657. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  658. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  659. const { t } = useTranslation();
  660. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  661. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  662. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  663. // base — computing it from min(present IDs) shifts everything left when slot 16
  664. // is the one currently mounted (#943).
  665. const rackNozzles = slots.filter(s => s.id >= 2);
  666. const RACK_SIZE = 6;
  667. const RACK_BASE_ID = 16;
  668. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  669. { length: RACK_SIZE },
  670. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  671. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  672. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  673. },
  674. );
  675. return (
  676. // Sized to its contents rather than growing: the six chips are a fixed
  677. // width at any one card size, so extra width would be dead space taken
  678. // from the temperature cards beside it — which are flex-1 with a 0 basis
  679. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  680. // stays enabled so the card still gives way on a narrow printer card
  681. // instead of overflowing.
  682. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  683. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  684. <div className="flex gap-[3px] justify-center">
  685. {rackSlots.map((slot, i) => {
  686. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  687. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  688. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  689. return (
  690. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  691. <div className="flex flex-col items-center gap-0.5">
  692. <div
  693. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  694. isEmpty
  695. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  696. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  697. }`}
  698. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  699. >
  700. <span
  701. data-rack-diameter
  702. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  703. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  704. >
  705. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  706. </span>
  707. </div>
  708. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  709. acted on without counting chips. Sits below the chip rather
  710. than inside it: the chip is barely wider than its own
  711. diameter text and already carries that over a
  712. filament-coloured background. */}
  713. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  714. {i + 1}
  715. </span>
  716. </div>
  717. </NozzleSlotHoverCard>
  718. );
  719. })}
  720. </div>
  721. </div>
  722. );
  723. }
  724. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  725. function WaterDropEmpty({ className }: { className?: string }) {
  726. return (
  727. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  728. <path d="M17.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"/>
  729. </svg>
  730. );
  731. }
  732. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  733. function WaterDropHalf({ className }: { className?: string }) {
  734. return (
  735. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  736. <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"/>
  737. <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"/>
  738. </svg>
  739. );
  740. }
  741. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  742. function WaterDropFull({ className }: { className?: string }) {
  743. return (
  744. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  745. <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"/>
  746. <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"/>
  747. </svg>
  748. );
  749. }
  750. // Thermometer SVG - empty outline
  751. function ThermometerEmpty({ className }: { className?: string }) {
  752. return (
  753. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  754. <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"/>
  755. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  756. </svg>
  757. );
  758. }
  759. // Thermometer SVG - half filled (gold - same as humidity fair)
  760. function ThermometerHalf({ className }: { className?: string }) {
  761. return (
  762. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  763. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  764. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  765. <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"/>
  766. </svg>
  767. );
  768. }
  769. // Thermometer SVG - fully filled (red - same as humidity bad)
  770. function ThermometerFull({ className }: { className?: string }) {
  771. return (
  772. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  773. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  774. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  775. <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"/>
  776. </svg>
  777. );
  778. }
  779. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  780. // Added for visual parity with the thermometer icons on the dual-nozzle card
  781. // that previously had no icon at all (#1115, design by @m4rtini2).
  782. function NozzleIcon({ className }: { className?: string }) {
  783. return (
  784. <svg
  785. className={className}
  786. viewBox="0 0 24 24"
  787. fill="none"
  788. xmlns="http://www.w3.org/2000/svg"
  789. stroke="currentColor"
  790. strokeWidth="1.5"
  791. strokeLinecap="round"
  792. strokeLinejoin="round"
  793. >
  794. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  795. <rect x="6" y="11.5" width="12.1" height="3.7" />
  796. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  797. </svg>
  798. );
  799. }
  800. // Heater thermometer icon - filled when heating, outline when off
  801. interface HeaterThermometerProps {
  802. className?: string;
  803. color: string; // The color class (e.g., "text-orange-400")
  804. isHeating: boolean;
  805. }
  806. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  807. // Extract the actual color from Tailwind class for SVG fill
  808. const colorMap: Record<string, string> = {
  809. 'text-orange-400': '#fb923c',
  810. 'text-blue-400': '#60a5fa',
  811. 'text-green-400': '#4ade80',
  812. };
  813. const fillColor = colorMap[color] || '#888';
  814. // Glow style when heating
  815. const glowStyle = isHeating ? {
  816. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  817. } : {};
  818. if (isHeating) {
  819. // Filled thermometer with glow - heater is ON
  820. return (
  821. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  822. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  823. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  824. <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"/>
  825. </svg>
  826. );
  827. }
  828. // Empty thermometer - heater is OFF
  829. return (
  830. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  831. <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"/>
  832. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  833. </svg>
  834. );
  835. }
  836. // AMS Filament Backup tri-state indicator + toggle.
  837. // state=true → ON, click to disable
  838. // state=false → OFF, click opens modal
  839. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  840. interface AmsBackupBadgeProps {
  841. state: boolean | null;
  842. onClick: () => void;
  843. }
  844. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  845. const { t } = useTranslation();
  846. const known = state !== null;
  847. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  848. let title: string;
  849. if (state === true) {
  850. className += known
  851. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  852. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  853. title = t('printers.amsBackup.titleOn');
  854. } else if (state === false) {
  855. className += known
  856. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  857. : 'bg-bambu-dark text-bambu-gray cursor-default';
  858. title = t('printers.amsBackup.titleOff');
  859. } else {
  860. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  861. title = t('printers.amsBackup.titleUnknown');
  862. }
  863. return (
  864. <button
  865. type="button"
  866. disabled={!known}
  867. onClick={() => known && onClick()}
  868. className={className}
  869. title={title}
  870. aria-label={title}
  871. >
  872. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  873. </button>
  874. );
  875. }
  876. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  877. // like AmsBackupBadge so the two sit together in the section header, but
  878. // pinned to the right-hand end of the rule: this is a view preference for the
  879. // row, not a property of the printer.
  880. interface ExternalSpoolToggleProps {
  881. hidden: boolean;
  882. onClick: () => void;
  883. }
  884. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  885. const { t } = useTranslation();
  886. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  887. return (
  888. <button
  889. type="button"
  890. onClick={onClick}
  891. aria-pressed={hidden}
  892. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  893. hidden
  894. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  895. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  896. }`}
  897. title={title}
  898. aria-label={title}
  899. >
  900. {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)]" />}
  901. </button>
  902. );
  903. }
  904. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  905. // Reference: https://github.com/theicedmango/bambu-humidity
  906. interface HumidityIndicatorProps {
  907. humidity: number | string;
  908. goodThreshold?: number; // <= this is green
  909. fairThreshold?: number; // <= this is orange, > is red
  910. onClick?: () => void;
  911. compact?: boolean; // Smaller version for grid layout
  912. }
  913. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  914. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  915. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  916. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  917. // Status thresholds (configurable via settings)
  918. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  919. let textColor: string;
  920. let statusText: string;
  921. if (isNaN(humidityValue)) {
  922. textColor = '#C3C2C1';
  923. statusText = 'Unknown';
  924. } else if (humidityValue <= good) {
  925. textColor = '#22a352'; // Green - Good
  926. statusText = 'Good';
  927. } else if (humidityValue <= fair) {
  928. textColor = '#d4a017'; // Gold - Fair
  929. statusText = 'Fair';
  930. } else {
  931. textColor = '#c62828'; // Red - Bad
  932. statusText = 'Bad';
  933. }
  934. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  935. let DropComponent: React.FC<{ className?: string }>;
  936. if (isNaN(humidityValue)) {
  937. DropComponent = WaterDropEmpty;
  938. } else if (humidityValue <= good) {
  939. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  940. } else if (humidityValue <= fair) {
  941. DropComponent = WaterDropHalf; // Fair - half filled
  942. } else {
  943. DropComponent = WaterDropFull; // Bad - full (too humid)
  944. }
  945. return (
  946. <button
  947. type="button"
  948. onClick={onClick}
  949. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  950. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  951. >
  952. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  953. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  954. </button>
  955. );
  956. }
  957. // Temperature indicator with dynamic icon and coloring
  958. interface TemperatureIndicatorProps {
  959. temp: number;
  960. goodThreshold?: number; // <= this is blue
  961. fairThreshold?: number; // <= this is orange, > is red
  962. onClick?: () => void;
  963. compact?: boolean; // Smaller version for grid layout
  964. }
  965. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  966. // Ensure thresholds are numbers
  967. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  968. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  969. let textColor: string;
  970. let statusText: string;
  971. let ThermoComponent: React.FC<{ className?: string }>;
  972. if (temp <= good) {
  973. textColor = '#22a352'; // Green - good (same as humidity)
  974. statusText = 'Good';
  975. ThermoComponent = ThermometerEmpty;
  976. } else if (temp <= fair) {
  977. textColor = '#d4a017'; // Gold - fair (same as humidity)
  978. statusText = 'Fair';
  979. ThermoComponent = ThermometerHalf;
  980. } else {
  981. textColor = '#c62828'; // Red - bad (same as humidity)
  982. statusText = 'Bad';
  983. ThermoComponent = ThermometerFull;
  984. }
  985. return (
  986. <button
  987. type="button"
  988. onClick={onClick}
  989. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  990. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  991. >
  992. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  993. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  994. </button>
  995. );
  996. }
  997. // How long to wait for an AMS to report a live drying cycle after the printer
  998. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  999. // within a couple of seconds; 30s covers the slowest observed push cadence
  1000. // without leaving the user waiting on a verdict.
  1001. const DRY_START_CONFIRM_MS = 30_000;
  1002. export function CoverImage({
  1003. url,
  1004. printName,
  1005. className = 'w-20 h-20',
  1006. radiusClass = 'rounded-lg',
  1007. }: {
  1008. url: string | null;
  1009. printName?: string;
  1010. className?: string;
  1011. radiusClass?: string;
  1012. }) {
  1013. const { t } = useTranslation();
  1014. const [loaded, setLoaded] = useState(false);
  1015. const [error, setError] = useState(false);
  1016. const [showOverlay, setShowOverlay] = useState(false);
  1017. const imgRef = useRef<HTMLImageElement>(null);
  1018. // Cache-bust the image URL when the print name changes so the browser
  1019. // fetches the new cover instead of serving the stale cached image.
  1020. const cacheBustedUrl = useMemo(() => {
  1021. if (!url) return null;
  1022. const sep = url.includes('?') ? '&' : '?';
  1023. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1024. }, [url, printName]);
  1025. // Re-evaluate load state when the image URL changes, and ask the element
  1026. // whether it is already showing something rather than assuming it is not.
  1027. //
  1028. // `onLoad` used to be the only thing that could set `loaded`, and this
  1029. // effect reset it to false unconditionally. That is right when the URL
  1030. // really changes, but it also runs on mount — and the two are not the same
  1031. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1032. // constant for the duration of a print, so navigating away from the
  1033. // printers page and back re-mounts with a byte-identical src that the
  1034. // browser serves from its in-memory cache. The `load` event for a cache hit
  1035. // and React's passive-effect flush are both plain tasks with no ordering
  1036. // between them, so when `load` won, this effect ran afterwards and undid
  1037. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1038. // sat there until a full reload. Nothing recovered it, because the URL
  1039. // never changes again during the print and so this effect never re-runs.
  1040. //
  1041. // Being a race, it reproduced every time for #2826's reporter and not at
  1042. // all here, which is also why the network panel showed no request: there
  1043. // was no request to show.
  1044. //
  1045. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1046. // which of the two ran first. It is also correct for the case the reporter
  1047. // proposed (a `load` that fires before React's handler is live), so the
  1048. // fix stands whichever mechanism is really at work.
  1049. useEffect(() => {
  1050. setError(false);
  1051. const el = imgRef.current;
  1052. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1053. }, [cacheBustedUrl]);
  1054. return (
  1055. <>
  1056. <div
  1057. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1058. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1059. >
  1060. {cacheBustedUrl && !error ? (
  1061. <>
  1062. <img
  1063. ref={imgRef}
  1064. src={cacheBustedUrl}
  1065. alt={t('printers.printPreview')}
  1066. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1067. onLoad={() => setLoaded(true)}
  1068. onError={() => setError(true)}
  1069. />
  1070. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1071. </>
  1072. ) : (
  1073. <Box className="w-8 h-8 text-bambu-gray" />
  1074. )}
  1075. </div>
  1076. {/* Cover Image Overlay */}
  1077. {showOverlay && cacheBustedUrl && (
  1078. <div
  1079. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1080. onClick={() => setShowOverlay(false)}
  1081. >
  1082. <div className="relative max-w-2xl max-h-full">
  1083. <img
  1084. src={cacheBustedUrl}
  1085. alt={t('printers.printPreview')}
  1086. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1087. />
  1088. {printName && (
  1089. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1090. )}
  1091. </div>
  1092. </div>
  1093. )}
  1094. </>
  1095. );
  1096. }
  1097. interface PrinterMaintenanceInfo {
  1098. due_count: number;
  1099. warning_count: number;
  1100. total_print_hours: number;
  1101. }
  1102. // Status summary bar component - uses queryClient to read cached statuses
  1103. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1104. const { t } = useTranslation();
  1105. const queryClient = useQueryClient();
  1106. // Subscribe to query cache changes to re-render when status updates
  1107. // Throttled to prevent rapid re-renders from causing tab crashes
  1108. const [cacheTick, setCacheTick] = useState(0);
  1109. useEffect(() => {
  1110. let pending = false;
  1111. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1112. if (!pending) {
  1113. pending = true;
  1114. requestAnimationFrame(() => {
  1115. setCacheTick(t => t + 1);
  1116. pending = false;
  1117. });
  1118. }
  1119. });
  1120. return () => unsubscribe();
  1121. }, [queryClient]);
  1122. const { counts, nextFinish } = useMemo(() => {
  1123. let printing = 0;
  1124. let paused = 0;
  1125. let finished = 0;
  1126. let idle = 0;
  1127. let offline = 0;
  1128. let loading = 0;
  1129. let error = 0;
  1130. let nextPrinterName: string | null = null;
  1131. let nextRemainingMin: number | null = null;
  1132. let nextProgress: number = 0;
  1133. printers?.forEach((printer) => {
  1134. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1135. if (status === undefined) {
  1136. // Status not yet loaded - don't count as offline yet
  1137. loading++;
  1138. } else if (!status.connected) {
  1139. offline++;
  1140. } else {
  1141. // Count printers with active HMS errors as problems
  1142. const knownHmsCount =
  1143. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1144. if (knownHmsCount > 0) {
  1145. error++;
  1146. }
  1147. switch (status.state) {
  1148. case 'RUNNING':
  1149. printing++;
  1150. if (status.remaining_time != null && status.remaining_time > 0) {
  1151. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1152. nextRemainingMin = status.remaining_time;
  1153. nextPrinterName = printer.name;
  1154. nextProgress = status.progress || 0;
  1155. }
  1156. }
  1157. break;
  1158. case 'PAUSE':
  1159. paused++;
  1160. break;
  1161. case 'FINISH':
  1162. finished++;
  1163. break;
  1164. case 'FAILED':
  1165. // FAILED is the printer's terminal gcode_state after a print stops —
  1166. // including user cancellations, where there's no actual fault. Only
  1167. // count it as a "problem" when an HMS error is also active; otherwise
  1168. // it's just a print that ended unsuccessfully and the plate needs
  1169. // clearing (same as FINISH from the operator's perspective).
  1170. if (knownHmsCount > 0) {
  1171. // Already counted above
  1172. } else {
  1173. finished++;
  1174. }
  1175. break;
  1176. default:
  1177. idle++;
  1178. break;
  1179. }
  1180. }
  1181. });
  1182. return {
  1183. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1184. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1185. };
  1186. // eslint-disable-next-line react-hooks/exhaustive-deps
  1187. }, [printers, queryClient, cacheTick]);
  1188. if (!printers?.length) return null;
  1189. const badges: { count: number; dot: string; label: string }[] = [
  1190. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1191. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1192. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1193. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1194. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1195. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1196. ];
  1197. return (
  1198. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1199. {badges.map(({ count, dot, label }) => count > 0 && (
  1200. <div key={label} className="flex items-center gap-1.5">
  1201. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1202. <span className="text-bambu-gray">
  1203. <span className="text-white font-medium">{count}</span> {label}
  1204. </span>
  1205. </div>
  1206. ))}
  1207. {nextFinish && (
  1208. <>
  1209. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1210. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1211. <div className="flex items-center gap-2">
  1212. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1213. <span className="text-white font-medium">{nextFinish.name}</span>
  1214. </div>
  1215. <div className="flex items-center gap-2 w-full sm:w-auto">
  1216. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1217. <div
  1218. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1219. style={{ width: `${nextFinish.progress}%` }}
  1220. />
  1221. </div>
  1222. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1223. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1224. </div>
  1225. </div>
  1226. </>
  1227. )}
  1228. </div>
  1229. );
  1230. }
  1231. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1232. type ViewMode = 'expanded' | 'compact';
  1233. type ToolbarDropdownOption<T extends string> = {
  1234. value: T;
  1235. label: string;
  1236. };
  1237. function ToolbarDropdown<T extends string>({
  1238. value,
  1239. options,
  1240. onChange,
  1241. fullWidth = false,
  1242. }: {
  1243. value: T;
  1244. options: ToolbarDropdownOption<T>[];
  1245. onChange: (value: T) => void;
  1246. fullWidth?: boolean;
  1247. }) {
  1248. const [isOpen, setIsOpen] = useState(false);
  1249. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1250. return (
  1251. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1252. <button
  1253. type="button"
  1254. onClick={() => setIsOpen(open => !open)}
  1255. 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'}`}
  1256. >
  1257. <span className="truncate">{selectedOption?.label}</span>
  1258. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1259. </button>
  1260. {isOpen && (
  1261. <>
  1262. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1263. <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">
  1264. {options.map(option => (
  1265. <button
  1266. key={option.value}
  1267. type="button"
  1268. onClick={() => {
  1269. onChange(option.value);
  1270. setIsOpen(false);
  1271. }}
  1272. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1273. option.value === value ? 'text-bambu-green' : 'text-white'
  1274. }`}
  1275. >
  1276. {option.label}
  1277. </button>
  1278. ))}
  1279. </div>
  1280. </>
  1281. )}
  1282. </div>
  1283. );
  1284. }
  1285. function ToolbarMenu({
  1286. label,
  1287. icon,
  1288. children,
  1289. }: {
  1290. label: string;
  1291. icon: React.ReactNode;
  1292. children: React.ReactNode;
  1293. }) {
  1294. const [isOpen, setIsOpen] = useState(false);
  1295. return (
  1296. <div className="relative">
  1297. <button
  1298. type="button"
  1299. onClick={() => setIsOpen(open => !open)}
  1300. 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"
  1301. aria-label={label}
  1302. title={label}
  1303. >
  1304. {icon}
  1305. </button>
  1306. {isOpen && (
  1307. <>
  1308. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1309. <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">
  1310. {children}
  1311. </div>
  1312. </>
  1313. )}
  1314. </div>
  1315. );
  1316. }
  1317. function IndicatorControlPopover({
  1318. title,
  1319. options = [],
  1320. unit,
  1321. customMin,
  1322. customMax,
  1323. customStep = 1,
  1324. widthClass = 'w-[240px]',
  1325. popoverWidth = 240,
  1326. popoverHeight = 280,
  1327. isPending,
  1328. onClose,
  1329. onSubmit,
  1330. children,
  1331. }: {
  1332. title: string;
  1333. options?: Array<{ label: string; value: number }>;
  1334. unit?: string;
  1335. customMin?: number;
  1336. customMax?: number;
  1337. customStep?: number;
  1338. widthClass?: string;
  1339. popoverWidth?: number;
  1340. popoverHeight?: number;
  1341. isPending?: boolean;
  1342. onClose: () => void;
  1343. onSubmit?: (value: number) => void;
  1344. children?: React.ReactNode;
  1345. }) {
  1346. const anchorRef = useRef<HTMLSpanElement>(null);
  1347. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1348. const [customValue, setCustomValue] = useState('');
  1349. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1350. // can position via fixed coords. Portaling to document.body escapes
  1351. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1352. // own contexts and would otherwise cover the popover even at z-[60].
  1353. useLayoutEffect(() => {
  1354. const trigger = anchorRef.current?.parentElement;
  1355. if (!trigger) return;
  1356. const measure = () => {
  1357. const rect = trigger.getBoundingClientRect();
  1358. setCoords(computePopoverPosition({
  1359. triggerRect: rect,
  1360. popoverWidth,
  1361. estimatedHeight: popoverHeight,
  1362. horizontalAlign: 'center',
  1363. }));
  1364. };
  1365. measure();
  1366. window.addEventListener('resize', measure);
  1367. window.addEventListener('scroll', measure, true);
  1368. return () => {
  1369. window.removeEventListener('resize', measure);
  1370. window.removeEventListener('scroll', measure, true);
  1371. };
  1372. }, [popoverWidth, popoverHeight]);
  1373. const showCustomInput = unit !== undefined;
  1374. const submitCustom = () => {
  1375. const value = Number(customValue);
  1376. if (!Number.isFinite(value)) return;
  1377. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1378. onSubmit?.(Math.round(bounded));
  1379. };
  1380. return (
  1381. <>
  1382. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1383. {createPortal(
  1384. <>
  1385. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1386. <div
  1387. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1388. style={{
  1389. top: coords?.top ?? -9999,
  1390. left: coords?.left ?? -9999,
  1391. visibility: coords ? 'visible' : 'hidden',
  1392. }}
  1393. onClick={e => e.stopPropagation()}
  1394. >
  1395. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1396. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1397. {options.length > 0 && (
  1398. <div className="px-3 py-2.5">
  1399. <div className="grid grid-cols-2 gap-1.5">
  1400. {options.map(option => (
  1401. <button
  1402. key={`${option.label}-${option.value}`}
  1403. type="button"
  1404. disabled={isPending}
  1405. onClick={() => onSubmit?.(option.value)}
  1406. 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"
  1407. >
  1408. {option.label}
  1409. </button>
  1410. ))}
  1411. </div>
  1412. </div>
  1413. )}
  1414. {children}
  1415. {showCustomInput && (
  1416. <>
  1417. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1418. <form
  1419. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1420. onSubmit={(e) => {
  1421. e.preventDefault();
  1422. submitCustom();
  1423. }}
  1424. >
  1425. <input
  1426. type="number"
  1427. min={customMin}
  1428. max={customMax}
  1429. step={customStep}
  1430. value={customValue}
  1431. onChange={e => setCustomValue(e.target.value)}
  1432. placeholder="Custom"
  1433. 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"
  1434. />
  1435. <button
  1436. type="submit"
  1437. disabled={isPending || customValue.trim() === ''}
  1438. 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"
  1439. >
  1440. Set
  1441. </button>
  1442. </form>
  1443. </>
  1444. )}
  1445. </div>
  1446. </>,
  1447. document.body
  1448. )}
  1449. </>
  1450. );
  1451. }
  1452. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1453. function NozzleTemperatureControlBox({
  1454. label,
  1455. current,
  1456. target,
  1457. isActive,
  1458. isPending,
  1459. onSubmit,
  1460. options = NOZZLE_TEMPERATURE_OPTIONS,
  1461. }: {
  1462. label: string;
  1463. current?: number;
  1464. target?: number;
  1465. isActive: boolean;
  1466. isPending?: boolean;
  1467. onSubmit: (value: number) => void;
  1468. options?: Array<{ label: string; value: number }>;
  1469. }) {
  1470. const [customValue, setCustomValue] = useState('');
  1471. const submitCustom = () => {
  1472. const value = Number(customValue);
  1473. if (!Number.isFinite(value)) return;
  1474. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1475. };
  1476. return (
  1477. <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'}`}>
  1478. <div className="mb-1.5 flex items-center justify-between gap-2">
  1479. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1480. <span className="text-[10px] text-bambu-gray">
  1481. {Math.round(current ?? 0)}°C
  1482. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1483. </span>
  1484. </div>
  1485. <div className="grid grid-cols-2 gap-1">
  1486. {options.map(option => (
  1487. <button
  1488. key={`${label}-${option.value}`}
  1489. type="button"
  1490. disabled={isPending}
  1491. onClick={() => onSubmit(option.value)}
  1492. 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"
  1493. >
  1494. {option.label}
  1495. </button>
  1496. ))}
  1497. </div>
  1498. <form
  1499. className="mt-1.5 flex gap-1"
  1500. onSubmit={(e) => {
  1501. e.preventDefault();
  1502. submitCustom();
  1503. }}
  1504. >
  1505. <input
  1506. type="number"
  1507. min={0}
  1508. max={320}
  1509. step={1}
  1510. value={customValue}
  1511. onChange={e => setCustomValue(e.target.value)}
  1512. placeholder="Custom"
  1513. 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"
  1514. />
  1515. <button
  1516. type="submit"
  1517. disabled={isPending || customValue.trim() === ''}
  1518. 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"
  1519. >
  1520. Set
  1521. </button>
  1522. </form>
  1523. </div>
  1524. );
  1525. }
  1526. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1527. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1528. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1529. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1530. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1531. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1532. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1533. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1534. };
  1535. /** Classify a printer into one of the UI status buckets. */
  1536. function classifyPrinterStatus(
  1537. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1538. ): PrinterState {
  1539. if (!status?.connected) return 'offline';
  1540. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1541. if (hmsErrors.length > 0) return 'error';
  1542. switch (status.state) {
  1543. case 'RUNNING': return 'printing';
  1544. case 'PAUSE': return 'paused';
  1545. case 'FINISH': return 'finished';
  1546. // FAILED without an active HMS error is the printer's terminal state after
  1547. // any unsuccessful end — including user-cancellations. Treat the same as
  1548. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1549. // HMS code is actually attached (handled by the early-return above).
  1550. case 'FAILED': return 'finished';
  1551. default: return 'idle';
  1552. }
  1553. }
  1554. /**
  1555. * Get human-readable status display text for a printer.
  1556. * Uses stg_cur_name for detailed calibration/preparation stages,
  1557. * otherwise formats the gcode_state nicely.
  1558. */
  1559. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1560. // If we have a specific stage name (calibration, heating, etc.), use it
  1561. if (stg_cur_name) {
  1562. return stg_cur_name;
  1563. }
  1564. // Format the gcode_state nicely
  1565. switch (state) {
  1566. case 'RUNNING':
  1567. return 'Printing';
  1568. case 'PAUSE':
  1569. return 'Paused';
  1570. case 'FINISH':
  1571. return 'Finished';
  1572. case 'FAILED':
  1573. return 'Failed';
  1574. case 'IDLE':
  1575. return 'Idle';
  1576. default:
  1577. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1578. }
  1579. }
  1580. // Bambu models that ship with an enclosure chamber fan (firmware field
  1581. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1582. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1583. // widget is hidden in fanItems instead of rendered greyed-out.
  1584. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1585. 'X1C',
  1586. 'X1',
  1587. 'X1E',
  1588. 'X2D',
  1589. 'P1S',
  1590. 'P2S',
  1591. 'H2D',
  1592. 'H2D Pro',
  1593. 'H2C',
  1594. 'H2S',
  1595. ]);
  1596. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1597. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1598. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1599. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1600. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1601. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1602. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1603. 'P2S',
  1604. 'X2D',
  1605. ]);
  1606. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1607. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1608. // • User-defined friendly name (editable, protected by printers:update)
  1609. // • AMS serial number
  1610. // • AMS firmware version
  1611. export function AmsNameHoverCard({
  1612. ams,
  1613. printerId,
  1614. label,
  1615. amsLabels,
  1616. canEdit,
  1617. onSaved,
  1618. children,
  1619. }: {
  1620. ams: import('../api/client').AMSUnit;
  1621. printerId: number;
  1622. label: string; // auto-generated label, e.g. "AMS-A"
  1623. amsLabels?: Record<number, string>;
  1624. canEdit: boolean;
  1625. onSaved: () => void;
  1626. children: React.ReactNode;
  1627. }) {
  1628. const { t } = useTranslation();
  1629. const [isVisible, setIsVisible] = useState(false);
  1630. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1631. const [editValue, setEditValue] = useState('');
  1632. const [isSaving, setIsSaving] = useState(false);
  1633. const [saveError, setSaveError] = useState<string | null>(null);
  1634. const [isInputFocused, setIsInputFocused] = useState(false);
  1635. const triggerRef = useRef<HTMLDivElement>(null);
  1636. const cardRef = useRef<HTMLDivElement>(null);
  1637. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1638. useEffect(() => {
  1639. if (isVisible) {
  1640. setEditValue(amsLabels?.[ams.id] ?? '');
  1641. setSaveError(null);
  1642. requestAnimationFrame(() => {
  1643. if (triggerRef.current && cardRef.current) {
  1644. const rect = triggerRef.current.getBoundingClientRect();
  1645. const spaceAbove = rect.top - 56;
  1646. const spaceBelow = window.innerHeight - rect.bottom;
  1647. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1648. }
  1649. });
  1650. }
  1651. }, [isVisible, amsLabels, ams.id]);
  1652. const handleMouseEnter = () => {
  1653. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1654. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1655. };
  1656. const handleMouseLeave = () => {
  1657. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1658. if (!isInputFocused) {
  1659. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1660. }
  1661. };
  1662. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1663. const handleSave = async () => {
  1664. if (!canEdit) return;
  1665. setIsSaving(true);
  1666. setSaveError(null);
  1667. try {
  1668. const trimmed = editValue.trim();
  1669. if (trimmed) {
  1670. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1671. } else {
  1672. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1673. }
  1674. onSaved();
  1675. setIsVisible(false);
  1676. } catch (err) {
  1677. setSaveError(err instanceof Error ? err.message : String(err));
  1678. } finally {
  1679. setIsSaving(false);
  1680. }
  1681. };
  1682. const handleClear = async () => {
  1683. if (!canEdit) return;
  1684. setIsSaving(true);
  1685. setSaveError(null);
  1686. try {
  1687. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1688. onSaved();
  1689. setIsVisible(false);
  1690. } catch (err) {
  1691. setSaveError(err instanceof Error ? err.message : String(err));
  1692. } finally {
  1693. setIsSaving(false);
  1694. }
  1695. };
  1696. return (
  1697. <div
  1698. ref={triggerRef}
  1699. className="relative inline-block"
  1700. onMouseEnter={handleMouseEnter}
  1701. onMouseLeave={handleMouseLeave}
  1702. >
  1703. {children}
  1704. {isVisible && (
  1705. <div
  1706. ref={cardRef}
  1707. className={`
  1708. absolute left-0 z-50
  1709. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1710. animate-in fade-in-0 zoom-in-95 duration-150
  1711. `}
  1712. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1713. onMouseEnter={handleMouseEnter}
  1714. onMouseLeave={handleMouseLeave}
  1715. >
  1716. <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">
  1717. {/* AMS auto-label */}
  1718. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1719. {/* Serial number */}
  1720. <div className="flex items-center justify-between gap-2">
  1721. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1722. {t('printers.amsPopup.serialNumber')}
  1723. </span>
  1724. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1725. </div>
  1726. {/* Firmware version */}
  1727. <div className="flex items-center justify-between gap-2">
  1728. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1729. {t('printers.amsPopup.firmwareVersion')}
  1730. </span>
  1731. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1732. </div>
  1733. {/* Friendly name editor */}
  1734. <div className="space-y-1">
  1735. <div className="flex items-center gap-2">
  1736. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1737. {t('printers.amsPopup.friendlyName')}
  1738. </span>
  1739. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1740. </div>
  1741. <input
  1742. type="text"
  1743. value={editValue}
  1744. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1745. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1746. onFocus={() => setIsInputFocused(true)}
  1747. onBlur={() => {
  1748. setIsInputFocused(false);
  1749. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1750. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1751. }}
  1752. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1753. disabled={!canEdit}
  1754. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1755. 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"
  1756. maxLength={100}
  1757. />
  1758. {canEdit && (
  1759. <div className="space-y-1">
  1760. {saveError && (
  1761. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1762. )}
  1763. <div className="flex gap-1 justify-end">
  1764. <button
  1765. onClick={handleSave}
  1766. disabled={isSaving}
  1767. 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"
  1768. >
  1769. {t('printers.amsPopup.save')}
  1770. </button>
  1771. {amsLabels?.[ams.id] && (
  1772. <button
  1773. onClick={handleClear}
  1774. disabled={isSaving}
  1775. 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"
  1776. >
  1777. {t('printers.amsPopup.clear')}
  1778. </button>
  1779. )}
  1780. </div>
  1781. </div>
  1782. )}
  1783. </div>
  1784. </div>
  1785. </div>
  1786. )}
  1787. </div>
  1788. );
  1789. }
  1790. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1791. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1792. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1793. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1794. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1795. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1796. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1797. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1798. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1799. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1800. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1801. };
  1802. // How much the printer card's body type and icons grow at each card size
  1803. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1804. // 1.0 and an existing install looks identical until the user picks L or XL --
  1805. // the same control the request asked to have this follow.
  1806. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1807. // The scaled sizes, handed to the card subtree as custom properties. Every
  1808. // converted class names its old fixed value as the fallback, so anything that
  1809. // renders outside a card root -- the portalled temperature popover -- keeps
  1810. // exactly the size it has today.
  1811. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1812. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1813. // Rounded to a tenth so the values stay readable in devtools.
  1814. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1815. return {
  1816. '--pc-t8': px(8),
  1817. '--pc-t9': px(9),
  1818. '--pc-t10': px(10),
  1819. '--pc-t11': px(11),
  1820. '--pc-i2': px(8),
  1821. '--pc-i25': px(10),
  1822. '--pc-i3': px(12),
  1823. '--pc-i35': px(14),
  1824. '--pc-i4': px(16),
  1825. '--pc-i5': px(20),
  1826. '--pc-i7': px(28),
  1827. } as React.CSSProperties;
  1828. }
  1829. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1830. const { t } = useTranslation();
  1831. const queryClient = useQueryClient();
  1832. const { showToast } = useToast();
  1833. // One fleet-wide query shared by every card, not one per card: the list is
  1834. // nearly always empty and a 20-printer fleet would otherwise make 20
  1835. // requests every 30s. React Query dedupes on the key.
  1836. const { data: scheduled = [] } = useQuery({
  1837. queryKey: SCHEDULED_DRYINGS_KEY,
  1838. queryFn: () => api.listScheduledDryings(),
  1839. refetchInterval: 30_000,
  1840. });
  1841. // The live AMS status reports a starting cycle well before the next poll;
  1842. // refetch so a just-dispatched schedule doesn't linger as pending.
  1843. useEffect(() => {
  1844. if (dryingActive) {
  1845. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1846. }
  1847. }, [dryingActive, queryClient]);
  1848. const cancelMutation = useMutation({
  1849. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1850. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1851. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1852. });
  1853. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1854. // old firmware on a printer that was offline at schedule time), and without
  1855. // this the run just vanishes with only the backend log saying why.
  1856. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1857. if (rows.length === 0) return null;
  1858. return (
  1859. <div className="mt-2 space-y-1">
  1860. {rows.map(s => {
  1861. const failed = s.status === 'failed';
  1862. const reasonKey = waitingReasonKey(s.waiting_reason);
  1863. const failedKey = failedReasonKey(s.error_code);
  1864. return (
  1865. <div
  1866. key={s.id}
  1867. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1868. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1869. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1870. }`}
  1871. >
  1872. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1873. {failed ? (
  1874. t('printers.drying.scheduleFailedReason', {
  1875. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1876. })
  1877. ) : (
  1878. <>
  1879. {s.start_after
  1880. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1881. : t('printers.drying.scheduledAsap')}
  1882. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1883. </>
  1884. )}
  1885. </span>
  1886. <button
  1887. onClick={() => cancelMutation.mutate(s.id)}
  1888. disabled={cancelMutation.isPending}
  1889. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1890. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1891. >
  1892. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1893. </button>
  1894. </div>
  1895. );
  1896. })}
  1897. </div>
  1898. );
  1899. }
  1900. function PrinterCard({
  1901. printer,
  1902. hideIfDisconnected,
  1903. maintenanceInfo,
  1904. viewMode = 'expanded',
  1905. cardSize = 2,
  1906. amsThresholds,
  1907. spoolmanEnabled = false,
  1908. linkedSpools,
  1909. spoolmanUrl,
  1910. spoolmanSyncMode,
  1911. onGetAssignment,
  1912. onUnassignSpool,
  1913. spoolmanSpools,
  1914. spoolmanSlotAssignments,
  1915. spoolmanLoading = false,
  1916. onUnassignSpoolmanSpool,
  1917. timeFormat = 'system',
  1918. cameraViewMode = 'window',
  1919. onOpenEmbeddedCamera,
  1920. onSelectCameraViewMode,
  1921. checkPrinterFirmware = true,
  1922. dryingPresets = DRYING_PRESETS,
  1923. requirePlateClear = false,
  1924. selectionMode = false,
  1925. isSelected = false,
  1926. onToggleSelect,
  1927. onOpenCompactCard,
  1928. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1929. bedTempPresets = BED_TEMP_DEFAULTS,
  1930. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1931. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1932. aiDetectionEnabled = false,
  1933. aiDetection,
  1934. aiLastError = null,
  1935. }: {
  1936. printer: Printer;
  1937. hideIfDisconnected?: boolean;
  1938. maintenanceInfo?: PrinterMaintenanceInfo;
  1939. viewMode?: ViewMode;
  1940. cardSize?: number;
  1941. amsThresholds?: {
  1942. humidityGood: number;
  1943. humidityFair: number;
  1944. tempGood: number;
  1945. tempFair: number;
  1946. };
  1947. spoolmanEnabled?: boolean;
  1948. hasUnlinkedSpools?: boolean;
  1949. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1950. spoolmanUrl?: string | null;
  1951. spoolmanSyncMode?: string | null;
  1952. spoolAssignments?: SpoolAssignment[];
  1953. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1954. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1955. spoolmanSpools?: InventorySpool[];
  1956. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1957. spoolmanLoading?: boolean;
  1958. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1959. timeFormat?: 'system' | '12h' | '24h';
  1960. cameraViewMode?: CameraViewMode;
  1961. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1962. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  1963. checkPrinterFirmware?: boolean;
  1964. dryingPresets?: Record<string, DryingPreset>;
  1965. requirePlateClear?: boolean;
  1966. selectionMode?: boolean;
  1967. isSelected?: boolean;
  1968. onToggleSelect?: (id: number) => void;
  1969. onOpenCompactCard?: (id: number) => void;
  1970. nozzleTempPresets?: readonly [number, number, number];
  1971. bedTempPresets?: readonly [number, number, number];
  1972. chamberTempPresets?: readonly [number, number, number];
  1973. fanSpeedPresets?: readonly [number, number, number];
  1974. aiDetectionEnabled?: boolean;
  1975. aiDetection?: AiDetection;
  1976. aiLastError?: string | null;
  1977. }) {
  1978. const { t } = useTranslation();
  1979. const queryClient = useQueryClient();
  1980. const navigate = useNavigate();
  1981. const { showToast } = useToast();
  1982. const { hasPermission, canModify, authEnabled, isAdmin } = useAuth();
  1983. const [showMenu, setShowMenu] = useState(false);
  1984. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1985. const [deleteArchives, setDeleteArchives] = useState(true);
  1986. const [showEditModal, setShowEditModal] = useState(false);
  1987. const [showFileManager, setShowFileManager] = useState(false);
  1988. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1989. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1990. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1991. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1992. const [showHMSModal, setShowHMSModal] = useState(false);
  1993. // #1546: AI failure detection modal — opens from the AI badge.
  1994. const [showAiModal, setShowAiModal] = useState(false);
  1995. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1996. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1997. // External spool visibility (#1782) — browser-local, per printer. Read once
  1998. // per card; the toggle that writes it is the only thing that changes it.
  1999. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2000. isExternalSpoolHidden(printer.id),
  2001. );
  2002. const toggleExternalSpool = useCallback(() => {
  2003. setExternalSpoolHidden((prev) => {
  2004. const next = !prev;
  2005. persistExternalSpoolHidden(printer.id, next);
  2006. return next;
  2007. });
  2008. }, [printer.id]);
  2009. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2010. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2011. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2012. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2013. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2014. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2015. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2016. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2017. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2018. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2019. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2020. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2021. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2022. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2023. // AMS drying popover state: which AMS unit has the popover open
  2024. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2025. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2026. const [dryingFilament, setDryingFilament] = useState('PLA');
  2027. const [dryingTemp, setDryingTemp] = useState(50);
  2028. const [dryingDuration, setDryingDuration] = useState(4);
  2029. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2030. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2031. // go through scheduleDryingMutation.
  2032. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2033. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2034. const [dryingStartAt, setDryingStartAt] = useState('');
  2035. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2036. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2037. // Reset every field the popover owns, including the start mode. Leaving the
  2038. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2039. // the next open, by then in the past, and the POST rejected it.
  2040. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2041. const firstTray = ams.tray.find(t => t.tray_type);
  2042. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2043. // Only reachable if a custom preset set dropped PLA itself.
  2044. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2045. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2046. setDryingFilament(filType);
  2047. setDryingTemp(preset[moduleType] || preset.n3f);
  2048. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2049. setDryingRotateTray(false);
  2050. setDryingStartMode('now');
  2051. setDryingDelayMinutes(120);
  2052. setDryingStartAt('');
  2053. setDryingPopoverModuleType(ams.module_type);
  2054. setDryingPopoverAmsId(ams.id);
  2055. setDryingPopoverAnchor(trigger);
  2056. }, [dryingPresets]);
  2057. // Re-measure on resize/scroll so the popover and its arrow track the
  2058. // flame button, like IndicatorControlPopover.
  2059. useLayoutEffect(() => {
  2060. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2061. const measure = () => {
  2062. setDryingPopoverPos(computePopoverPosition({
  2063. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2064. popoverWidth: DRYING_POPOVER_WIDTH,
  2065. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2066. horizontalAlign: 'center',
  2067. }));
  2068. };
  2069. measure();
  2070. window.addEventListener('resize', measure);
  2071. window.addEventListener('scroll', measure, true);
  2072. return () => {
  2073. window.removeEventListener('resize', measure);
  2074. window.removeEventListener('scroll', measure, true);
  2075. };
  2076. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2077. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2078. // Whether the click hitting the backdrop is the one that dismissed the
  2079. // native datetime picker (see the backdrop's onMouseDown).
  2080. const dryingBackdropSkipCloseRef = useRef(false);
  2081. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2082. // an object rather than a bare id so restarting drying on the SAME unit produces
  2083. // a new identity and rearms the timeout below.
  2084. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2085. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2086. const [isDropUploading, setIsDropUploading] = useState(false);
  2087. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2088. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2089. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2090. // inside the card would have to open upward into the card body; anchored to
  2091. // the viewport it escapes the card and the grid's scroll container both.
  2092. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2093. const dragCounterRef = useRef(0);
  2094. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2095. amsId: number;
  2096. amsLabel: string;
  2097. mode: 'humidity' | 'temperature';
  2098. } | null>(null);
  2099. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2100. initialKind: HeaterSensorKind;
  2101. availableKinds: HeaterSensorKind[];
  2102. } | null>(null);
  2103. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2104. tagUid: string;
  2105. trayUuid: string;
  2106. printerId: number;
  2107. amsId: number;
  2108. trayId: number;
  2109. } | null>(null);
  2110. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2111. printerId: number;
  2112. amsId: number;
  2113. trayId: number;
  2114. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2115. } | null>(null);
  2116. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2117. amsId: number;
  2118. trayId: number;
  2119. trayCount: number;
  2120. trayType?: string;
  2121. trayColor?: string;
  2122. traySubBrands?: string;
  2123. trayInfoIdx?: string;
  2124. extruderId?: number;
  2125. caliIdx?: number | null;
  2126. savedPresetId?: string;
  2127. } | null>(null);
  2128. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2129. const [plateCheckResult, setPlateCheckResult] = useState<{
  2130. is_empty: boolean;
  2131. confidence: number;
  2132. difference_percent: number;
  2133. message: string;
  2134. debug_image_url?: string;
  2135. needs_calibration: boolean;
  2136. light_warning?: boolean;
  2137. reference_count?: number;
  2138. max_references?: number;
  2139. roi?: { x: number; y: number; w: number; h: number };
  2140. } | null>(null);
  2141. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2142. const [isCalibrating, setIsCalibrating] = useState(false);
  2143. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2144. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2145. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2146. const { data: status } = useQuery({
  2147. queryKey: ['printerStatus', printer.id],
  2148. queryFn: () => api.getPrinterStatus(printer.id),
  2149. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2150. });
  2151. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2152. const { data: firmwareInfo } = useQuery({
  2153. queryKey: ['firmwareUpdate', printer.id],
  2154. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2155. staleTime: 5 * 60 * 1000,
  2156. refetchInterval: 5 * 60 * 1000,
  2157. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2158. });
  2159. // Collect unique tray_info_idx values for cloud filament info lookup
  2160. const trayInfoIds = useMemo(() => {
  2161. const ids = new Set<string>();
  2162. if (status?.ams) {
  2163. for (const ams of status.ams) {
  2164. for (const tray of ams.tray || []) {
  2165. if (tray.tray_info_idx) {
  2166. ids.add(tray.tray_info_idx);
  2167. }
  2168. }
  2169. }
  2170. }
  2171. for (const vt of status?.vt_tray ?? []) {
  2172. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2173. }
  2174. if (status?.nozzle_rack) {
  2175. for (const slot of status.nozzle_rack) {
  2176. if (slot.filament_id) {
  2177. ids.add(slot.filament_id);
  2178. }
  2179. }
  2180. }
  2181. return Array.from(ids);
  2182. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2183. // Collect loaded filament types for queue widget filtering
  2184. const loadedFilamentTypes = useMemo(() => {
  2185. const types = new Set<string>();
  2186. if (status?.ams) {
  2187. for (const ams of status.ams) {
  2188. for (const tray of ams.tray || []) {
  2189. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2190. }
  2191. }
  2192. }
  2193. for (const vt of status?.vt_tray ?? []) {
  2194. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2195. }
  2196. return types;
  2197. }, [status?.ams, status?.vt_tray]);
  2198. // Collect loaded filament type+color pairs for queue widget override matching
  2199. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2200. const loadedFilaments = useMemo(() => {
  2201. const filaments = new Set<string>();
  2202. if (status?.ams) {
  2203. for (const ams of status.ams) {
  2204. for (const tray of ams.tray || []) {
  2205. if (tray.tray_type && tray.tray_color) {
  2206. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2207. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2208. }
  2209. }
  2210. }
  2211. }
  2212. for (const vt of status?.vt_tray ?? []) {
  2213. if (vt.tray_type && vt.tray_color) {
  2214. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2215. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2216. }
  2217. }
  2218. return filaments;
  2219. }, [status?.ams, status?.vt_tray]);
  2220. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2221. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2222. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2223. const loadedVariants = useMemo(() => {
  2224. const variants = new Set<string>();
  2225. if (status?.ams) {
  2226. for (const ams of status.ams) {
  2227. for (const tray of ams.tray || []) {
  2228. if (tray.tray_type && tray.tray_color) {
  2229. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2230. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2231. }
  2232. }
  2233. }
  2234. }
  2235. for (const vt of status?.vt_tray ?? []) {
  2236. if (vt.tray_type && vt.tray_color) {
  2237. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2238. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2239. }
  2240. }
  2241. return variants;
  2242. }, [status?.ams, status?.vt_tray]);
  2243. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2244. const { data: filamentInfo } = useQuery({
  2245. queryKey: ['filamentInfo', trayInfoIds],
  2246. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2247. enabled: trayInfoIds.length > 0,
  2248. staleTime: 5 * 60 * 1000, // 5 minutes
  2249. });
  2250. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2251. const { data: slotPresets } = useQuery({
  2252. queryKey: ['slotPresets', printer.id],
  2253. queryFn: () => api.getSlotPresets(printer.id),
  2254. staleTime: 2 * 60 * 1000, // 2 minutes
  2255. });
  2256. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2257. // Only queried when there's a running print backed by an archive; shared
  2258. // React Query cache with the Queue / Archives pages keeps it cheap.
  2259. const activeArchiveId =
  2260. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2261. const { data: activeArchivePlates } = useQuery({
  2262. queryKey: ['archive-plates', activeArchiveId],
  2263. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2264. enabled: activeArchiveId != null,
  2265. staleTime: 5 * 60 * 1000,
  2266. });
  2267. const activePlateLabel = (() => {
  2268. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2269. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2270. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2271. })();
  2272. // Fetch user-defined AMS friendly names from the database
  2273. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2274. queryKey: ['amsLabels', printer.id],
  2275. queryFn: () => api.getAmsLabels(printer.id),
  2276. staleTime: 5 * 60 * 1000, // 5 minutes
  2277. });
  2278. // Cache WiFi signal to prevent it disappearing on updates
  2279. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2280. useEffect(() => {
  2281. if (status?.wifi_signal != null) {
  2282. setCachedWifiSignal(status.wifi_signal);
  2283. }
  2284. }, [status?.wifi_signal]);
  2285. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2286. // Cache connected state to prevent flicker when status briefly becomes undefined
  2287. const cachedConnected = useRef<boolean | undefined>(undefined);
  2288. useEffect(() => {
  2289. if (status?.connected !== undefined) {
  2290. cachedConnected.current = status.connected;
  2291. }
  2292. }, [status?.connected]);
  2293. const isConnected = status?.connected ?? cachedConnected.current;
  2294. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2295. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2296. useEffect(() => {
  2297. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2298. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2299. }
  2300. }, [status?.ams_extruder_map]);
  2301. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2302. ? status.ams_extruder_map
  2303. : cachedAmsExtruderMap.current;
  2304. // Same caching for the Filament Track Switch inlet bindings, for the same
  2305. // reason: a partial MQTT frame briefly empties the map and the badges would
  2306. // otherwise blink out.
  2307. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2308. useEffect(() => {
  2309. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2310. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2311. }
  2312. }, [status?.ams_switch_inlet]);
  2313. const ftsInstalled = status?.fila_switch?.installed === true;
  2314. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2315. ? status.ams_switch_inlet
  2316. : cachedAmsSwitchInlet.current;
  2317. // Cache AMS data to prevent it disappearing on idle/offline printers
  2318. const cachedAmsData = useRef<AMSUnit[]>([]);
  2319. useEffect(() => {
  2320. if (status?.ams && status.ams.length > 0) {
  2321. cachedAmsData.current = status.ams;
  2322. }
  2323. }, [status?.ams]);
  2324. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2325. // #2532: the K-profile line only exists on slots the printer has actually
  2326. // calibrated. The AMS units and the external-spool group are flex siblings in
  2327. // one row, so on a card that shows a value anywhere, the slots without one
  2328. // reserve the same height -- otherwise their fill bars sit a line above their
  2329. // neighbours'. A card with no calibrated slot at all is unaffected.
  2330. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2331. || (status?.vt_tray ?? []).some(tray => tray.k);
  2332. // Confirm a drying cycle actually started (#2533). Firmware answers
  2333. // ams_filament_drying with result=success even when it then silently declines,
  2334. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2335. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2336. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2337. // means the printer took the command and dropped it.
  2338. useEffect(() => {
  2339. if (!dryStartWatch) return;
  2340. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2341. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2342. }, [dryStartWatch, amsData]);
  2343. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2344. // otherwise rearm the timeout on every frame, so it would never elapse.
  2345. useEffect(() => {
  2346. if (!dryStartWatch) return;
  2347. const timer = setTimeout(() => {
  2348. setDryStartWatch(null);
  2349. showToast(t('printers.drying.toastNotStarted'), 'error');
  2350. }, DRY_START_CONFIRM_MS);
  2351. return () => clearTimeout(timer);
  2352. }, [dryStartWatch, showToast, t]);
  2353. // Cache tray_now to prevent flickering when undefined values come in
  2354. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2355. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2356. const cachedTrayNow = useRef<number | undefined>(undefined);
  2357. const currentTrayNow = status?.tray_now;
  2358. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2359. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2360. cachedTrayNow.current = currentTrayNow;
  2361. } else if (currentTrayNow === 255) {
  2362. cachedTrayNow.current = undefined;
  2363. }
  2364. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2365. ? currentTrayNow
  2366. : cachedTrayNow.current;
  2367. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2368. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2369. // expectedTray = the slot the firmware now expects filament in
  2370. // previousTray = the slot that ran out
  2371. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2372. // so these are often different — the graphic highlights the expected one.
  2373. const expectedTray = status?.expected_tray ?? null;
  2374. const previousTray = status?.previous_tray ?? null;
  2375. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2376. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2377. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2378. if (globalId === null) return null;
  2379. if (globalId === 254) return t('printers.expectedSlot.external');
  2380. if (globalId >= 128 && globalId <= 135) {
  2381. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2382. }
  2383. const amsId = Math.floor(globalId / 4);
  2384. const slot = globalId % 4;
  2385. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2386. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2387. };
  2388. const runoutGuidance = status?.state === 'PAUSE'
  2389. ? {
  2390. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2391. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2392. }
  2393. : null;
  2394. // Fetch smart plug for this printer
  2395. const { data: smartPlug } = useQuery({
  2396. queryKey: ['smartPlugByPrinter', printer.id],
  2397. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2398. });
  2399. // Fetch script plugs for this printer (for multi-device control)
  2400. const { data: scriptPlugs } = useQuery({
  2401. queryKey: ['scriptPlugsByPrinter', printer.id],
  2402. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2403. });
  2404. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2405. const { data: plugStatus } = useQuery({
  2406. queryKey: ['smartPlugStatus', smartPlug?.id],
  2407. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2408. enabled: !!smartPlug,
  2409. refetchInterval: 10000, // 10 seconds for real-time power display
  2410. });
  2411. // Fetch queue count for this printer
  2412. const { data: queueItems } = useQuery({
  2413. queryKey: ['queue', printer.id, 'pending'],
  2414. queryFn: () => api.getQueue(printer.id, 'pending'),
  2415. });
  2416. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2417. // so the badge only shows on printers that can actually run the queued jobs.
  2418. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2419. const queueCount = useMemo(() => {
  2420. if (!queueItems?.length) return 0;
  2421. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2422. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2423. // Fetch currently printing queue item to show who started it (Issue #206)
  2424. const { data: printingQueueItems } = useQuery({
  2425. queryKey: ['queue', printer.id, 'printing'],
  2426. queryFn: () => api.getQueue(printer.id, 'printing'),
  2427. enabled: status?.state === 'RUNNING',
  2428. });
  2429. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2430. const { data: reprintUser } = useQuery({
  2431. queryKey: ['currentPrintUser', printer.id],
  2432. queryFn: () => api.getCurrentPrintUser(printer.id),
  2433. enabled: status?.state === 'RUNNING',
  2434. });
  2435. // Combine both sources: queue item user takes precedence, then reprint user
  2436. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2437. // Fetch last completed print for this printer
  2438. const { data: lastPrints } = useQuery({
  2439. queryKey: ['archives', printer.id, 'last'],
  2440. queryFn: () => api.getArchives(printer.id, 1, 0),
  2441. enabled: status?.connected && status?.state !== 'RUNNING',
  2442. });
  2443. const lastPrint = lastPrints?.[0];
  2444. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2445. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2446. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2447. // gate is up and the just-finished print asked for a verdict, offer
  2448. // Good/Reject right where the operator releases the plate. Releasing the
  2449. // plate without answering stays possible — the two are orthogonal (though
  2450. // the confirm_default_good_on_plate_clear setting can couple them).
  2451. // Only offered to whoever may record it: the PATCH checks archives:update
  2452. // against the archive's owner, so for anyone else the pair could only fail.
  2453. const pendingConfirmArchive =
  2454. lastPrint &&
  2455. lastPrint.status === 'completed' &&
  2456. lastPrint.confirm_requested &&
  2457. lastPrint.user_verdict == null &&
  2458. canModify('archives', 'update', lastPrint.created_by_id)
  2459. ? lastPrint
  2460. : null;
  2461. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2462. // Auto Power Off the printer is powered down exactly when the operator clears the
  2463. // plate. Hiding the control there left no way to release the gate (#2864).
  2464. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2465. const activePrintName = status?.current_print && isPrintingOrPaused
  2466. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2467. : null;
  2468. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2469. useEffect(() => {
  2470. if (activePrintName) {
  2471. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2472. } else if (!needsPlateClear) {
  2473. setRetainedPrintJob(null);
  2474. }
  2475. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2476. const plateStatus = (() => {
  2477. // Connected-only because the pill's only render site sits inside the live-status
  2478. // panel. For a powered-down printer the plate-clear button itself carries the
  2479. // state — see the standalone slot below the status block (#2864).
  2480. if (!requirePlateClear || !status?.connected) return null;
  2481. if (isPrintingOrPaused) {
  2482. return {
  2483. label: t('printers.plateStatus.inUse'),
  2484. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2485. };
  2486. }
  2487. if (status.awaiting_plate_clear) {
  2488. return {
  2489. label: t('printers.plateStatus.notCleared'),
  2490. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2491. };
  2492. }
  2493. return {
  2494. label: t('printers.plateStatus.cleared'),
  2495. className: 'bg-status-ok/20 text-status-ok',
  2496. };
  2497. })();
  2498. const plateStatusPill = plateStatus ? (
  2499. <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}`}>
  2500. {plateStatus.label}
  2501. </span>
  2502. ) : null;
  2503. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2504. const shouldHide = hideIfDisconnected && isConnected === false;
  2505. const deleteMutation = useMutation({
  2506. mutationFn: (options: { deleteArchives: boolean }) =>
  2507. api.deletePrinter(printer.id, options.deleteArchives),
  2508. onSuccess: () => {
  2509. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2510. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2511. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2512. },
  2513. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2514. });
  2515. const connectMutation = useMutation({
  2516. mutationFn: () => api.connectPrinter(printer.id),
  2517. onSuccess: () => {
  2518. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2519. },
  2520. });
  2521. const forceRefreshMutation = useMutation({
  2522. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2523. onSuccess: () => {
  2524. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2525. showToast(t('printers.forceRefreshSuccess'), 'success');
  2526. },
  2527. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2528. });
  2529. const unlinkSpoolMutation = useMutation({
  2530. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2531. onSuccess: (result) => {
  2532. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2533. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2534. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2535. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2536. },
  2537. onError: (error: Error) => {
  2538. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2539. },
  2540. });
  2541. // AMS drying mutations
  2542. const startDryingMutation = useMutation({
  2543. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2544. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2545. onSuccess: (_data, { amsId }) => {
  2546. setDryingPopoverAmsId(null);
  2547. setDryStartWatch({ amsId });
  2548. // "Command sent", not "drying started" — at this point the printer has only
  2549. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2550. // the cycle is genuinely live; the watcher below covers the case where it
  2551. // never appears.
  2552. showToast(t('printers.drying.toastCommandSent'), 'success');
  2553. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2554. },
  2555. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2556. });
  2557. // Scheduled (delayed / at-time) drying runs (#2638)
  2558. const scheduleDryingMutation = useMutation({
  2559. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2560. api.createScheduledDrying({
  2561. printer_id: printer.id,
  2562. ams_id: params.amsId,
  2563. temp: params.temp,
  2564. duration_hours: params.duration,
  2565. filament: params.filament,
  2566. rotate_tray: params.rotateTray,
  2567. start_after: params.startAfter,
  2568. }),
  2569. onSuccess: () => {
  2570. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2571. setDryingPopoverAmsId(null);
  2572. },
  2573. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2574. });
  2575. const stopDryingMutation = useMutation({
  2576. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2577. onSuccess: () => {
  2578. setDryStartWatch(null);
  2579. showToast(t('printers.drying.toastStopped'), 'success');
  2580. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2581. },
  2582. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2583. });
  2584. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2585. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2586. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2587. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2588. // showing the old backup state until the user reopens it.
  2589. const setAmsBackupMutation = useMutation({
  2590. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2591. onSuccess: (_data, enabled) => {
  2592. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2593. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2594. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2595. },
  2596. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2597. });
  2598. // Smart plug control mutations
  2599. const powerControlMutation = useMutation({
  2600. mutationFn: (action: 'on' | 'off') =>
  2601. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2602. onSuccess: () => {
  2603. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2604. },
  2605. });
  2606. const toggleAutoOffMutation = useMutation({
  2607. mutationFn: (enabled: boolean) =>
  2608. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2609. onSuccess: () => {
  2610. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2611. // Also invalidate the smart-plugs list to keep Settings page in sync
  2612. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2613. },
  2614. });
  2615. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2616. const runScriptMutation = useMutation({
  2617. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2618. onSuccess: () => {
  2619. showToast(t('printers.toast.scriptTriggered'));
  2620. },
  2621. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2622. });
  2623. // Print control mutations
  2624. const stopPrintMutation = useMutation({
  2625. mutationFn: () => api.stopPrint(printer.id),
  2626. onSuccess: () => {
  2627. showToast(t('printers.toast.printStopped'));
  2628. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2629. },
  2630. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2631. });
  2632. const pausePrintMutation = useMutation({
  2633. mutationFn: () => api.pausePrint(printer.id),
  2634. onSuccess: () => {
  2635. showToast(t('printers.toast.printPaused'));
  2636. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2637. },
  2638. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2639. });
  2640. const resumePrintMutation = useMutation({
  2641. mutationFn: () => api.resumePrint(printer.id),
  2642. onSuccess: () => {
  2643. showToast(t('printers.toast.printResumed'));
  2644. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2645. },
  2646. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2647. });
  2648. const clearPlateMutation = useMutation({
  2649. mutationFn: () => api.clearPlate(printer.id),
  2650. onSuccess: () => {
  2651. showToast(t('queue.clearPlateSuccess'));
  2652. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2653. old ? { ...old, awaiting_plate_clear: false } : old
  2654. );
  2655. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2656. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2657. },
  2658. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2659. });
  2660. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2661. // reject goes through the dialog for the optional reason + reprint.
  2662. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2663. // Only "good" is answered on the card. A reject wants a reason and possibly
  2664. // a reprint, so that button opens the dialog instead — and the parameter
  2665. // says as much, rather than accepting a verdict this path cannot send and
  2666. // then reporting it as good.
  2667. const cardVerdictMutation = useMutation({
  2668. mutationFn: (verdict: 'good') =>
  2669. api.updateArchive(pendingConfirmArchive!.id, {
  2670. user_verdict: verdict,
  2671. user_verdict_source: 'printer_card',
  2672. }),
  2673. onSuccess: () => {
  2674. showToast(t('confirmOutcome.savedGood'), 'success');
  2675. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2676. },
  2677. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2678. });
  2679. // Rendered from two places: inside the live-status block for a connected printer,
  2680. // and standalone below it for a powered-down one, whose status block isn't rendered
  2681. // at all (#2864). Shared so the two can't drift apart.
  2682. const expandedClearPlateButton = (
  2683. <>
  2684. {pendingConfirmArchive && (
  2685. <div className="mt-2 flex items-center gap-1.5">
  2686. <span
  2687. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2688. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2689. >
  2690. {t('confirmOutcome.cardPrompt')}
  2691. </span>
  2692. <button
  2693. type="button"
  2694. onClick={() => setShowConfirmOutcome(true)}
  2695. disabled={cardVerdictMutation.isPending}
  2696. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2697. title={t('confirmOutcome.reject')}
  2698. >
  2699. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2700. </button>
  2701. <button
  2702. type="button"
  2703. onClick={() => cardVerdictMutation.mutate('good')}
  2704. disabled={cardVerdictMutation.isPending}
  2705. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2706. title={t('confirmOutcome.good')}
  2707. >
  2708. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2709. </button>
  2710. </div>
  2711. )}
  2712. <button
  2713. type="button"
  2714. onClick={() => clearPlateMutation.mutate()}
  2715. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2716. 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"
  2717. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2718. >
  2719. {clearPlateMutation.isPending ? (
  2720. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2721. ) : (
  2722. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2723. )}
  2724. {t('printers.plateStatus.markCleared')}
  2725. </button>
  2726. {showConfirmOutcome && pendingConfirmArchive && (
  2727. <ConfirmOutcomeDialog
  2728. archiveId={pendingConfirmArchive.id}
  2729. onClose={() => setShowConfirmOutcome(false)}
  2730. />
  2731. )}
  2732. </>
  2733. );
  2734. const nozzleTemperatureMutation = useMutation({
  2735. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2736. api.setNozzleTemperature(printer.id, target, nozzle),
  2737. onSuccess: (result) => {
  2738. setStatusControlMenu(null);
  2739. showToast(result.message);
  2740. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2741. },
  2742. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2743. });
  2744. const bedTemperatureMutation = useMutation({
  2745. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2746. onSuccess: (result) => {
  2747. setStatusControlMenu(null);
  2748. showToast(result.message);
  2749. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2750. },
  2751. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2752. });
  2753. const chamberTemperatureMutation = useMutation({
  2754. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2755. onSuccess: (result) => {
  2756. setStatusControlMenu(null);
  2757. showToast(result.message);
  2758. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2759. },
  2760. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2761. });
  2762. const fanSpeedMutation = useMutation({
  2763. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2764. api.setFanSpeed(printer.id, fan, speed),
  2765. onMutate: async ({ fan, speed }) => {
  2766. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2767. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2768. const fanField = {
  2769. part: 'cooling_fan_speed',
  2770. aux: 'big_fan1_speed',
  2771. aux2: 'left_aux_fan_speed',
  2772. chamber: 'big_fan2_speed',
  2773. }[fan];
  2774. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2775. old ? { ...old, [fanField]: speed } : old
  2776. );
  2777. return { previousStatus };
  2778. },
  2779. onSuccess: (result) => {
  2780. setStatusControlMenu(null);
  2781. showToast(result.message);
  2782. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2783. },
  2784. onError: (error: Error, _variables, context) => {
  2785. if (context?.previousStatus) {
  2786. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2787. }
  2788. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2789. },
  2790. });
  2791. const selectExtruderMutation = useMutation({
  2792. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2793. onMutate: async (extruder) => {
  2794. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2795. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2796. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2797. old ? { ...old, active_extruder: extruder } : old
  2798. );
  2799. return { previousStatus };
  2800. },
  2801. onSuccess: (result) => {
  2802. setStatusControlMenu(null);
  2803. showToast(result.message);
  2804. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2805. },
  2806. onError: (error: Error, _extruder, context) => {
  2807. if (context?.previousStatus) {
  2808. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2809. }
  2810. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2811. },
  2812. });
  2813. // Chamber light mutation with optimistic update
  2814. const chamberLightMutation = useMutation({
  2815. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2816. onMutate: async (on) => {
  2817. // Cancel any outgoing refetches
  2818. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2819. // Snapshot the previous value
  2820. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2821. // Optimistically update
  2822. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2823. ...old,
  2824. chamber_light: on,
  2825. }));
  2826. return { previousStatus };
  2827. },
  2828. onSuccess: (_, on) => {
  2829. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2830. },
  2831. onError: (error: Error, _, context) => {
  2832. // Rollback on error
  2833. if (context?.previousStatus) {
  2834. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2835. }
  2836. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2837. },
  2838. });
  2839. // Print speed mutation with optimistic update
  2840. const printSpeedMutation = useMutation({
  2841. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2842. onMutate: async (mode) => {
  2843. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2844. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2845. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2846. ...old,
  2847. speed_level: mode,
  2848. }));
  2849. return { previousStatus };
  2850. },
  2851. onError: (error: Error, _, context) => {
  2852. if (context?.previousStatus) {
  2853. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2854. }
  2855. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2856. },
  2857. });
  2858. const airductMutation = useMutation({
  2859. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2860. onMutate: async (mode) => {
  2861. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2862. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2863. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2864. ...old,
  2865. airduct_mode: mode === 'cooling' ? 0 : 1,
  2866. }));
  2867. return { previousStatus };
  2868. },
  2869. onError: (error: Error, _, context) => {
  2870. if (context?.previousStatus) {
  2871. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2872. }
  2873. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2874. },
  2875. });
  2876. const bedJogMutation = useMutation({
  2877. mutationFn: ({ distance }: { distance: number }) =>
  2878. api.bedJog(printer.id, distance),
  2879. onError: (error: Error) =>
  2880. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2881. });
  2882. const xyJogMutation = useMutation({
  2883. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2884. api.xyJog(printer.id, x, y),
  2885. onError: (error: Error) =>
  2886. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2887. });
  2888. const extruderJogMutation = useMutation({
  2889. mutationFn: (distance: number) =>
  2890. api.extruderJog(printer.id, distance),
  2891. onError: (error: Error) =>
  2892. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2893. });
  2894. const homeAxesMutation = useMutation({
  2895. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2896. onSuccess: () => {
  2897. showToast(t('printers.bedJog.homingStarted'));
  2898. },
  2899. onError: (error: Error) =>
  2900. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2901. });
  2902. // Plate detection setting mutation
  2903. const plateDetectionMutation = useMutation({
  2904. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2905. onSuccess: () => {
  2906. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2907. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2908. },
  2909. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2910. });
  2911. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2912. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2913. // metrics, and the print picker — so flipping this flag puts the printer
  2914. // out of service across every consumer in one place. Used from the
  2915. // overflow menu and EditPrinterModal.
  2916. const maintenanceMutation = useMutation({
  2917. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2918. onSuccess: (_data, isActive) => {
  2919. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2920. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2921. showToast(
  2922. isActive
  2923. ? t('printers.maintenance.toastExited', { name: printer.name })
  2924. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2925. 'success',
  2926. );
  2927. },
  2928. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2929. });
  2930. // Confirm before entering maintenance on a printing printer (entering mode
  2931. // disconnects MQTT, which stops progress tracking + completion notifications
  2932. // for the in-flight job).
  2933. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2934. const handleEnterMaintenance = () => {
  2935. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2936. setConfirmMaintenanceEnter(true);
  2937. } else {
  2938. maintenanceMutation.mutate(false);
  2939. }
  2940. };
  2941. // Query for printable objects (for skip functionality)
  2942. // Fetch when printing with 2+ objects OR when modal is open
  2943. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2944. const { data: objectsData } = useQuery({
  2945. queryKey: ['printableObjects', printer.id],
  2946. queryFn: () => api.getPrintableObjects(printer.id),
  2947. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2948. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2949. });
  2950. // State for tracking which AMS slot is being refreshed
  2951. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2952. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2953. const seenBusyStateRef = useRef<boolean>(false);
  2954. // Fallback timeout ref
  2955. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2956. // Minimum display time passed
  2957. const minTimePassedRef = useRef<boolean>(false);
  2958. // AMS slot refresh mutation
  2959. const refreshAmsSlotMutation = useMutation({
  2960. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2961. api.refreshAmsSlot(printer.id, amsId, slotId),
  2962. onMutate: ({ amsId, slotId }) => {
  2963. // Clear any existing timeout
  2964. if (refreshTimeoutRef.current) {
  2965. clearTimeout(refreshTimeoutRef.current);
  2966. }
  2967. // Reset state
  2968. seenBusyStateRef.current = false;
  2969. minTimePassedRef.current = false;
  2970. setRefreshingSlot({ amsId, slotId });
  2971. // Minimum display time (2 seconds)
  2972. setTimeout(() => {
  2973. minTimePassedRef.current = true;
  2974. }, 2000);
  2975. // Fallback timeout (30 seconds max)
  2976. refreshTimeoutRef.current = setTimeout(() => {
  2977. setRefreshingSlot(null);
  2978. }, 30000);
  2979. },
  2980. onSuccess: (data) => {
  2981. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2982. },
  2983. onError: (error: Error) => {
  2984. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2985. if (refreshTimeoutRef.current) {
  2986. clearTimeout(refreshTimeoutRef.current);
  2987. }
  2988. setRefreshingSlot(null);
  2989. },
  2990. });
  2991. // AMS load/unload mutations (#891)
  2992. const loadAmsTrayMutation = useMutation({
  2993. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  2994. api.loadAmsTray(printer.id, trayId, extruderId),
  2995. onSuccess: (data) => {
  2996. setFeedDirectionRequest(null);
  2997. showToast(data.message || t('printers.toast.loadInitiated'));
  2998. },
  2999. onError: (error: Error) => {
  3000. setFeedDirectionRequest(null);
  3001. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3002. },
  3003. });
  3004. const unloadAmsMutation = useMutation({
  3005. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3006. onSuccess: (data) => {
  3007. showToast(data.message || t('printers.toast.unloadInitiated'));
  3008. },
  3009. onError: (error: Error) => {
  3010. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3011. },
  3012. });
  3013. // Pending "which hotend?" question, non-null only while the dialog is open.
  3014. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3015. // load command has to name one — see FeedDirectionModal.
  3016. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3017. trayId: number;
  3018. amsId: number;
  3019. slotId: number;
  3020. slotLabel: string;
  3021. } | null>(null);
  3022. // Whether a load from this printer has to ask which hotend to feed.
  3023. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3024. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3025. // The external holder needs no question: its two tray ids name the side
  3026. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3027. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3028. // external spool, because it would occupy an extruder channel permanently.
  3029. //
  3030. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3031. // carries does not address an HT unit, so the load is refused whatever the
  3032. // answer. Asking first would only put a dialog in front of the same error.
  3033. const isExternal = amsId === 255;
  3034. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3035. loadAmsTrayMutation.mutate({ trayId });
  3036. return;
  3037. }
  3038. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3039. // front rather than sending a command the firmware will drop. BambuStudio
  3040. // shows the same message and returns without publishing anything.
  3041. if (!status?.fila_switch?.ready) {
  3042. showToast(t('printers.ams.switchNotReady'), 'warning');
  3043. return;
  3044. }
  3045. setFeedDirectionRequest({
  3046. trayId,
  3047. amsId,
  3048. slotId,
  3049. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3050. });
  3051. };
  3052. // Plate references state
  3053. const [plateReferences, setPlateReferences] = useState<{
  3054. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3055. max_references: number;
  3056. } | null>(null);
  3057. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3058. // Fetch plate references
  3059. const fetchPlateReferences = async () => {
  3060. try {
  3061. const data = await api.getPlateReferences(printer.id);
  3062. setPlateReferences(data);
  3063. } catch {
  3064. // Ignore errors - references will show as empty
  3065. }
  3066. };
  3067. // Toggle plate detection enabled/disabled
  3068. const handleTogglePlateDetection = () => {
  3069. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3070. };
  3071. // Open plate detection management modal (for calibration/references)
  3072. const handleOpenPlateManagement = async () => {
  3073. setIsCheckingPlate(true);
  3074. setPlateCheckResult(null);
  3075. // Auto-turn on light if it's off
  3076. const lightWasOff = status?.chamber_light === false;
  3077. setPlateCheckLightWasOff(lightWasOff);
  3078. if (lightWasOff) {
  3079. await api.setChamberLight(printer.id, true);
  3080. // Wait for light to physically turn on and camera to adjust exposure
  3081. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3082. await new Promise(resolve => setTimeout(resolve, 2500));
  3083. }
  3084. try {
  3085. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3086. setPlateCheckResult(result);
  3087. fetchPlateReferences();
  3088. } catch (error) {
  3089. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3090. // Restore light if check failed
  3091. if (lightWasOff) {
  3092. await api.setChamberLight(printer.id, false);
  3093. setPlateCheckLightWasOff(false);
  3094. }
  3095. } finally {
  3096. setIsCheckingPlate(false);
  3097. }
  3098. };
  3099. // Close plate check modal and restore light state
  3100. const closePlateCheckModal = useCallback(async () => {
  3101. setPlateCheckResult(null);
  3102. // Restore light to original state if we turned it on
  3103. if (plateCheckLightWasOff) {
  3104. await api.setChamberLight(printer.id, false);
  3105. setPlateCheckLightWasOff(false);
  3106. }
  3107. }, [plateCheckLightWasOff, printer.id]);
  3108. // Calibrate plate detection handler
  3109. const handleCalibratePlate = async (label?: string) => {
  3110. setIsCalibrating(true);
  3111. try {
  3112. const result = await api.calibratePlateDetection(printer.id, { label });
  3113. if (result.success) {
  3114. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3115. // Refresh references and re-check
  3116. fetchPlateReferences();
  3117. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3118. setPlateCheckResult(checkResult);
  3119. } else {
  3120. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3121. }
  3122. } catch (error) {
  3123. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3124. } finally {
  3125. setIsCalibrating(false);
  3126. }
  3127. };
  3128. // Update reference label
  3129. const handleUpdateRefLabel = async (index: number, label: string) => {
  3130. try {
  3131. await api.updatePlateReferenceLabel(printer.id, index, label);
  3132. setEditingRefLabel(null);
  3133. fetchPlateReferences();
  3134. } catch (error) {
  3135. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3136. }
  3137. };
  3138. // Delete reference
  3139. const handleDeleteRef = async (index: number) => {
  3140. try {
  3141. await api.deletePlateReference(printer.id, index);
  3142. showToast(t('printers.toast.referenceDeleted'), 'success');
  3143. fetchPlateReferences();
  3144. // Re-check to update counts
  3145. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3146. setPlateCheckResult(checkResult);
  3147. } catch (error) {
  3148. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3149. }
  3150. };
  3151. // Save ROI settings
  3152. const handleSaveRoi = async () => {
  3153. if (!editingRoi) return;
  3154. setIsSavingRoi(true);
  3155. try {
  3156. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3157. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3158. setEditingRoi(null);
  3159. // Re-check to see new ROI in action
  3160. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3161. setPlateCheckResult(checkResult);
  3162. } catch (error) {
  3163. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3164. } finally {
  3165. setIsSavingRoi(false);
  3166. }
  3167. };
  3168. // Close plate check modal on Escape key
  3169. useEffect(() => {
  3170. const handleEscape = (e: KeyboardEvent) => {
  3171. if (e.key === 'Escape' && plateCheckResult) {
  3172. closePlateCheckModal();
  3173. }
  3174. };
  3175. window.addEventListener('keydown', handleEscape);
  3176. return () => window.removeEventListener('keydown', handleEscape);
  3177. }, [plateCheckResult, closePlateCheckModal]);
  3178. // Watch ams_status_main to detect when RFID read completes
  3179. // ams_status_main: 0=idle, 2=rfid_identifying
  3180. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3181. useEffect(() => {
  3182. if (!refreshingSlot) return;
  3183. const amsStatus = status?.ams_status_main ?? 0;
  3184. // Track when we see non-idle state (printer is working)
  3185. if (amsStatus !== 0) {
  3186. seenBusyStateRef.current = true;
  3187. // Cancel any deferred clear since we're back to busy
  3188. if (deferredClearRef.current) {
  3189. clearTimeout(deferredClearRef.current);
  3190. deferredClearRef.current = null;
  3191. }
  3192. }
  3193. // When we've seen busy and now idle, clear (with min time check)
  3194. if (seenBusyStateRef.current && amsStatus === 0) {
  3195. if (minTimePassedRef.current) {
  3196. // Min time passed - clear now
  3197. if (refreshTimeoutRef.current) {
  3198. clearTimeout(refreshTimeoutRef.current);
  3199. }
  3200. setRefreshingSlot(null);
  3201. } else {
  3202. // Schedule clear after min time (2 seconds from start)
  3203. if (!deferredClearRef.current) {
  3204. deferredClearRef.current = setTimeout(() => {
  3205. if (refreshTimeoutRef.current) {
  3206. clearTimeout(refreshTimeoutRef.current);
  3207. }
  3208. setRefreshingSlot(null);
  3209. }, 2000);
  3210. }
  3211. }
  3212. }
  3213. return () => {
  3214. if (deferredClearRef.current) {
  3215. clearTimeout(deferredClearRef.current);
  3216. }
  3217. };
  3218. }, [status?.ams_status_main, refreshingSlot]);
  3219. useEffect(() => {
  3220. if (!showMenu) return;
  3221. const handleClickOutside = (event: MouseEvent) => {
  3222. const target = event.target as Node;
  3223. if (!printerActionsMenuRef.current?.contains(target)) {
  3224. setShowMenu(false);
  3225. }
  3226. };
  3227. document.addEventListener('mousedown', handleClickOutside);
  3228. return () => document.removeEventListener('mousedown', handleClickOutside);
  3229. }, [showMenu]);
  3230. if (shouldHide) {
  3231. return null;
  3232. }
  3233. // Size-based styling helpers
  3234. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3235. // width, its thumbnail and the printer name, but every label inside the
  3236. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3237. // S one -- the disparity was worst exactly where someone asking for more
  3238. // room ends up. These custom properties carry the scaled sizes into the
  3239. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3240. // unless they reach for a size that is already asking for more space.
  3241. // Plain computation rather than useMemo: this sits after the card's early
  3242. // returns, where a hook would break the rules-of-hooks ordering, and
  3243. // building ten strings per render costs nothing.
  3244. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3245. const getImageSize = () => {
  3246. switch (cardSize) {
  3247. case 1: return 'w-10 h-10';
  3248. case 2: return 'w-14 h-14';
  3249. case 3: return 'w-16 h-16';
  3250. case 4: return 'w-20 h-20';
  3251. default: return 'w-14 h-14';
  3252. }
  3253. };
  3254. const getTitleSize = () => {
  3255. switch (cardSize) {
  3256. case 1: return 'text-base truncate';
  3257. case 2: return 'text-lg';
  3258. case 3: return 'text-xl';
  3259. case 4: return 'text-2xl';
  3260. default: return 'text-lg';
  3261. }
  3262. };
  3263. const getSpacing = () => {
  3264. switch (cardSize) {
  3265. case 1: return 'mb-2';
  3266. case 2: return 'mb-4';
  3267. case 3: return 'mb-5';
  3268. case 4: return 'mb-6';
  3269. default: return 'mb-4';
  3270. }
  3271. };
  3272. // A dropped file always becomes a queue item, so a printer that is busy,
  3273. // offline or mid-drying is no reason to refuse the drop — it only means the
  3274. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3275. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3276. // what this would have done for them.
  3277. //
  3278. // What remains is what the flow actually performs: upload the file, then
  3279. // create a queue item. It never touches printers:control, which is what this
  3280. // used to check — so someone holding that but neither of these had the file
  3281. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3282. // button below has always checked this pair.
  3283. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3284. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3285. // and the modal's own "will start later" toast cannot disagree.
  3286. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3287. const handleCardDragEnter = (e: React.DragEvent) => {
  3288. e.preventDefault();
  3289. dragCounterRef.current++;
  3290. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3291. };
  3292. const handleCardDragOver = (e: React.DragEvent) => {
  3293. e.preventDefault();
  3294. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3295. };
  3296. const handleCardDragLeave = (e: React.DragEvent) => {
  3297. e.preventDefault();
  3298. dragCounterRef.current--;
  3299. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3300. };
  3301. const handleCardDrop = async (e: React.DragEvent) => {
  3302. e.preventDefault();
  3303. dragCounterRef.current = 0;
  3304. setIsDraggingFile(false);
  3305. if (!canDrop) return;
  3306. const droppedFiles = Array.from(e.dataTransfer.files);
  3307. const file = droppedFiles[0];
  3308. if (!file) return;
  3309. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3310. const lower = file.name.toLowerCase();
  3311. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3312. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3313. return;
  3314. }
  3315. setIsDropUploading(true);
  3316. try {
  3317. const result = await api.uploadLibraryFile(file, null);
  3318. // Check printer compatibility if sliced_for_model is available in metadata
  3319. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3320. const printerModel = mapModelCode(printer.model);
  3321. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3322. await api.deleteLibraryFile(result.id).catch(() => {});
  3323. showToast(
  3324. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3325. 'error'
  3326. );
  3327. return;
  3328. }
  3329. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3330. } catch {
  3331. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3332. } finally {
  3333. setIsDropUploading(false);
  3334. }
  3335. };
  3336. const handleCardClick = (e: React.MouseEvent) => {
  3337. if (viewMode !== 'compact' || selectionMode) return;
  3338. const target = e.target as HTMLElement;
  3339. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3340. onOpenCompactCard?.(printer.id);
  3341. };
  3342. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3343. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3344. // Opening a camera in a given mode, without touching which mode is remembered
  3345. // -- the split button's two halves want the same action but disagree about
  3346. // whether the choice was deliberate enough to keep.
  3347. const openCameraIn = (mode: CameraViewMode) => {
  3348. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3349. onOpenEmbeddedCamera(printer.id, printer.name);
  3350. } else {
  3351. openCameraWindow(printer.id);
  3352. }
  3353. };
  3354. // Picking a mode both opens the camera that way and makes it the mode the
  3355. // plain icon uses from now on. A menu that only changed a preference would
  3356. // leave the user with a second click to do the thing they already asked for.
  3357. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3358. [
  3359. {
  3360. mode: 'window' as const,
  3361. icon: <ExternalLink className="w-4 h-4" />,
  3362. label: t('settings.newWindow'),
  3363. title: t('settings.cameraWindowDescription'),
  3364. },
  3365. {
  3366. mode: 'embedded' as const,
  3367. icon: <PictureInPicture2 className="w-4 h-4" />,
  3368. label: t('settings.embeddedOverlay'),
  3369. title: t('settings.cameraOverlayDescription'),
  3370. },
  3371. ]
  3372. ).map(({ mode, icon, label, title }) => ({
  3373. icon,
  3374. // The remembered mode is marked in the label itself: the icon slot already
  3375. // carries the mode's own icon, and a separate tick column would push both
  3376. // entries out of line with every other card menu.
  3377. label: mode === cameraViewMode ? `${label} ✓` : label,
  3378. title,
  3379. onClick: () => {
  3380. onSelectCameraViewMode?.(mode);
  3381. openCameraIn(mode);
  3382. },
  3383. }));
  3384. const renderAmsSlotActions = ({
  3385. amsId,
  3386. slotId,
  3387. loadTrayId,
  3388. isRefreshing,
  3389. includeRfid = true,
  3390. }: {
  3391. amsId: number;
  3392. slotId: number;
  3393. loadTrayId: number;
  3394. isRefreshing?: boolean;
  3395. includeRfid?: boolean;
  3396. }) => {
  3397. const printerBusy = status?.state === 'RUNNING';
  3398. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3399. // ams*4+slot, so the id this menu carries does not name it to the load and
  3400. // unload endpoints — they reject it. Sending no slot falls back to the
  3401. // printer-wide unload, which is what this menu did for every slot before
  3402. // the per-slot form existed. Load has never worked on an HT slot for the
  3403. // same addressing reason; fixing that is a separate change.
  3404. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3405. return (
  3406. <>
  3407. {includeRfid && (
  3408. <button
  3409. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3410. hasPermission('printers:ams_rfid')
  3411. ? 'text-white hover:bg-bambu-dark-tertiary'
  3412. : 'text-bambu-gray/50 cursor-not-allowed'
  3413. }`}
  3414. onClick={(e) => {
  3415. e.stopPropagation();
  3416. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3417. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3418. }}
  3419. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3420. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3421. >
  3422. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3423. {t('printers.rfid.reread')}
  3424. </button>
  3425. )}
  3426. <button
  3427. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3428. hasPermission('printers:control')
  3429. ? 'text-white hover:bg-bambu-dark-tertiary'
  3430. : 'text-bambu-gray/50 cursor-not-allowed'
  3431. }`}
  3432. onClick={(e) => {
  3433. e.stopPropagation();
  3434. if (printerBusy || !hasPermission('printers:control')) return;
  3435. startAmsLoad(amsId, slotId, loadTrayId);
  3436. }}
  3437. disabled={printerBusy || !hasPermission('printers:control')}
  3438. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3439. >
  3440. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3441. {t('printers.ams.load')}
  3442. </button>
  3443. <button
  3444. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3445. hasPermission('printers:control')
  3446. ? 'text-white hover:bg-bambu-dark-tertiary'
  3447. : 'text-bambu-gray/50 cursor-not-allowed'
  3448. }`}
  3449. onClick={(e) => {
  3450. e.stopPropagation();
  3451. if (printerBusy || !hasPermission('printers:control')) return;
  3452. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3453. }}
  3454. disabled={printerBusy || !hasPermission('printers:control')}
  3455. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3456. >
  3457. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3458. {t('printers.ams.unload')}
  3459. </button>
  3460. </>
  3461. );
  3462. };
  3463. const printerActionsMenu = (
  3464. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3465. <Button
  3466. variant="secondary"
  3467. size="sm"
  3468. onClick={() => setShowMenu(!showMenu)}
  3469. title={t('common.more', 'More')}
  3470. className={footerIconButtonClass}
  3471. >
  3472. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3473. </Button>
  3474. {showMenu && (
  3475. <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">
  3476. <button
  3477. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3478. hasPermission('printers:update')
  3479. ? 'hover:bg-bambu-dark-tertiary'
  3480. : 'opacity-50 cursor-not-allowed'
  3481. }`}
  3482. onClick={() => {
  3483. if (!hasPermission('printers:update')) return;
  3484. setShowEditModal(true);
  3485. setShowMenu(false);
  3486. }}
  3487. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3488. >
  3489. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3490. {t('common.edit')}
  3491. </button>
  3492. <button
  3493. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3494. onClick={() => {
  3495. setShowPrinterInfo(true);
  3496. setShowMenu(false);
  3497. }}
  3498. >
  3499. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3500. {t('printers.printerInformation')}
  3501. </button>
  3502. {authEnabled && isAdmin && (
  3503. <button
  3504. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3505. onClick={() => {
  3506. setShowMenu(false);
  3507. navigate(`/settings?tab=users&sub=printer-access&view=printers&printer=${printer.id}`);
  3508. }}
  3509. >
  3510. <KeyRound className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3511. {t('printerAccess.whoHasAccess')}
  3512. </button>
  3513. )}
  3514. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3515. <button
  3516. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3517. hasPermission('printers:update')
  3518. ? 'hover:bg-bambu-dark-tertiary'
  3519. : 'opacity-50 cursor-not-allowed'
  3520. }`}
  3521. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3522. onClick={() => {
  3523. if (!hasPermission('printers:update')) return;
  3524. setShowMenu(false);
  3525. if (printer.is_active !== false) {
  3526. handleEnterMaintenance();
  3527. } else {
  3528. maintenanceMutation.mutate(true);
  3529. }
  3530. }}
  3531. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3532. >
  3533. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3534. {printer.is_active !== false
  3535. ? t('printers.maintenance.menuEnter')
  3536. : t('printers.maintenance.menuExit')}
  3537. </button>
  3538. <button
  3539. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3540. onClick={() => {
  3541. connectMutation.mutate();
  3542. setShowMenu(false);
  3543. }}
  3544. >
  3545. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3546. {t('printers.reconnect')}
  3547. </button>
  3548. <button
  3549. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3550. disabled={forceRefreshMutation.isPending}
  3551. onClick={() => {
  3552. forceRefreshMutation.mutate();
  3553. setShowMenu(false);
  3554. }}
  3555. >
  3556. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3557. {t('printers.forceRefresh')}
  3558. </button>
  3559. <button
  3560. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3561. onClick={() => {
  3562. setShowMQTTDebug(true);
  3563. setShowMenu(false);
  3564. }}
  3565. >
  3566. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3567. {t('printers.mqttDebug')}
  3568. </button>
  3569. <button
  3570. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3571. onClick={() => {
  3572. setShowDiagnostic(true);
  3573. setShowMenu(false);
  3574. }}
  3575. >
  3576. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3577. {t('diagnostic.runButton')}
  3578. </button>
  3579. <button
  3580. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3581. hasPermission('printers:delete')
  3582. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3583. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3584. }`}
  3585. onClick={() => {
  3586. if (!hasPermission('printers:delete')) return;
  3587. setShowDeleteConfirm(true);
  3588. setShowMenu(false);
  3589. }}
  3590. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3591. >
  3592. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3593. {t('common.delete')}
  3594. </button>
  3595. </div>
  3596. )}
  3597. </div>
  3598. );
  3599. return (
  3600. <Card
  3601. id={`printer-card-${printer.id}`}
  3602. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3603. style={cardScaleStyle}
  3604. onClick={handleCardClick}
  3605. onDragEnter={handleCardDragEnter}
  3606. onDragOver={handleCardDragOver}
  3607. onDragLeave={handleCardDragLeave}
  3608. onDrop={handleCardDrop}
  3609. >
  3610. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3611. {selectionMode && (
  3612. <div
  3613. className="absolute inset-0 z-20 flex items-start p-2"
  3614. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3615. >
  3616. {isSelected ? (
  3617. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3618. ) : (
  3619. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3620. )}
  3621. </div>
  3622. )}
  3623. {/* Drop zone overlay */}
  3624. {(isDraggingFile || isDropUploading) && (
  3625. <div
  3626. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3627. isDropUploading
  3628. ? 'bg-bambu-green/10 border-bambu-green/50'
  3629. : canDrop
  3630. ? 'bg-bambu-green/10 border-bambu-green'
  3631. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3632. }`}
  3633. >
  3634. <div className="text-center">
  3635. {isDropUploading ? (
  3636. <>
  3637. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3638. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3639. </>
  3640. ) : canDrop ? (
  3641. <>
  3642. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3643. <p className="text-sm font-medium text-bambu-green">
  3644. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3645. </p>
  3646. </>
  3647. ) : (
  3648. <>
  3649. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3650. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3651. {!hasPermission('library:upload')
  3652. ? t('fileManager.noPermissionUpload')
  3653. : t('fileManager.noPermissionAddToQueue')}
  3654. </p>
  3655. </>
  3656. )}
  3657. </div>
  3658. </div>
  3659. )}
  3660. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3661. {/* Header */}
  3662. <div className={getSpacing()}>
  3663. {/* Top row: Image, Name, Menu */}
  3664. <div className="flex items-start justify-between gap-2">
  3665. <div className="flex items-center gap-3 min-w-0 flex-1">
  3666. {/* Printer Model Image */}
  3667. <img
  3668. src={getPrinterImage(printer.model)}
  3669. alt={printer.model || t('common.printer')}
  3670. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3671. />
  3672. <div className="min-w-0 flex-1">
  3673. <div className="flex items-center justify-between gap-2">
  3674. <div className="flex min-w-0 items-center gap-2">
  3675. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3676. {/* Connection indicator dot for compact mode */}
  3677. {viewMode === 'compact' && (() => {
  3678. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3679. const hasSevere = hmsErrors.some(isSevereHMSError);
  3680. const hasWarning = hmsErrors.length > 0;
  3681. const pipColor = !status?.connected
  3682. ? 'bg-status-error'
  3683. : hasSevere
  3684. ? 'bg-status-error'
  3685. : hasWarning
  3686. ? 'bg-status-warning'
  3687. : 'bg-status-ok';
  3688. const pipTitle = !status?.connected
  3689. ? t('printers.connection.offline')
  3690. : hasWarning
  3691. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3692. : t('printers.connection.connected');
  3693. return (
  3694. <div
  3695. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3696. title={pipTitle}
  3697. />
  3698. );
  3699. })()}
  3700. </div>
  3701. {viewMode === 'compact' && showClearPlateButton && (
  3702. <button
  3703. type="button"
  3704. onClick={() => clearPlateMutation.mutate()}
  3705. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3706. aria-label={t('printers.plateStatus.markCleared')}
  3707. 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"
  3708. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3709. >
  3710. {clearPlateMutation.isPending ? (
  3711. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3712. ) : (
  3713. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3714. )}
  3715. </button>
  3716. )}
  3717. </div>
  3718. <p className="text-sm text-bambu-gray">
  3719. {printer.model || 'Unknown Model'}
  3720. {/* Nozzle Info - only in expanded. Every fitted size, not
  3721. just nozzles[0]: the array is indexed by extruder, so on a
  3722. dual-nozzle machine with two sizes fitted showing the
  3723. first entry alone named one hotend and implied it was the
  3724. whole printer. Deduplicated, so the usual matching pair
  3725. still reads as a single "0.4mm". */}
  3726. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3727. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3728. • {installedNozzleDiameters(status).join(' / ')}mm
  3729. </span>
  3730. )}
  3731. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3732. <span className="ml-2 text-bambu-gray">
  3733. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3734. {Math.round(maintenanceInfo.total_print_hours)}h
  3735. </span>
  3736. )}
  3737. </p>
  3738. </div>
  3739. </div>
  3740. </div>
  3741. {/* Badges row - only in expanded mode */}
  3742. {viewMode === 'expanded' && (
  3743. <div className="mt-2">
  3744. <div className="flex flex-wrap items-center gap-2">
  3745. {/* Connection status badge (or Maintenance pill when out of service).
  3746. Defensive: only swap when is_active is EXPLICITLY false. An
  3747. undefined / missing field defaults to "active" so the regular
  3748. pill renders — matches the backend default and prevents test
  3749. fixtures (or stale clients) from accidentally tripping the
  3750. maintenance UI. */}
  3751. {printer.is_active === false ? (
  3752. <span
  3753. 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"
  3754. title={t('printers.maintenance.subtitle')}
  3755. >
  3756. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3757. {t('printers.maintenance.pillLabel')}
  3758. </span>
  3759. ) : (
  3760. <span
  3761. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3762. status?.connected
  3763. ? 'bg-status-ok/20 text-status-ok'
  3764. : 'bg-status-error/20 text-status-error'
  3765. }`}
  3766. >
  3767. {status?.connected ? (
  3768. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3769. ) : (
  3770. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3771. )}
  3772. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3773. </span>
  3774. )}
  3775. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3776. {printer.is_active !== false && !status?.connected && (
  3777. <button
  3778. onClick={() => setShowDiagnostic(true)}
  3779. 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"
  3780. title={t('diagnostic.runButton')}
  3781. >
  3782. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3783. {t('diagnostic.runButton')}
  3784. </button>
  3785. )}
  3786. {/* Network connection indicator */}
  3787. {status?.connected && status?.wired_network && (
  3788. <span
  3789. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3790. title={t('printers.connection.ethernet', 'Ethernet')}
  3791. >
  3792. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3793. {t('printers.connection.ethernet', 'Ethernet')}
  3794. </span>
  3795. )}
  3796. {/* WiFi signal indicator */}
  3797. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3798. <span
  3799. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3800. wifiSignal >= -50
  3801. ? 'bg-status-ok/20 text-status-ok'
  3802. : wifiSignal >= -60
  3803. ? 'bg-status-ok/20 text-status-ok'
  3804. : wifiSignal >= -70
  3805. ? 'bg-status-warning/20 text-status-warning'
  3806. : wifiSignal >= -80
  3807. ? 'bg-orange-500/20 text-orange-600'
  3808. : 'bg-status-error/20 text-status-error'
  3809. }`}
  3810. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3811. >
  3812. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3813. {wifiSignal}dBm
  3814. </span>
  3815. )}
  3816. {/* HMS Status Indicator */}
  3817. {status?.connected && (() => {
  3818. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3819. return (
  3820. <button
  3821. onClick={() => setShowHMSModal(true)}
  3822. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3823. knownErrors.length > 0
  3824. ? knownErrors.some(isSevereHMSError)
  3825. ? 'bg-status-error/20 text-status-error'
  3826. : 'bg-status-warning/20 text-status-warning'
  3827. : 'bg-status-ok/20 text-status-ok'
  3828. }`}
  3829. title={t('printers.clickToViewHmsErrors')}
  3830. >
  3831. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3832. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3833. </button>
  3834. );
  3835. })()}
  3836. {/* AI failure detection badge (#1546) — always shown while detection
  3837. is enabled for this printer, like the other health badges. Gray
  3838. "Idle" outside a monitored print, class-colored during one. */}
  3839. {aiDetectionEnabled && (() => {
  3840. const cls = aiDetectionClass(aiDetection);
  3841. const colorClass =
  3842. cls === 'failure'
  3843. ? 'bg-status-error/20 text-status-error'
  3844. : cls === 'warning'
  3845. ? 'bg-status-warning/20 text-status-warning'
  3846. : cls === 'safe'
  3847. ? 'bg-status-ok/20 text-status-ok'
  3848. : cls === 'error'
  3849. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3850. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3851. // 'error' and 'unknown' have no score to quote — saying
  3852. // "Safe (0.000)" for a print nothing is looking at is the
  3853. // whole of #2952.
  3854. const title =
  3855. cls === 'error'
  3856. ? t('printers.aiDetection.tooltipError', {
  3857. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3858. })
  3859. : cls === 'unknown'
  3860. ? t('printers.aiDetection.tooltipUnknown')
  3861. : aiDetection
  3862. ? t('printers.aiDetection.tooltip', {
  3863. status: t(`printers.aiDetection.${cls}`),
  3864. score: aiDetection.score.toFixed(3),
  3865. })
  3866. : t('printers.aiDetection.tooltipIdle');
  3867. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3868. return (
  3869. <button
  3870. onClick={() => setShowAiModal(true)}
  3871. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3872. title={title}
  3873. >
  3874. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3875. {t(`printers.aiDetection.${cls}`)}
  3876. </button>
  3877. );
  3878. })()}
  3879. {/* Maintenance Status Indicator */}
  3880. {maintenanceInfo && (
  3881. <button
  3882. onClick={() => navigate('/maintenance')}
  3883. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3884. maintenanceInfo.due_count > 0
  3885. ? 'bg-status-error/20 text-status-error'
  3886. : maintenanceInfo.warning_count > 0
  3887. ? 'bg-status-warning/20 text-status-warning'
  3888. : 'bg-status-ok/20 text-status-ok'
  3889. }`}
  3890. title={
  3891. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3892. ? `${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`
  3893. : t('printers.maintenanceUpToDate')
  3894. }
  3895. >
  3896. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3897. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3898. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3899. : 'OK'}
  3900. </button>
  3901. )}
  3902. {/* Queue Count Badge */}
  3903. {queueCount > 0 && (
  3904. <button
  3905. onClick={() => navigate('/queue')}
  3906. 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"
  3907. title={t('printers.queue.inQueue', { count: queueCount })}
  3908. >
  3909. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3910. {queueCount}
  3911. </button>
  3912. )}
  3913. {/* Firmware Version Badge */}
  3914. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3915. <button
  3916. onClick={() => setShowFirmwareModal(true)}
  3917. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3918. firmwareInfo.update_available
  3919. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3920. : 'bg-status-ok/20 text-status-ok'
  3921. }`}
  3922. title={
  3923. firmwareInfo.update_available
  3924. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3925. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3926. }
  3927. >
  3928. {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)]" />}
  3929. {firmwareInfo.current_version}
  3930. </button>
  3931. ) : status?.firmware_version ? (
  3932. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3933. {status.firmware_version}
  3934. </span>
  3935. ) : null}
  3936. {/* Enclosure Door Badge — models with an actual door sensor.
  3937. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3938. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3939. <span
  3940. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3941. status.door_open
  3942. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3943. : 'bg-status-ok/20 text-status-ok'
  3944. }`}
  3945. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3946. >
  3947. {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)]" />}
  3948. </span>
  3949. )}
  3950. </div>
  3951. </div>
  3952. )}
  3953. </div>
  3954. {/* Delete Confirmation */}
  3955. {showDeleteConfirm && (
  3956. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3957. <Card className="w-full max-w-md mx-4">
  3958. <CardContent>
  3959. <div className="flex items-start gap-3 mb-4">
  3960. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3961. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3962. </div>
  3963. <div>
  3964. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3965. <p className="text-sm text-bambu-gray mt-1">
  3966. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3967. </p>
  3968. </div>
  3969. </div>
  3970. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3971. <label className="flex items-start gap-3 cursor-pointer">
  3972. <input
  3973. type="checkbox"
  3974. checked={deleteArchives}
  3975. onChange={(e) => setDeleteArchives(e.target.checked)}
  3976. 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"
  3977. />
  3978. <div>
  3979. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3980. <p className="text-xs text-bambu-gray mt-0.5">
  3981. {deleteArchives
  3982. ? t('printers.confirm.deleteArchivesNote')
  3983. : t('printers.confirm.keepArchivesNote')}
  3984. </p>
  3985. </div>
  3986. </label>
  3987. </div>
  3988. <div className="flex justify-end gap-2">
  3989. <Button
  3990. variant="secondary"
  3991. onClick={() => {
  3992. setShowDeleteConfirm(false);
  3993. setDeleteArchives(true);
  3994. }}
  3995. >
  3996. {t('common.cancel')}
  3997. </Button>
  3998. <Button
  3999. variant="danger"
  4000. onClick={() => {
  4001. deleteMutation.mutate({ deleteArchives });
  4002. setShowDeleteConfirm(false);
  4003. setDeleteArchives(true);
  4004. }}
  4005. >
  4006. Delete
  4007. </Button>
  4008. </div>
  4009. </CardContent>
  4010. </Card>
  4011. </div>
  4012. )}
  4013. {/* Status — see the equivalent defensive `=== false` check on the
  4014. header pill above for why this is not `!printer.is_active`. */}
  4015. {printer.is_active === false ? (
  4016. // Maintenance mode (#1476) — replaces the cover/progress container
  4017. // so the card keeps the same height. Renders for both compact and
  4018. // expanded view modes so the printer stays visible but plainly
  4019. // out-of-service.
  4020. <>
  4021. {viewMode === 'compact' ? (
  4022. <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">
  4023. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4024. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4025. {t('printers.maintenance.pillLabel')}
  4026. </span>
  4027. </div>
  4028. ) : (
  4029. <>
  4030. <div className="flex items-center gap-2 mb-2">
  4031. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4032. {t('printers.status.title', 'Status')}
  4033. </span>
  4034. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4035. </div>
  4036. <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">
  4037. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4038. <div className="flex-1 min-w-0">
  4039. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4040. {t('printers.maintenance.title')}
  4041. </p>
  4042. <p className="text-xs text-bambu-gray mt-0.5">
  4043. {t('printers.maintenance.subtitle')}
  4044. </p>
  4045. </div>
  4046. <Button
  4047. variant="secondary"
  4048. size="sm"
  4049. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4050. onClick={() => maintenanceMutation.mutate(true)}
  4051. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4052. >
  4053. {t('printers.maintenance.exitButton')}
  4054. </Button>
  4055. </div>
  4056. </>
  4057. )}
  4058. </>
  4059. ) : status?.connected && (
  4060. <>
  4061. {/* Compact: Simple status bar */}
  4062. {viewMode === 'compact' ? (
  4063. (() => {
  4064. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4065. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4066. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4067. ? Math.max(0, Math.min(100, status.progress || 0))
  4068. : showClearPlateButton
  4069. ? 100
  4070. : hasProblem
  4071. ? 100
  4072. : 0;
  4073. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4074. const compactProgressClass = hasProblem
  4075. ? 'bg-status-error'
  4076. : status.state === 'PAUSE'
  4077. ? 'bg-status-warning'
  4078. : 'bg-bambu-green';
  4079. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4080. const hasCompactLayers =
  4081. isActiveCompactPrint &&
  4082. status.layer_num != null &&
  4083. status.total_layers != null &&
  4084. status.total_layers > 0;
  4085. return (
  4086. <>
  4087. <div className="relative mt-2 flex items-center gap-2">
  4088. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4089. <div
  4090. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4091. style={{ width: `${compactProgress}%` }}
  4092. />
  4093. </div>
  4094. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4095. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4096. </span>
  4097. </div>
  4098. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4099. enough to answer "which printer finishes first", which is what a
  4100. wall-mounted fleet view is for. One line of the metrics the
  4101. expanded card already renders, using the same formatters and the
  4102. same ETA styling so S and M read alike. The row keeps its height
  4103. when idle so cards don't shift as prints start and stop. */}
  4104. <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">
  4105. {hasCompactEta && (
  4106. <>
  4107. <span className="flex shrink-0 items-center gap-1">
  4108. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4109. {formatDuration(status.remaining_time! * 60)}
  4110. </span>
  4111. <span
  4112. className="shrink-0 font-medium text-bambu-green"
  4113. title={t('printers.estimatedCompletion')}
  4114. >
  4115. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4116. </span>
  4117. </>
  4118. )}
  4119. {hasCompactLayers && (
  4120. <span className="flex min-w-0 items-center gap-1 truncate">
  4121. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4122. {status.layer_num}/{status.total_layers}
  4123. </span>
  4124. )}
  4125. </div>
  4126. </>
  4127. );
  4128. })()
  4129. ) : (
  4130. /* Expanded: Full status section */
  4131. <>
  4132. <div className="flex items-center gap-2 mb-2">
  4133. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4134. {t('printers.status.title', 'Status')}
  4135. </span>
  4136. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4137. </div>
  4138. {/* Current Print or Idle Placeholder */}
  4139. {(() => {
  4140. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4141. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4142. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4143. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4144. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4145. // A running print always has at least one object, so a count of
  4146. // zero means "not loaded", not "nothing to skip" — after a
  4147. // restart mid-print the list is empty until something rebuilds
  4148. // it. Treating that as nothing-to-skip disabled the only
  4149. // control that opens the modal, and the modal's own fetch is
  4150. // what rebuilds the list, so the print could never get it back.
  4151. // Exactly one object is the real nothing-to-skip case.
  4152. const objectCount = status.printable_objects_count ?? 0;
  4153. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4154. return (
  4155. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4156. <button
  4157. onClick={() => setShowSkipObjectsModal(true)}
  4158. disabled={!canSkipObjects}
  4159. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4160. canSkipObjects
  4161. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4162. : 'text-bambu-gray/30 cursor-not-allowed'
  4163. }`}
  4164. title={
  4165. !hasPermission('printers:control')
  4166. ? t('printers.permission.noControl')
  4167. : !isActivePrint
  4168. ? t('printers.skipObjects.onlyWhilePrinting')
  4169. : objectCount === 1
  4170. ? t('printers.skipObjects.requiresMultiple')
  4171. : t('printers.skipObjects.tooltip')
  4172. }
  4173. >
  4174. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4175. {objectsData && objectsData.skipped_count > 0 && (
  4176. <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">
  4177. {objectsData.skipped_count}
  4178. </span>
  4179. )}
  4180. </button>
  4181. <div className="flex items-stretch gap-2">
  4182. <CoverImage
  4183. url={coverUrl}
  4184. printName={printName || undefined}
  4185. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4186. />
  4187. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4188. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4189. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4190. {plateStatusPill}
  4191. </div>
  4192. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4193. {printName || t('printers.noActiveJob', 'No active job')}
  4194. </p>
  4195. <div className="flex h-3 items-center gap-2 text-sm">
  4196. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4197. <div
  4198. 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`}
  4199. style={{ width: `${progress}%` }}
  4200. />
  4201. </div>
  4202. <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>
  4203. </div>
  4204. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4205. {isActivePrint ? (
  4206. <>
  4207. {status.remaining_time != null && status.remaining_time > 0 && (
  4208. <>
  4209. <span className="flex items-center gap-1">
  4210. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4211. {formatDuration(status.remaining_time * 60)}
  4212. </span>
  4213. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4214. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4215. </span>
  4216. </>
  4217. )}
  4218. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4219. <span className="flex items-center gap-1">
  4220. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4221. {status.layer_num}/{status.total_layers}
  4222. </span>
  4223. )}
  4224. {currentPrintUser && (
  4225. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4226. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4227. {currentPrintUser}
  4228. </span>
  4229. )}
  4230. </>
  4231. ) : lastPrint ? (
  4232. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4233. Last: {lastPrint.print_name || lastPrint.filename}
  4234. {lastPrint.completed_at && (
  4235. <span className="ml-1 text-bambu-gray/60">
  4236. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4237. </span>
  4238. )}
  4239. </p>
  4240. ) : (
  4241. <span>{t('printers.readyToPrint')}</span>
  4242. )}
  4243. </div>
  4244. </div>
  4245. </div>
  4246. <PrinterQueueWidget
  4247. printerId={printer.id}
  4248. printerModel={printer.model}
  4249. loadedFilamentTypes={loadedFilamentTypes}
  4250. loadedFilaments={loadedFilaments}
  4251. loadedVariants={loadedVariants}
  4252. variant="panelExtension"
  4253. />
  4254. </div>
  4255. );
  4256. })()}
  4257. </>
  4258. )}
  4259. {/* Temperatures */}
  4260. {status.temperatures && viewMode === 'expanded' && (() => {
  4261. // Use actual heater states from MQTT stream
  4262. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4263. const bedHeating = status.temperatures.bed_heating || false;
  4264. const chamberHeating = status.temperatures.chamber_heating || false;
  4265. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4266. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4267. const kinds: HeaterSensorKind[] = ['nozzle'];
  4268. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4269. kinds.push('bed');
  4270. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4271. return kinds;
  4272. })();
  4273. // active_extruder: 0=right, 1=left
  4274. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4275. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4276. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4277. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4278. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4279. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4280. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4281. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4282. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4283. 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 ${
  4284. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4285. }`;
  4286. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4287. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4288. // the widget there is at best dead UI and at worst suggests a
  4289. // control that does nothing. Mirrors the enclosure-door badge
  4290. // gate above.
  4291. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4292. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4293. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4294. // show it only when the printer actually reports it (airduct part id 3,
  4295. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4296. // have a built-in chamber fan that's always present, so they keep the
  4297. // existing model-list gate and the "Chamber Fan" label.
  4298. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4299. const chamberFanLabel = isExhaustModel
  4300. ? t('printers.fans.exhaust')
  4301. : t('printers.fans.chamber');
  4302. // Composed rather than either/or so both lists stay live for
  4303. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4304. // where that fan is an add-on kit — actually report it. Written
  4305. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4306. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4307. // which reads as if removing them were safe.
  4308. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4309. const fanItems: {
  4310. key: string;
  4311. label: string;
  4312. value: number;
  4313. Icon: typeof Fan;
  4314. activeClass: string;
  4315. }[] = [
  4316. {
  4317. key: 'part',
  4318. label: t('printers.fans.partCooling'),
  4319. value: status.cooling_fan_speed ?? 0,
  4320. Icon: Fan,
  4321. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4322. },
  4323. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4324. // Only reported (non-null) when the firmware lists airduct part
  4325. // id 10, i.e. when the fan is physically installed. Placed
  4326. // before the right-hand auxiliary fan so the two aux badges read
  4327. // left-to-right in the same order as the physical hardware.
  4328. ...(status.left_aux_fan_speed != null
  4329. ? [
  4330. {
  4331. key: 'aux2',
  4332. label: t('printers.fans.leftAuxiliary'),
  4333. value: status.left_aux_fan_speed,
  4334. Icon: Wind,
  4335. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4336. },
  4337. ]
  4338. : []),
  4339. {
  4340. key: 'aux',
  4341. label: t('printers.fans.auxiliary'),
  4342. value: status.big_fan1_speed ?? 0,
  4343. Icon: Wind,
  4344. activeClass: 'text-blue-600 dark:text-blue-400',
  4345. },
  4346. ...(showChamberFan
  4347. ? [
  4348. {
  4349. key: 'chamber',
  4350. label: chamberFanLabel,
  4351. value: status.big_fan2_speed ?? 0,
  4352. Icon: AirVent,
  4353. activeClass: 'text-green-600 dark:text-green-400',
  4354. },
  4355. ]
  4356. : []),
  4357. ];
  4358. return (
  4359. <>
  4360. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4361. {/* Nozzle temp - combined for dual nozzle */}
  4362. <div
  4363. className={statusControlClass}
  4364. title={statusControlTitle}
  4365. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4366. >
  4367. <button
  4368. type="button"
  4369. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4370. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4371. onClick={(e) => {
  4372. e.stopPropagation();
  4373. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4374. }}
  4375. >
  4376. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4377. </button>
  4378. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4379. {status.temperatures.nozzle_2 !== undefined ? (
  4380. <>
  4381. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4382. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4383. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4384. </p>
  4385. </>
  4386. ) : singleNozzleSlot ? (
  4387. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4388. <div className="cursor-default">
  4389. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4390. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4391. {Math.round(status.temperatures.nozzle || 0)}°C
  4392. </p>
  4393. </div>
  4394. </NozzleSlotHoverCard>
  4395. ) : (
  4396. <>
  4397. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4398. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4399. {Math.round(status.temperatures.nozzle || 0)}°C
  4400. </p>
  4401. </>
  4402. )}
  4403. {statusControlMenu === 'nozzle-temp' && (
  4404. isDualNozzle ? (
  4405. <IndicatorControlPopover
  4406. title="Set Nozzle Temperatures"
  4407. widthClass="w-[300px]"
  4408. popoverWidth={300}
  4409. popoverHeight={260}
  4410. isPending={nozzleTemperatureMutation.isPending}
  4411. onClose={() => setStatusControlMenu(null)}
  4412. >
  4413. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4414. <NozzleTemperatureControlBox
  4415. label="Left Temp"
  4416. current={status.temperatures.nozzle}
  4417. target={status.temperatures.nozzle_target}
  4418. isActive={activeNozzle === 'L'}
  4419. isPending={nozzleTemperatureMutation.isPending}
  4420. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4421. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4422. />
  4423. <NozzleTemperatureControlBox
  4424. label="Right Temp"
  4425. current={status.temperatures.nozzle_2}
  4426. target={status.temperatures.nozzle_2_target}
  4427. isActive={activeNozzle === 'R'}
  4428. isPending={nozzleTemperatureMutation.isPending}
  4429. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4430. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4431. />
  4432. </div>
  4433. </IndicatorControlPopover>
  4434. ) : (
  4435. <IndicatorControlPopover
  4436. title="Set Nozzle Temperature"
  4437. unit="°C"
  4438. customMin={0}
  4439. customMax={320}
  4440. isPending={nozzleTemperatureMutation.isPending}
  4441. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4442. onClose={() => setStatusControlMenu(null)}
  4443. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4444. />
  4445. )
  4446. )}
  4447. </div>
  4448. <div
  4449. className={statusControlClass}
  4450. title={statusControlTitle}
  4451. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4452. >
  4453. <button
  4454. type="button"
  4455. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4456. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4457. onClick={(e) => {
  4458. e.stopPropagation();
  4459. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4460. }}
  4461. >
  4462. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4463. </button>
  4464. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4465. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4466. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4467. {Math.round(status.temperatures.bed || 0)}°C
  4468. </p>
  4469. {statusControlMenu === 'bed-temp' && (
  4470. <IndicatorControlPopover
  4471. title="Set Bed Temperature"
  4472. unit="°C"
  4473. customMin={0}
  4474. customMax={140}
  4475. isPending={bedTemperatureMutation.isPending}
  4476. options={buildPresetOptions(bedTempPresets, 'C')}
  4477. onClose={() => setStatusControlMenu(null)}
  4478. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4479. />
  4480. )}
  4481. </div>
  4482. {status.temperatures.chamber !== undefined && (() => {
  4483. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4484. // but can't act on M141, so we keep the card read-only there.
  4485. const hasChamberHeater = status.supports_chamber_heater === true;
  4486. return (
  4487. <div
  4488. className={hasChamberHeater
  4489. ? statusControlClass
  4490. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4491. title={hasChamberHeater ? statusControlTitle : undefined}
  4492. onClick={hasChamberHeater
  4493. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4494. : undefined}
  4495. >
  4496. <button
  4497. type="button"
  4498. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4499. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4500. onClick={(e) => {
  4501. e.stopPropagation();
  4502. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4503. }}
  4504. >
  4505. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4506. </button>
  4507. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4508. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4509. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4510. {Math.round(status.temperatures.chamber || 0)}°C
  4511. </p>
  4512. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4513. <IndicatorControlPopover
  4514. title="Set Chamber Temperature"
  4515. unit="°C"
  4516. customMin={0}
  4517. customMax={MAX_CHAMBER_TEMP_C}
  4518. isPending={chamberTemperatureMutation.isPending}
  4519. options={buildPresetOptions(chamberTempPresets, 'C')}
  4520. onClose={() => setStatusControlMenu(null)}
  4521. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4522. />
  4523. )}
  4524. </div>
  4525. );
  4526. })()}
  4527. {/* Active nozzle indicator for dual-nozzle printers */}
  4528. {isDualNozzle && (
  4529. <DualNozzleHoverCard
  4530. leftSlot={leftNozzleSlot}
  4531. rightSlot={rightNozzleSlot}
  4532. activeNozzle={activeNozzle}
  4533. filamentInfo={filamentInfo}
  4534. >
  4535. <div
  4536. 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 ${
  4537. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4538. }`}
  4539. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4540. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4541. >
  4542. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4543. <div className="flex items-center gap-2">
  4544. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4545. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4546. </span>
  4547. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4548. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4549. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4550. </span>
  4551. </div>
  4552. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4553. {statusControlMenu === 'nozzle-select' && (
  4554. <IndicatorControlPopover
  4555. title="Set Nozzle Selection"
  4556. widthClass="w-[300px]"
  4557. popoverWidth={300}
  4558. popoverHeight={140}
  4559. isPending={selectExtruderMutation.isPending}
  4560. options={[
  4561. { label: 'Left', value: 1 },
  4562. { label: 'Right', value: 0 },
  4563. ]}
  4564. onClose={() => setStatusControlMenu(null)}
  4565. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4566. />
  4567. )}
  4568. </div>
  4569. </DualNozzleHoverCard>
  4570. )}
  4571. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4572. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4573. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4574. )}
  4575. </div>
  4576. <div className="mt-2 flex items-center gap-1.5">
  4577. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4578. const active = value > 0;
  4579. return (
  4580. <div
  4581. key={key}
  4582. 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 ${
  4583. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4584. }`}
  4585. title={canUseStatusControls ? label : statusControlTitle}
  4586. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4587. >
  4588. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4589. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4590. {value}%
  4591. </span>
  4592. {statusControlMenu === `fan-${key}` && (
  4593. <IndicatorControlPopover
  4594. title={`Set ${label} Speed`}
  4595. unit="%"
  4596. customMin={0}
  4597. customMax={100}
  4598. isPending={fanSpeedMutation.isPending}
  4599. options={buildPresetOptions(fanSpeedPresets, '%')}
  4600. onClose={() => setStatusControlMenu(null)}
  4601. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4602. />
  4603. )}
  4604. </div>
  4605. );
  4606. })}
  4607. </div>
  4608. </>
  4609. );
  4610. })()}
  4611. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4612. {/* Controls */}
  4613. {viewMode === 'expanded' && (() => {
  4614. // Determine print state for control buttons
  4615. const isRunning = status.state === 'RUNNING';
  4616. const isPaused = status.state === 'PAUSE';
  4617. const isPrinting = isRunning || isPaused;
  4618. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4619. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4620. 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';
  4621. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4622. return (
  4623. <div className="mt-3">
  4624. {/* Section Header */}
  4625. <div className="flex items-center gap-2 mb-2">
  4626. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4627. {t('printers.controls')}
  4628. </span>
  4629. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4630. </div>
  4631. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4632. {/* Left: Secondary controls */}
  4633. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4634. <button
  4635. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4636. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4637. className={`${iconControlClass} ${
  4638. status.chamber_light
  4639. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4640. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4641. }`}
  4642. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4643. >
  4644. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4645. </button>
  4646. {/* Airduct Mode (P2S / X2D / H2*) */}
  4647. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4648. const isHeating = status.airduct_mode === 1;
  4649. const Icon = isHeating ? Flame : Snowflake;
  4650. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4651. 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';
  4652. return (
  4653. <div className="relative">
  4654. <button
  4655. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4656. disabled={!hasPermission('printers:control')}
  4657. className={`${iconControlClass} ${bg}`}
  4658. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4659. >
  4660. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4661. </button>
  4662. {showAirductMenu === printer.id && (
  4663. <>
  4664. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4665. <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]">
  4666. {([
  4667. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4668. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4669. ] as const).map(({ mode, label, modeId }) => (
  4670. <button
  4671. key={mode}
  4672. onClick={() => {
  4673. airductMutation.mutate(mode);
  4674. setShowAirductMenu(null);
  4675. }}
  4676. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4677. status.airduct_mode === modeId
  4678. ? 'text-bambu-green bg-bambu-green/10'
  4679. : 'text-white hover:bg-bambu-dark-tertiary'
  4680. }`}
  4681. >
  4682. {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)]" />}
  4683. {label}
  4684. </button>
  4685. ))}
  4686. </div>
  4687. </>
  4688. )}
  4689. </div>
  4690. );
  4691. })()}
  4692. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4693. {(() => {
  4694. const canControl = hasPermission('printers:control');
  4695. const disabled = isPrinting || !canControl;
  4696. 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';
  4697. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4698. // nozzle-bed gap that means the same thing on every printer, so the
  4699. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4700. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4701. // plate toward the nozzle and closes it.
  4702. const zMovesToolhead = isBedSlinger(printer.model);
  4703. const requestZJog = (arrow: 'up' | 'down') => {
  4704. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4705. // No not-homed gate here, and no endstop bypass to gate either:
  4706. // since #2579 the jog is a bare move that never touches M211. That
  4707. // does not make it clamped — the firmware ignores soft endstops on
  4708. // MQTT G-code entirely, which is what the banner above warns about.
  4709. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4710. };
  4711. const requestXyJog = (x: number, y: number) => {
  4712. xyJogMutation.mutate({ x, y });
  4713. };
  4714. const requestExtruderJog = (distance: number) => {
  4715. extruderJogMutation.mutate(distance);
  4716. };
  4717. return (
  4718. <div className="relative">
  4719. <button
  4720. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4721. disabled={disabled}
  4722. className={`${iconControlClass} ${
  4723. disabled
  4724. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4725. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4726. }`}
  4727. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4728. >
  4729. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4730. </button>
  4731. {showBedJogMenu === printer.id && (
  4732. <>
  4733. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4734. <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">
  4735. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4736. {t('printers.bedJog.title')}
  4737. </div>
  4738. <div className="h-px bg-bambu-dark-tertiary" />
  4739. {/* #2579: Bambu firmware does not enforce soft endstops on
  4740. G-code sent over MQTT, so manual moves can drive past the
  4741. travel limits and cause a collision. Not fixable from our
  4742. side — warn prominently. */}
  4743. <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">
  4744. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4745. <span>{t('printers.bedJog.limitWarning')}</span>
  4746. </div>
  4747. <div className="h-px bg-bambu-dark-tertiary" />
  4748. <div className="flex justify-center px-3 py-2.5">
  4749. <div className="flex items-center justify-center gap-3">
  4750. <div className="grid grid-cols-3 gap-1">
  4751. <div />
  4752. <button
  4753. onClick={() => requestXyJog(0, bedJogStep)}
  4754. disabled={xyJogMutation.isPending}
  4755. className={jogButtonClass}
  4756. aria-label="Move Y forward"
  4757. >
  4758. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4759. </button>
  4760. <div />
  4761. <button
  4762. onClick={() => requestXyJog(-bedJogStep, 0)}
  4763. disabled={xyJogMutation.isPending}
  4764. className={jogButtonClass}
  4765. aria-label="Move X left"
  4766. >
  4767. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4768. </button>
  4769. <button
  4770. onClick={() => {
  4771. setShowBedJogMenu(null);
  4772. homeAxesMutation.mutate('all');
  4773. }}
  4774. disabled={homeAxesMutation.isPending}
  4775. className={jogButtonClass}
  4776. aria-label={t('printers.bedJog.homeZ')}
  4777. >
  4778. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4779. </button>
  4780. <button
  4781. onClick={() => requestXyJog(bedJogStep, 0)}
  4782. disabled={xyJogMutation.isPending}
  4783. className={jogButtonClass}
  4784. aria-label="Move X right"
  4785. >
  4786. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4787. </button>
  4788. <div />
  4789. <button
  4790. onClick={() => requestXyJog(0, -bedJogStep)}
  4791. disabled={xyJogMutation.isPending}
  4792. className={jogButtonClass}
  4793. aria-label="Move Y back"
  4794. >
  4795. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4796. </button>
  4797. <div />
  4798. </div>
  4799. <div className="flex flex-col items-center gap-1">
  4800. <button
  4801. onClick={() => requestZJog('up')}
  4802. disabled={bedJogMutation.isPending}
  4803. className={jogButtonClass}
  4804. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4805. >
  4806. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4807. </button>
  4808. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4809. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4810. </div>
  4811. <button
  4812. onClick={() => requestZJog('down')}
  4813. disabled={bedJogMutation.isPending}
  4814. className={jogButtonClass}
  4815. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4816. >
  4817. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4818. </button>
  4819. </div>
  4820. <div className="flex flex-col items-center gap-1">
  4821. <button
  4822. onClick={() => requestExtruderJog(-bedJogStep)}
  4823. disabled={extruderJogMutation.isPending}
  4824. className={jogButtonClass}
  4825. aria-label="Retract filament"
  4826. >
  4827. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4828. </button>
  4829. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4830. <span className="text-sm font-semibold leading-none">E</span>
  4831. </div>
  4832. <button
  4833. onClick={() => requestExtruderJog(bedJogStep)}
  4834. disabled={extruderJogMutation.isPending}
  4835. className={jogButtonClass}
  4836. aria-label="Extrude filament"
  4837. >
  4838. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4839. </button>
  4840. </div>
  4841. </div>
  4842. </div>
  4843. <div className="h-px bg-bambu-dark-tertiary" />
  4844. <div className="px-3 pt-2.5 pb-3">
  4845. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4846. {t('printers.bedJog.step')}
  4847. </div>
  4848. <div className="flex gap-1">
  4849. {[1, 10, 50].map((step) => (
  4850. <button
  4851. key={step}
  4852. onClick={() => setBedJogStep(step)}
  4853. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4854. bedJogStep === step
  4855. ? 'bg-bambu-green/20 text-bambu-green'
  4856. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4857. }`}
  4858. >
  4859. {step}
  4860. </button>
  4861. ))}
  4862. </div>
  4863. </div>
  4864. </div>
  4865. </>
  4866. )}
  4867. </div>
  4868. );
  4869. })()}
  4870. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4871. <button
  4872. onClick={handleTogglePlateDetection}
  4873. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4874. className={`${iconControlClass} rounded-r-none ${
  4875. printer.plate_detection_enabled
  4876. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4877. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4878. }`}
  4879. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4880. >
  4881. {plateDetectionMutation.isPending ? (
  4882. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4883. ) : (
  4884. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4885. )}
  4886. </button>
  4887. <button
  4888. onClick={handleOpenPlateManagement}
  4889. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4890. 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 ${
  4891. printer.plate_detection_enabled
  4892. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4893. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4894. }`}
  4895. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4896. >
  4897. {isCheckingPlate ? (
  4898. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4899. ) : (
  4900. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4901. )}
  4902. </button>
  4903. </div>
  4904. {/* Print Speed */}
  4905. {(() => (
  4906. <div className="relative">
  4907. <button
  4908. data-testid="speed-control"
  4909. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4910. disabled={!isPrinting || !hasPermission('printers:control')}
  4911. className={`${iconControlClass} ${
  4912. isPrinting
  4913. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4914. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4915. }`}
  4916. title={isPrinting ? t('printers.speed.title') : undefined}
  4917. >
  4918. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4919. </button>
  4920. {showSpeedMenu === printer.id && (
  4921. <>
  4922. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4923. <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]">
  4924. {([
  4925. { mode: 1, label: t('printers.speed.silent') },
  4926. { mode: 2, label: t('printers.speed.standard') },
  4927. { mode: 3, label: t('printers.speed.sport') },
  4928. { mode: 4, label: t('printers.speed.ludicrous') },
  4929. ] as const).map(({ mode, label }) => (
  4930. <button
  4931. key={mode}
  4932. onClick={() => {
  4933. printSpeedMutation.mutate(mode);
  4934. setShowSpeedMenu(null);
  4935. }}
  4936. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4937. status.speed_level === mode
  4938. ? 'text-bambu-green bg-bambu-green/10'
  4939. : 'text-white hover:bg-bambu-dark-tertiary'
  4940. }`}
  4941. >
  4942. {label}
  4943. </button>
  4944. ))}
  4945. </div>
  4946. </>
  4947. )}
  4948. </div>
  4949. ))()}
  4950. </div>
  4951. {/* Right: Print Control Buttons */}
  4952. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4953. {/* Pause/Resume button */}
  4954. {(() => {
  4955. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4956. return (
  4957. <button
  4958. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4959. disabled={pauseUnavailable}
  4960. className={`
  4961. ${printControlClass}
  4962. ${pauseUnavailable
  4963. ? unavailablePrintActionClass
  4964. : isPaused
  4965. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4966. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4967. }
  4968. `}
  4969. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4970. >
  4971. {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)]" />}
  4972. {isPaused ? t('printers.resume') : t('printers.pause')}
  4973. </button>
  4974. );
  4975. })()}
  4976. {/* Stop button */}
  4977. {(() => {
  4978. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4979. return (
  4980. <button
  4981. onClick={() => setShowStopConfirm(true)}
  4982. disabled={stopUnavailable}
  4983. className={`
  4984. ${printControlClass}
  4985. ${stopUnavailable
  4986. ? unavailablePrintActionClass
  4987. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4988. }
  4989. `}
  4990. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4991. >
  4992. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4993. {t('printers.stop')}
  4994. </button>
  4995. );
  4996. })()}
  4997. </div>
  4998. </div>
  4999. </div>
  5000. );
  5001. })()}
  5002. {/* AMS Units - 2-Column Grid Layout */}
  5003. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  5004. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  5005. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  5006. const htAms = amsData.filter(ams => ams.tray.length === 1);
  5007. // The external spool can only be hidden while some AMS remains to
  5008. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  5009. // filament section, so the toggle is not offered there and a stored
  5010. // preference from a printer that later lost its AMS cannot blank the
  5011. // row either — both read through canHideExternalSpool.
  5012. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  5013. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5014. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5015. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5016. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5017. // floating point, and that lands verbatim in the DOM.
  5018. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5019. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5020. // already grow to fill the row, so the 3.5rem is a floor they sit
  5021. // well above in practice -- raising it just costs a unit its place
  5022. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5023. // its line, and flex-grow stretches its single slot across the whole
  5024. // card. The AMS-HT's own width does scale, below, because its
  5025. // readings sit beside the slot rather than under it.
  5026. const slotMinWidth = '3.5rem';
  5027. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5028. // The AMS-HT holds a single spool, and its slot is the only thing
  5029. // on that row able to grow -- so it swallowed every spare pixel and
  5030. // shoved the temperature and humidity hard against the card's edge.
  5031. // Capping it at roughly two ordinary slots keeps the readings clear
  5032. // of the edge; the cap scales because the text inside the slot does.
  5033. const htSlotStyle: React.CSSProperties = {
  5034. minWidth: slotMinWidth,
  5035. maxWidth: scaledRem(7.25),
  5036. };
  5037. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5038. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5039. });
  5040. // #1762 (comment 2): while a print is running/paused, overlay a small
  5041. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5042. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5043. // staged to a printer with mismatched filament: the wrong-slot pill
  5044. // is visible the instant printing starts.
  5045. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5046. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5047. ? status.ams_mapping
  5048. : [];
  5049. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5050. const boundedSlotCount = Math.max(1, slotCount);
  5051. const gapCount = Math.max(0, boundedSlotCount - 1);
  5052. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5053. return {
  5054. flex: `1 1 ${minWidth}`,
  5055. minWidth,
  5056. };
  5057. };
  5058. return (
  5059. <div className="mt-3">
  5060. {/* Section Header */}
  5061. <div className="flex items-center gap-2 mb-2">
  5062. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5063. {t('printers.filaments')}
  5064. </span>
  5065. <AmsBackupBadge
  5066. state={status.ams_filament_backup}
  5067. onClick={() => setAmsBackupModalOpen(true)}
  5068. />
  5069. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5070. {/* Offered only when an AMS is present: on a printer that
  5071. feeds from the external spool alone, hiding it would
  5072. empty the row entirely (#1782). */}
  5073. {canHideExternalSpool && (
  5074. <>
  5075. <ExternalSpoolToggle
  5076. hidden={externalSpoolHidden}
  5077. onClick={toggleExternalSpool}
  5078. />
  5079. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5080. </>
  5081. )}
  5082. </div>
  5083. {/* AMS Content */}
  5084. <div className="flex flex-wrap gap-2">
  5085. {/* Regular AMS units */}
  5086. {regularAms.map((ams) => {
  5087. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5088. return (
  5089. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5090. {/* Header: Label + Stats (no icon) */}
  5091. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5092. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5093. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5094. <AmsNameHoverCard
  5095. ams={ams}
  5096. printerId={printer.id}
  5097. label={getAmsLabel(ams.id, ams.tray.length)}
  5098. amsLabels={amsLabels}
  5099. canEdit={hasPermission('printers:update')}
  5100. onSaved={refetchAmsLabels}
  5101. >
  5102. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5103. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5104. </span>
  5105. </AmsNameHoverCard>
  5106. {sideBadge?.kind === 'inlet' ? (
  5107. <InletBadge
  5108. inlet={sideBadge.inlet}
  5109. title={t('printers.amsSwitchInletTooltip', {
  5110. inlet: sideBadge.inlet,
  5111. side: FTS_INLET_SIDE[sideBadge.inlet],
  5112. })}
  5113. />
  5114. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5115. <NozzleBadge side={sideBadge.side} />
  5116. ) : null}
  5117. </div>
  5118. {(ams.humidity != null || ams.temp != null) && (
  5119. <div className="flex shrink-0 items-center gap-1.5">
  5120. {ams.humidity != null && (
  5121. <HumidityIndicator
  5122. humidity={ams.humidity}
  5123. goodThreshold={amsThresholds?.humidityGood}
  5124. fairThreshold={amsThresholds?.humidityFair}
  5125. onClick={() => setAmsHistoryModal({
  5126. amsId: ams.id,
  5127. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5128. mode: 'humidity',
  5129. })}
  5130. compact
  5131. />
  5132. )}
  5133. {ams.temp != null && (
  5134. <div className="mr-1">
  5135. <TemperatureIndicator
  5136. temp={ams.temp}
  5137. goodThreshold={amsThresholds?.tempGood}
  5138. fairThreshold={amsThresholds?.tempFair}
  5139. onClick={() => setAmsHistoryModal({
  5140. amsId: ams.id,
  5141. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5142. mode: 'temperature',
  5143. })}
  5144. compact
  5145. />
  5146. </div>
  5147. )}
  5148. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5149. Screen-only models (P1 series) keep the control but can't
  5150. be commanded: it stays disabled and says why (#2533). */}
  5151. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5152. <button
  5153. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5154. onClick={(e) => {
  5155. if (ams.dry_time > 0) {
  5156. stopDryingMutation.mutate(ams.id);
  5157. } else if (dryingPopoverAmsId === ams.id) {
  5158. setDryingPopoverAmsId(null);
  5159. } else {
  5160. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5161. }
  5162. }}
  5163. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5164. ams.dry_time > 0
  5165. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5166. : status.drying_screen_only || ams.dry_sf_reason?.length
  5167. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5168. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5169. }`}
  5170. 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')}
  5171. >
  5172. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5173. </button>
  5174. )}
  5175. </div>
  5176. )}
  5177. </div>
  5178. {/* Drying status bar. A dry_time whose countdown is not
  5179. ticking, with no active drying phase (a parked command —
  5180. e.g. an H2D mid-print already powering other drying — or
  5181. a paused cycle), is shown as "not running", not as an
  5182. active cycle: the amber badge claiming a running dry
  5183. that the AMS never began is how this was found. */}
  5184. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5185. <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')}>
  5186. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5187. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5188. {ams.dry_filament && (
  5189. <span className="text-slate-500/90 dark:text-slate-400/80">
  5190. {ams.dry_target_temp != null
  5191. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5192. : ams.dry_filament}
  5193. </span>
  5194. )}
  5195. {!status.drying_screen_only && (
  5196. <button
  5197. onClick={() => stopDryingMutation.mutate(ams.id)}
  5198. disabled={stopDryingMutation.isPending}
  5199. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5200. title={t('printers.drying.stop')}
  5201. >
  5202. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5203. </button>
  5204. )}
  5205. </div>
  5206. )}
  5207. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5208. <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)]">
  5209. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5210. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5211. {/* The temperature is only ever known from the target we
  5212. cached when sending the command — the filament can also
  5213. be read off a uniformly loaded unit, so it can outlive
  5214. the temperature (#2759). */}
  5215. {ams.dry_filament && (
  5216. <span className="text-amber-700/80 dark:text-amber-300/70">
  5217. {ams.dry_target_temp != null
  5218. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5219. : ams.dry_filament}
  5220. </span>
  5221. )}
  5222. <span className="text-amber-700/80 dark:text-amber-300/70">
  5223. {t('printers.drying.timeRemaining', {
  5224. time: ams.dry_time >= 60
  5225. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5226. : `${ams.dry_time}m`
  5227. })}
  5228. </span>
  5229. {/* A cycle on a screen-only model was started at the printer
  5230. and can only be stopped there (#2533). */}
  5231. {!status.drying_screen_only && (
  5232. <button
  5233. onClick={() => stopDryingMutation.mutate(ams.id)}
  5234. disabled={stopDryingMutation.isPending}
  5235. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5236. title={t('printers.drying.stop')}
  5237. >
  5238. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5239. </button>
  5240. )}
  5241. </div>
  5242. )}
  5243. {/* Slots grid: 4 columns - always render 4 slots */}
  5244. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5245. {[0, 1, 2, 3].map((slotIdx) => {
  5246. // Find tray data for this slot (may be undefined if data incomplete)
  5247. // Use array index if available, as tray.id may not always be set
  5248. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5249. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5250. const isEmpty = !tray?.tray_type;
  5251. const emptyKind = getEmptySlotKind(tray);
  5252. // Check if this is the currently loaded tray
  5253. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5254. const globalTrayId = ams.id * 4 + slotIdx;
  5255. const isActive = effectiveTrayNow === globalTrayId;
  5256. // Runout guidance (#2587): the slot the paused print now
  5257. // expects filament in, and the slot that ran out.
  5258. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5259. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5260. // Get cloud preset info if available
  5261. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5262. // Get saved slot preset mapping (for user-configured slots)
  5263. const slotPreset = slotPresets?.[globalTrayId];
  5264. // Only trusted while it still describes what the printer reports in the
  5265. // slot: the row survives a spool swap, and the display chain below puts
  5266. // it ahead of the live filament id (see slotPresetDescribesTray).
  5267. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5268. ? slotPreset?.preset_name
  5269. : undefined;
  5270. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5271. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5272. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5273. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5274. // Slot-assigned-only spool fill (no tag link required)
  5275. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5276. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5277. : undefined;
  5278. const slotSpoolForFill = slotAssignmentForFill
  5279. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5280. : undefined;
  5281. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5282. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5283. : null;
  5284. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5285. const inventoryFill = (() => {
  5286. const sp = inventoryAssignment?.spool;
  5287. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5288. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5289. }
  5290. return null;
  5291. })();
  5292. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5293. // (inventory weight_used may be stale or over-counted — #676)
  5294. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5295. ? null : inventoryFill;
  5296. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5297. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5298. : resolvedInventoryFill !== null ? 'inventory' as const
  5299. : hasFillLevel ? 'ams' as const
  5300. : undefined;
  5301. // Build filament data for hover card
  5302. const filamentData = tray?.tray_type ? {
  5303. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5304. // Spoolman spool name wins over cloud lookup so a slot bound to
  5305. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5306. // Design PLA") instead of whatever the printer's filament_id
  5307. // resolves to in the cloud catalog (often "Generic PLA" for
  5308. // P-prefix local presets). Spoolman's filament.name is just the
  5309. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5310. // the hover card shows "Devil Design PLA Basic" rather than the
  5311. // vendor-less form. Strip the "@<printer>..." suffix that
  5312. // BambuStudio appends to user-preset names.
  5313. 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,
  5314. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5315. colorHex: tray.tray_color || null,
  5316. kFactor: formatKValue(tray.k),
  5317. fillLevel: effectiveFill,
  5318. trayUuid: tray.tray_uuid || null,
  5319. tagUid: tray.tag_uid || null,
  5320. fillSource,
  5321. } : null;
  5322. // Check if this specific slot is being refreshed
  5323. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5324. refreshingSlot?.slotId === slotIdx;
  5325. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5326. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5327. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5328. ? `P${activePrintSlotIdx + 1}`
  5329. : null;
  5330. // Slot visual content (goes inside hover card)
  5331. const slotVisual = (
  5332. <div
  5333. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5334. isExpectedSlot
  5335. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5336. : isRanOutSlot
  5337. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5338. : isActive
  5339. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5340. : ''
  5341. }`}
  5342. >
  5343. {isExpectedSlot && (
  5344. <span
  5345. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5346. title={t('printers.expectedSlot.title')}
  5347. 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"
  5348. >
  5349. ↓
  5350. </span>
  5351. )}
  5352. {activePrintSlotLabel && (
  5353. <span
  5354. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5355. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5356. 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"
  5357. >
  5358. {activePrintSlotLabel}
  5359. </span>
  5360. )}
  5361. {/* Filament color circle with 1-based slot number centered inside */}
  5362. <FilamentSlotCircle
  5363. trayColor={tray?.tray_color}
  5364. trayType={tray?.tray_type}
  5365. isEmpty={isEmpty}
  5366. emptyKind={emptyKind}
  5367. slotNumber={slotIdx + 1}
  5368. />
  5369. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5370. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5371. </div>
  5372. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5373. {/* Fill bar */}
  5374. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5375. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5376. <div
  5377. className="h-full rounded-full transition-all"
  5378. style={{
  5379. width: `${effectiveFill}%`,
  5380. backgroundColor: getFillBarColor(effectiveFill),
  5381. }}
  5382. />
  5383. )}
  5384. </div>
  5385. </div>
  5386. );
  5387. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5388. return (
  5389. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5390. {/* Loading overlay during RFID re-read */}
  5391. {isRefreshing && (
  5392. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5393. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5394. </div>
  5395. )}
  5396. {/* Hover card wraps only the visual content */}
  5397. {filamentData ? (
  5398. <FilamentHoverCard
  5399. data={filamentData}
  5400. actions={renderAmsSlotActions({
  5401. amsId: ams.id,
  5402. slotId: slotIdx,
  5403. loadTrayId: ams.id * 4 + slotIdx,
  5404. isRefreshing,
  5405. })}
  5406. spoolman={{
  5407. enabled: spoolmanEnabled,
  5408. // #1457: slot assignment is the user's most explicit action — it must
  5409. // outrank the tag-link, which can be stale when a non-RFID slot's
  5410. // fallback tag is still attached to a previous spool in Spoolman.
  5411. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5412. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5413. spoolmanUrl,
  5414. syncMode: spoolmanSyncMode,
  5415. // Suppress Link button when slot is already occupied by ANY assignment
  5416. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5417. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5418. // still appearing on slots with a local Devil Design PLA assigned.
  5419. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5420. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5421. setLinkSpoolModal({
  5422. tagUid: filamentData.tagUid || linkTag,
  5423. trayUuid: filamentData.trayUuid || '',
  5424. printerId: printer.id,
  5425. amsId: ams.id,
  5426. trayId: slotIdx,
  5427. });
  5428. } : undefined,
  5429. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5430. }}
  5431. inventory={(() => {
  5432. if (spoolmanEnabled) {
  5433. if (spoolmanLoading) return undefined;
  5434. const slotAssignment = slotAssignmentForFill;
  5435. const spoolmanSpool = slotSpoolForFill;
  5436. return {
  5437. assignedSpool: spoolmanSpool ? {
  5438. id: spoolmanSpool.id,
  5439. material: spoolmanSpool.material,
  5440. subtype: spoolmanSpool.subtype,
  5441. brand: spoolmanSpool.brand ?? null,
  5442. color_name: spoolmanSpool.color_name ?? null,
  5443. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5444. // The spool's own swatch (#2967). Spoolman carries the
  5445. // extra stops but has no effect field at all, so those
  5446. // rolls gradient and never shimmer.
  5447. rgba: spoolmanSpool.rgba ?? null,
  5448. extra_colors: spoolmanSpool.extra_colors ?? null,
  5449. effect_type: spoolmanSpool.effect_type ?? null,
  5450. remainingWeightGrams: spoolmanSpool.label_weight
  5451. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5452. : undefined,
  5453. } : null,
  5454. onAssignSpool: () => setAssignSpoolModal({
  5455. printerId: printer.id,
  5456. amsId: ams.id,
  5457. trayId: slotIdx,
  5458. trayInfo: {
  5459. type: tray?.tray_type || filamentData.profile,
  5460. material: tray?.tray_type ?? undefined,
  5461. profile: filamentData.profile,
  5462. color: filamentData.colorHex || '',
  5463. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5464. },
  5465. }),
  5466. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5467. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5468. };
  5469. }
  5470. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5471. return {
  5472. assignedSpool: assignment?.spool ? {
  5473. id: assignment.spool.id,
  5474. material: assignment.spool.material,
  5475. subtype: assignment.spool.subtype,
  5476. brand: assignment.spool.brand,
  5477. color_name: assignment.spool.color_name,
  5478. // The spool's own swatch (#2967).
  5479. rgba: assignment.spool.rgba ?? null,
  5480. extra_colors: assignment.spool.extra_colors ?? null,
  5481. effect_type: assignment.spool.effect_type ?? null,
  5482. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5483. } : null,
  5484. onAssignSpool: () => setAssignSpoolModal({
  5485. printerId: printer.id,
  5486. amsId: ams.id,
  5487. trayId: slotIdx,
  5488. trayInfo: {
  5489. type: tray?.tray_type || filamentData.profile,
  5490. material: tray?.tray_type ?? undefined,
  5491. profile: filamentData.profile,
  5492. color: filamentData.colorHex || '',
  5493. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5494. },
  5495. }),
  5496. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5497. isAssigned: !!assignment || isBambuLabSpool(tray),
  5498. };
  5499. })()}
  5500. configureSlot={{
  5501. enabled: hasPermission('printers:control'),
  5502. onConfigure: () => setConfigureSlotModal({
  5503. amsId: ams.id,
  5504. trayId: slotIdx,
  5505. trayCount: ams.tray.length,
  5506. trayType: tray?.tray_type || undefined,
  5507. trayColor: tray?.tray_color || undefined,
  5508. traySubBrands: tray?.tray_sub_brands || undefined,
  5509. trayInfoIdx: tray?.tray_info_idx || undefined,
  5510. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5511. caliIdx: tray?.cali_idx,
  5512. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5513. }),
  5514. }}
  5515. >
  5516. {slotVisual}
  5517. </FilamentHoverCard>
  5518. ) : (
  5519. <EmptySlotHoverCard
  5520. kind={emptyKind ?? undefined}
  5521. actions={renderAmsSlotActions({
  5522. amsId: ams.id,
  5523. slotId: slotIdx,
  5524. loadTrayId: ams.id * 4 + slotIdx,
  5525. isRefreshing,
  5526. })}
  5527. configureSlot={{
  5528. enabled: hasPermission('printers:control'),
  5529. onConfigure: () => setConfigureSlotModal({
  5530. amsId: ams.id,
  5531. trayId: slotIdx,
  5532. trayCount: ams.tray.length,
  5533. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5534. }),
  5535. }}
  5536. onAssignSpool={() => setAssignSpoolModal({
  5537. printerId: printer.id,
  5538. amsId: ams.id,
  5539. trayId: slotIdx,
  5540. trayInfo: {
  5541. type: '',
  5542. material: undefined,
  5543. profile: '',
  5544. color: '',
  5545. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5546. },
  5547. })}
  5548. >
  5549. {slotVisual}
  5550. </EmptySlotHoverCard>
  5551. )}
  5552. </div>
  5553. );
  5554. })}
  5555. </div>
  5556. </div>
  5557. );
  5558. })}
  5559. {/* HT AMS units */}
  5560. {htAms.map((ams) => {
  5561. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5562. const tray = ams.tray[0];
  5563. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5564. const isEmpty = !tray?.tray_type;
  5565. const emptyKind = getEmptySlotKind(tray);
  5566. // Check if this is the currently loaded tray
  5567. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5568. const isActive = effectiveTrayNow === globalTrayId;
  5569. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5570. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5571. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5572. // Get cloud preset info if available
  5573. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5574. // Get saved slot preset mapping (for user-configured slots)
  5575. const slotPreset = slotPresets?.[globalTrayId];
  5576. // Only trusted while it still describes what the printer reports in the
  5577. // slot: the row survives a spool swap, and the display chain below puts
  5578. // it ahead of the live filament id (see slotPresetDescribesTray).
  5579. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx)
  5580. ? slotPreset?.preset_name
  5581. : undefined;
  5582. const htSlotId = tray?.id ?? 0;
  5583. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5584. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5585. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5586. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5587. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5588. const htInventoryFill = (() => {
  5589. const sp = htInventoryAssignment?.spool;
  5590. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5591. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5592. }
  5593. return null;
  5594. })();
  5595. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5596. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5597. ? null : htInventoryFill;
  5598. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5599. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5600. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5601. : undefined;
  5602. const htSlotSpoolForFill = htSlotAssignmentForFill
  5603. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5604. : undefined;
  5605. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5606. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5607. : null;
  5608. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5609. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5610. : htResolvedInventoryFill !== null ? 'inventory' as const
  5611. : hasFillLevel ? 'ams' as const
  5612. : undefined;
  5613. // Build filament data for hover card
  5614. const filamentData = tray?.tray_type ? {
  5615. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5616. 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,
  5617. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5618. colorHex: tray.tray_color || null,
  5619. kFactor: formatKValue(tray.k),
  5620. fillLevel: htEffectiveFill,
  5621. trayUuid: tray.tray_uuid || null,
  5622. tagUid: tray.tag_uid || null,
  5623. fillSource: htFillSource,
  5624. } : null;
  5625. // Check if this specific slot is being refreshed
  5626. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5627. refreshingSlot?.slotId === htSlotId;
  5628. // #1762 (comment 2): active print-slot index for this HT slot.
  5629. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5630. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5631. ? `P${htActivePrintSlotIdx + 1}`
  5632. : null;
  5633. // Slot visual content (goes inside hover card)
  5634. const slotVisual = (
  5635. <div
  5636. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5637. isExpectedSlot
  5638. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5639. : isRanOutSlot
  5640. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5641. : isActive
  5642. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5643. : ''
  5644. }`}
  5645. >
  5646. {isExpectedSlot && (
  5647. <span
  5648. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5649. title={t('printers.expectedSlot.title')}
  5650. 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"
  5651. >
  5652. ↓
  5653. </span>
  5654. )}
  5655. {htActivePrintSlotLabel && (
  5656. <span
  5657. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5658. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5659. 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"
  5660. >
  5661. {htActivePrintSlotLabel}
  5662. </span>
  5663. )}
  5664. {/* Filament color circle with 1-based slot number centered inside */}
  5665. <FilamentSlotCircle
  5666. trayColor={tray?.tray_color}
  5667. trayType={tray?.tray_type}
  5668. isEmpty={isEmpty}
  5669. emptyKind={emptyKind}
  5670. slotNumber={1}
  5671. />
  5672. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5673. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5674. </div>
  5675. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5676. {/* Fill bar */}
  5677. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5678. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5679. <div
  5680. className="h-full rounded-full transition-all"
  5681. style={{
  5682. width: `${htEffectiveFill}%`,
  5683. backgroundColor: getFillBarColor(htEffectiveFill),
  5684. }}
  5685. />
  5686. )}
  5687. </div>
  5688. </div>
  5689. );
  5690. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5691. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5692. // Without this override, the L view squishes HT into a sliver next to the
  5693. // 4-slot AMS neighbors.
  5694. // 11rem holds one slot plus the temperature/humidity
  5695. // column beside it; both grow with the body scale.
  5696. const htCardWidth = scaledRem(11);
  5697. const htCardStyle: React.CSSProperties = {
  5698. flex: `1 1 ${htCardWidth}`,
  5699. minWidth: htCardWidth,
  5700. // An AMS-HT is never wider than a full AMS. Without a
  5701. // ceiling, a unit that wraps onto a line of its own is
  5702. // the only flex item there and grow stretches its single
  5703. // slot across the entire card, leaving the readings
  5704. // stranded at the far edge.
  5705. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5706. };
  5707. return (
  5708. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5709. {/* Row 1: Label + Nozzle + Drying */}
  5710. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5711. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5712. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5713. <AmsNameHoverCard
  5714. ams={ams}
  5715. printerId={printer.id}
  5716. label={getAmsLabel(ams.id, ams.tray.length)}
  5717. amsLabels={amsLabels}
  5718. canEdit={hasPermission('printers:update')}
  5719. onSaved={refetchAmsLabels}
  5720. >
  5721. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5722. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5723. </span>
  5724. </AmsNameHoverCard>
  5725. {sideBadge?.kind === 'inlet' ? (
  5726. <InletBadge
  5727. inlet={sideBadge.inlet}
  5728. title={t('printers.amsSwitchInletTooltip', {
  5729. inlet: sideBadge.inlet,
  5730. side: FTS_INLET_SIDE[sideBadge.inlet],
  5731. })}
  5732. />
  5733. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5734. <NozzleBadge side={sideBadge.side} />
  5735. ) : null}
  5736. </div>
  5737. {/* Drying button for HT AMS */}
  5738. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5739. <div className="relative ml-auto">
  5740. <button
  5741. disabled={status.drying_screen_only}
  5742. onClick={(e) => {
  5743. if (ams.dry_time > 0) {
  5744. stopDryingMutation.mutate(ams.id);
  5745. } else if (dryingPopoverAmsId === ams.id) {
  5746. setDryingPopoverAmsId(null);
  5747. } else {
  5748. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5749. }
  5750. }}
  5751. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5752. ams.dry_time > 0
  5753. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5754. : status.drying_screen_only
  5755. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5756. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5757. }`}
  5758. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5759. >
  5760. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5761. </button>
  5762. </div>
  5763. )}
  5764. </div>
  5765. {/* HT AMS drying status bar. Same not-running split as the
  5766. standard-AMS bar above: a frozen countdown is not a
  5767. running cycle. */}
  5768. {ams.dry_time > 0 && (
  5769. <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}>
  5770. {ams.dry_countdown_stalled
  5771. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5772. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5773. {ams.dry_countdown_stalled && (
  5774. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5775. )}
  5776. {ams.dry_filament && (
  5777. <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`}>
  5778. {ams.dry_target_temp != null
  5779. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5780. : ams.dry_filament}
  5781. </span>
  5782. )}
  5783. {!ams.dry_countdown_stalled && (
  5784. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5785. {ams.dry_time >= 60
  5786. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5787. : `${ams.dry_time}m`}
  5788. </span>
  5789. )}
  5790. {!status.drying_screen_only && (
  5791. <button
  5792. onClick={() => stopDryingMutation.mutate(ams.id)}
  5793. disabled={stopDryingMutation.isPending}
  5794. 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"
  5795. title={t('printers.drying.stop')}
  5796. >
  5797. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5798. </button>
  5799. )}
  5800. </div>
  5801. )}
  5802. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5803. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5804. {/* Slot wrapper with loading overlay */}
  5805. <div className="relative group flex-1" style={htSlotStyle}>
  5806. {/* Loading overlay during RFID re-read */}
  5807. {isHtRefreshing && (
  5808. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5809. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5810. </div>
  5811. )}
  5812. {/* Hover card wraps only the visual content */}
  5813. {filamentData ? (
  5814. <FilamentHoverCard
  5815. data={filamentData}
  5816. actions={renderAmsSlotActions({
  5817. amsId: ams.id,
  5818. slotId: htSlotId,
  5819. loadTrayId: ams.id * 4 + htSlotId,
  5820. isRefreshing: isHtRefreshing,
  5821. })}
  5822. spoolman={{
  5823. enabled: spoolmanEnabled,
  5824. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5825. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5826. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5827. spoolmanUrl,
  5828. syncMode: spoolmanSyncMode,
  5829. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5830. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5831. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5832. setLinkSpoolModal({
  5833. tagUid: filamentData.tagUid || linkTag,
  5834. trayUuid: filamentData.trayUuid || '',
  5835. printerId: printer.id,
  5836. amsId: ams.id,
  5837. trayId: htSlotId,
  5838. });
  5839. } : undefined,
  5840. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5841. }}
  5842. inventory={(() => {
  5843. if (spoolmanEnabled) {
  5844. if (spoolmanLoading) return undefined;
  5845. const slotAssignment = htSlotAssignmentForFill;
  5846. const spoolmanSpool = htSlotSpoolForFill;
  5847. return {
  5848. assignedSpool: spoolmanSpool ? {
  5849. id: spoolmanSpool.id,
  5850. material: spoolmanSpool.material,
  5851. subtype: spoolmanSpool.subtype,
  5852. brand: spoolmanSpool.brand ?? null,
  5853. color_name: spoolmanSpool.color_name ?? null,
  5854. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5855. // The spool's own swatch (#2967). Spoolman carries the
  5856. // extra stops but has no effect field at all, so those
  5857. // rolls gradient and never shimmer.
  5858. rgba: spoolmanSpool.rgba ?? null,
  5859. extra_colors: spoolmanSpool.extra_colors ?? null,
  5860. effect_type: spoolmanSpool.effect_type ?? null,
  5861. remainingWeightGrams: spoolmanSpool.label_weight
  5862. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5863. : undefined,
  5864. } : null,
  5865. onAssignSpool: () => setAssignSpoolModal({
  5866. printerId: printer.id,
  5867. amsId: ams.id,
  5868. trayId: htSlotId,
  5869. trayInfo: {
  5870. type: tray?.tray_type || filamentData.profile,
  5871. material: tray?.tray_type ?? undefined,
  5872. profile: filamentData.profile,
  5873. color: filamentData.colorHex || '',
  5874. location: getAmsLabel(ams.id, ams.tray.length),
  5875. },
  5876. }),
  5877. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5878. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5879. };
  5880. }
  5881. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5882. return {
  5883. assignedSpool: assignment?.spool ? {
  5884. id: assignment.spool.id,
  5885. material: assignment.spool.material,
  5886. subtype: assignment.spool.subtype,
  5887. brand: assignment.spool.brand,
  5888. color_name: assignment.spool.color_name,
  5889. // The spool's own swatch (#2967).
  5890. rgba: assignment.spool.rgba ?? null,
  5891. extra_colors: assignment.spool.extra_colors ?? null,
  5892. effect_type: assignment.spool.effect_type ?? null,
  5893. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5894. } : null,
  5895. onAssignSpool: () => setAssignSpoolModal({
  5896. printerId: printer.id,
  5897. amsId: ams.id,
  5898. trayId: htSlotId,
  5899. trayInfo: {
  5900. type: tray?.tray_type || filamentData.profile,
  5901. material: tray?.tray_type ?? undefined,
  5902. profile: filamentData.profile,
  5903. color: filamentData.colorHex || '',
  5904. location: getAmsLabel(ams.id, ams.tray.length),
  5905. },
  5906. }),
  5907. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5908. isAssigned: !!assignment || isBambuLabSpool(tray),
  5909. };
  5910. })()}
  5911. configureSlot={{
  5912. enabled: hasPermission('printers:control'),
  5913. onConfigure: () => setConfigureSlotModal({
  5914. amsId: ams.id,
  5915. trayId: htSlotId,
  5916. trayCount: ams.tray.length,
  5917. trayType: tray?.tray_type || undefined,
  5918. trayColor: tray?.tray_color || undefined,
  5919. traySubBrands: tray?.tray_sub_brands || undefined,
  5920. trayInfoIdx: tray?.tray_info_idx || undefined,
  5921. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5922. caliIdx: tray?.cali_idx,
  5923. savedPresetId: slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx, slotPreset?.tray_info_idx) ? slotPreset?.preset_id : undefined,
  5924. }),
  5925. }}
  5926. >
  5927. {slotVisual}
  5928. </FilamentHoverCard>
  5929. ) : (
  5930. <EmptySlotHoverCard
  5931. kind={emptyKind ?? undefined}
  5932. actions={renderAmsSlotActions({
  5933. amsId: ams.id,
  5934. slotId: htSlotId,
  5935. loadTrayId: ams.id * 4 + htSlotId,
  5936. isRefreshing: isHtRefreshing,
  5937. })}
  5938. configureSlot={{
  5939. enabled: hasPermission('printers:control'),
  5940. onConfigure: () => setConfigureSlotModal({
  5941. amsId: ams.id,
  5942. trayId: htSlotId,
  5943. trayCount: ams.tray.length,
  5944. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5945. }),
  5946. }}
  5947. onAssignSpool={() => setAssignSpoolModal({
  5948. printerId: printer.id,
  5949. amsId: ams.id,
  5950. trayId: htSlotId,
  5951. trayInfo: {
  5952. type: '',
  5953. material: undefined,
  5954. profile: '',
  5955. color: '',
  5956. location: getAmsLabel(ams.id, ams.tray.length),
  5957. },
  5958. })}
  5959. >
  5960. {slotVisual}
  5961. </EmptySlotHoverCard>
  5962. )}
  5963. </div>
  5964. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5965. {(ams.humidity != null || ams.temp != null) && (
  5966. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5967. {ams.temp != null && (
  5968. <TemperatureIndicator
  5969. temp={ams.temp}
  5970. goodThreshold={amsThresholds?.tempGood}
  5971. fairThreshold={amsThresholds?.tempFair}
  5972. onClick={() => setAmsHistoryModal({
  5973. amsId: ams.id,
  5974. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5975. mode: 'temperature',
  5976. })}
  5977. compact
  5978. />
  5979. )}
  5980. {ams.humidity != null && (
  5981. <HumidityIndicator
  5982. humidity={ams.humidity}
  5983. goodThreshold={amsThresholds?.humidityGood}
  5984. fairThreshold={amsThresholds?.humidityFair}
  5985. onClick={() => setAmsHistoryModal({
  5986. amsId: ams.id,
  5987. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5988. mode: 'humidity',
  5989. })}
  5990. compact
  5991. />
  5992. )}
  5993. </div>
  5994. )}
  5995. </div>
  5996. </div>
  5997. );
  5998. })}
  5999. {/* External spool(s) - grouped in one card like regular AMS */}
  6000. {status.vt_tray.length > 0 && showExternalSpool && (
  6001. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  6002. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  6003. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  6004. </div>
  6005. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  6006. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  6007. const extTrayId = extTray.id ?? 254;
  6008. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  6009. // generically — use active_extruder to determine L vs R:
  6010. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  6011. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  6012. ? (extTrayId === 254 && status.active_extruder === 1) ||
  6013. (extTrayId === 255 && status.active_extruder === 0)
  6014. : effectiveTrayNow === extTrayId;
  6015. const slotTrayId = extTrayId - 254; // 0 or 1
  6016. const extLabel = isDualNozzle
  6017. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6018. : '';
  6019. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6020. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6021. // Only trusted while it still describes what the printer reports in the
  6022. // slot: the row survives a spool swap, and the display chain below puts
  6023. // it ahead of the live filament id (see slotPresetDescribesTray).
  6024. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx)
  6025. ? extSlotPreset?.preset_name
  6026. : undefined;
  6027. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6028. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6029. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6030. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6031. const extInventoryFill = (() => {
  6032. const sp = extInventoryAssignment?.spool;
  6033. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6034. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6035. }
  6036. return null;
  6037. })();
  6038. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6039. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6040. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6041. ? null : extInventoryFill;
  6042. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6043. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6044. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6045. : undefined;
  6046. const extSlotSpoolForFill = extSlotAssignmentForFill
  6047. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6048. : undefined;
  6049. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6050. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6051. : null;
  6052. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6053. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6054. : extResolvedInventoryFill !== null ? 'inventory' as const
  6055. : extHasFillLevel ? 'ams' as const
  6056. : undefined;
  6057. const extFilamentData = {
  6058. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6059. 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',
  6060. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6061. colorHex: extTray.tray_color || null,
  6062. kFactor: formatKValue(extTray.k),
  6063. fillLevel: extEffectiveFill,
  6064. trayUuid: extTray.tray_uuid || null,
  6065. tagUid: extTray.tag_uid || null,
  6066. fillSource: extFillSource,
  6067. };
  6068. const isEmpty = !extTray.tray_type;
  6069. const emptyKind = getEmptySlotKind(extTray);
  6070. const extSlotContent = (
  6071. <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' : ''}`}>
  6072. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6073. the separate Ext-L/Ext-R caption that made the row taller than
  6074. regular AMS slots), 1-based slot number on single-nozzle. */}
  6075. <FilamentSlotCircle
  6076. trayColor={extTray.tray_color}
  6077. trayType={extTray.tray_type}
  6078. isEmpty={isEmpty}
  6079. emptyKind={emptyKind}
  6080. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6081. />
  6082. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6083. {extTray.tray_type || t('ams.slotEmpty')}
  6084. </div>
  6085. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6086. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6087. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6088. <div
  6089. className="h-full rounded-full transition-all"
  6090. style={{
  6091. width: `${extEffectiveFill}%`,
  6092. backgroundColor: getFillBarColor(extEffectiveFill),
  6093. }}
  6094. />
  6095. )}
  6096. </div>
  6097. </div>
  6098. );
  6099. return (
  6100. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6101. {!isEmpty ? (
  6102. <FilamentHoverCard
  6103. data={extFilamentData}
  6104. actions={renderAmsSlotActions({
  6105. amsId: 255,
  6106. slotId: slotTrayId,
  6107. loadTrayId: extTrayId,
  6108. includeRfid: false,
  6109. })}
  6110. spoolman={{
  6111. enabled: spoolmanEnabled,
  6112. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6113. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6114. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6115. spoolmanUrl,
  6116. syncMode: spoolmanSyncMode,
  6117. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6118. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6119. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6120. setLinkSpoolModal({
  6121. tagUid: extFilamentData.tagUid || linkTag,
  6122. trayUuid: extFilamentData.trayUuid || '',
  6123. printerId: printer.id,
  6124. amsId: 255,
  6125. trayId: slotTrayId,
  6126. });
  6127. } : undefined,
  6128. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6129. }}
  6130. inventory={(() => {
  6131. if (spoolmanEnabled) {
  6132. if (spoolmanLoading) return undefined;
  6133. const slotAssignment = extSlotAssignmentForFill;
  6134. const spoolmanSpool = extSlotSpoolForFill;
  6135. return {
  6136. assignedSpool: spoolmanSpool ? {
  6137. id: spoolmanSpool.id,
  6138. material: spoolmanSpool.material,
  6139. subtype: spoolmanSpool.subtype,
  6140. brand: spoolmanSpool.brand ?? null,
  6141. color_name: spoolmanSpool.color_name ?? null,
  6142. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6143. // The spool's own swatch (#2967). Spoolman carries the
  6144. // extra stops but has no effect field at all, so those
  6145. // rolls gradient and never shimmer.
  6146. rgba: spoolmanSpool.rgba ?? null,
  6147. extra_colors: spoolmanSpool.extra_colors ?? null,
  6148. effect_type: spoolmanSpool.effect_type ?? null,
  6149. remainingWeightGrams: spoolmanSpool.label_weight
  6150. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6151. : undefined,
  6152. } : null,
  6153. onAssignSpool: () => setAssignSpoolModal({
  6154. printerId: printer.id,
  6155. amsId: 255,
  6156. trayId: slotTrayId,
  6157. trayInfo: {
  6158. type: extTray.tray_type || extFilamentData.profile,
  6159. material: extTray.tray_type ?? undefined,
  6160. profile: extFilamentData.profile,
  6161. color: extFilamentData.colorHex || '',
  6162. location: extLabel || t('printers.external'),
  6163. },
  6164. }),
  6165. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6166. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6167. };
  6168. }
  6169. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6170. return {
  6171. assignedSpool: assignment?.spool ? {
  6172. id: assignment.spool.id,
  6173. material: assignment.spool.material,
  6174. subtype: assignment.spool.subtype,
  6175. brand: assignment.spool.brand,
  6176. color_name: assignment.spool.color_name,
  6177. // The spool's own swatch (#2967).
  6178. rgba: assignment.spool.rgba ?? null,
  6179. extra_colors: assignment.spool.extra_colors ?? null,
  6180. effect_type: assignment.spool.effect_type ?? null,
  6181. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6182. } : null,
  6183. onAssignSpool: () => setAssignSpoolModal({
  6184. printerId: printer.id,
  6185. amsId: 255,
  6186. trayId: slotTrayId,
  6187. trayInfo: {
  6188. type: extTray.tray_type || extFilamentData.profile,
  6189. material: extTray.tray_type ?? undefined,
  6190. profile: extFilamentData.profile,
  6191. color: extFilamentData.colorHex || '',
  6192. location: extLabel || t('printers.external'),
  6193. },
  6194. }),
  6195. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6196. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6197. };
  6198. })()}
  6199. configureSlot={{
  6200. enabled: hasPermission('printers:control'),
  6201. onConfigure: () => setConfigureSlotModal({
  6202. amsId: 255,
  6203. trayId: slotTrayId,
  6204. trayCount: 1,
  6205. trayType: extTray.tray_type || undefined,
  6206. trayColor: extTray.tray_color || undefined,
  6207. traySubBrands: extTray.tray_sub_brands || undefined,
  6208. trayInfoIdx: extTray.tray_info_idx || undefined,
  6209. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6210. caliIdx: extTray.cali_idx,
  6211. savedPresetId: slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx, extSlotPreset?.tray_info_idx) ? extSlotPreset?.preset_id : undefined,
  6212. }),
  6213. }}
  6214. >
  6215. {extSlotContent}
  6216. </FilamentHoverCard>
  6217. ) : (
  6218. <EmptySlotHoverCard
  6219. kind={emptyKind ?? undefined}
  6220. actions={renderAmsSlotActions({
  6221. amsId: 255,
  6222. slotId: slotTrayId,
  6223. loadTrayId: extTrayId,
  6224. includeRfid: false,
  6225. })}
  6226. configureSlot={{
  6227. enabled: hasPermission('printers:control'),
  6228. onConfigure: () => setConfigureSlotModal({
  6229. amsId: 255,
  6230. trayId: slotTrayId,
  6231. trayCount: 1,
  6232. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6233. }),
  6234. }}
  6235. onAssignSpool={() => setAssignSpoolModal({
  6236. printerId: printer.id,
  6237. amsId: 255,
  6238. trayId: slotTrayId,
  6239. trayInfo: {
  6240. type: '',
  6241. material: undefined,
  6242. profile: '',
  6243. color: '',
  6244. location: `External Slot ${slotTrayId + 1}`,
  6245. },
  6246. })}
  6247. >
  6248. {extSlotContent}
  6249. </EmptySlotHoverCard>
  6250. )}
  6251. </div>
  6252. );
  6253. })}
  6254. </div>
  6255. </div>
  6256. )}
  6257. </div>
  6258. </div>
  6259. );
  6260. })()}
  6261. </>
  6262. )}
  6263. {/* Powered-down printer with a dirty plate: the status block above renders
  6264. nothing without a live connection, so the plate-clear control gets its own
  6265. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6266. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6267. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6268. expandedClearPlateButton
  6269. )}
  6270. {/* Bottom block (power row + action bar). Wrapped together so the
  6271. power row hugs the action bar at the card bottom instead of
  6272. floating up when there's less filament content above. */}
  6273. {viewMode === 'expanded' && (
  6274. <div className="mt-auto">
  6275. {smartPlug && (
  6276. <div className="pt-3">
  6277. <div className="flex items-center gap-2 mb-2">
  6278. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6279. {t('printers.power', 'Power')}
  6280. </span>
  6281. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6282. </div>
  6283. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6284. {/* Plug name + current power */}
  6285. <div className="flex items-center gap-2 min-w-0 pl-1">
  6286. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6287. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6288. <span
  6289. 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"
  6290. title={t('smartPlugs.power')}
  6291. >
  6292. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6293. </span>
  6294. </div>
  6295. {/* Spacer */}
  6296. <div className="flex-1" />
  6297. <div className="flex items-center gap-2">
  6298. {/* Auto-off */}
  6299. <button
  6300. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6301. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6302. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6303. 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 ${
  6304. !hasPermission('smart_plugs:control')
  6305. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6306. : smartPlug.auto_off || smartPlug.auto_off_executed
  6307. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6308. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6309. }`}
  6310. >
  6311. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6312. </button>
  6313. <button
  6314. onClick={() => {
  6315. if (plugStatus?.state === 'ON') {
  6316. setShowPowerOffConfirm(true);
  6317. } else {
  6318. setShowPowerOnConfirm(true);
  6319. }
  6320. }}
  6321. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6322. 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 ${
  6323. !hasPermission('smart_plugs:control')
  6324. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6325. : plugStatus?.state === 'ON'
  6326. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6327. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6328. }`}
  6329. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6330. >
  6331. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6332. </button>
  6333. </div>
  6334. </div>
  6335. {/* HA entity buttons row */}
  6336. {scriptPlugs && scriptPlugs.length > 0 && (
  6337. <div className="flex items-center gap-2 mt-2">
  6338. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6339. <span className="text-xs text-bambu-gray">HA:</span>
  6340. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6341. <div className="flex flex-wrap gap-1">
  6342. {scriptPlugs.map(script => {
  6343. const isScript = script.ha_entity_id?.startsWith('script.');
  6344. return (
  6345. <button
  6346. key={script.id}
  6347. onClick={() => {
  6348. if (isScript) {
  6349. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6350. } else {
  6351. setHaToggleConfirm(script);
  6352. }
  6353. }}
  6354. disabled={runScriptMutation.isPending}
  6355. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6356. 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"
  6357. >
  6358. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6359. {script.name}
  6360. </button>
  6361. );
  6362. })}
  6363. </div>
  6364. </div>
  6365. )}
  6366. </div>
  6367. )}
  6368. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6369. a printer can have an enclosure door contact without having a plug,
  6370. and nesting it there would hide the row on exactly those setups. */}
  6371. <PrinterHASensorRow printerId={printer.id} />
  6372. {/* Connection Info & Actions */}
  6373. <div className="pt-4">
  6374. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6375. <div className="flex items-center justify-between gap-2">
  6376. {printerActionsMenu}
  6377. <div className="flex items-center justify-end gap-2 flex-wrap">
  6378. {/* Camera split button: the icon opens whichever view was used
  6379. last, the caret picks between the two and remembers it.
  6380. Replaces the old Settings > General > Camera switch, which
  6381. made choosing between an overlay and a window a trip to
  6382. another page for something you decide per camera. */}
  6383. <div className="flex items-center flex-shrink-0">
  6384. <Button
  6385. variant="secondary"
  6386. size="sm"
  6387. onClick={() => openCameraIn(cameraViewMode)}
  6388. disabled={!status?.connected || !hasPermission('camera:view')}
  6389. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6390. className={`${footerIconButtonClass} !rounded-r-none`}
  6391. >
  6392. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6393. </Button>
  6394. <Button
  6395. variant="secondary"
  6396. size="sm"
  6397. onClick={(e) => {
  6398. // No open/close toggle: the menu's own outside-mousedown
  6399. // handler has already dismissed it by the time this lands.
  6400. const rect = e.currentTarget.getBoundingClientRect();
  6401. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6402. }}
  6403. disabled={!status?.connected || !hasPermission('camera:view')}
  6404. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6405. aria-label={t('settings.cameraViewMode')}
  6406. // Not footerIconButtonClass plus an override: both widths
  6407. // would carry !important and the stylesheet's own order,
  6408. // not this one, would decide which won.
  6409. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6410. >
  6411. <ChevronDown className="w-3 h-3" />
  6412. </Button>
  6413. </div>
  6414. {cameraMenuAnchor && (
  6415. <ContextMenu
  6416. x={cameraMenuAnchor.x}
  6417. y={cameraMenuAnchor.y}
  6418. items={cameraViewModeMenuItems}
  6419. onClose={() => setCameraMenuAnchor(null)}
  6420. />
  6421. )}
  6422. <Button
  6423. variant="secondary"
  6424. size="sm"
  6425. onClick={() => setShowFileManager(true)}
  6426. disabled={!hasPermission('printers:files')}
  6427. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6428. className={footerIconButtonClass}
  6429. >
  6430. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6431. </Button>
  6432. {/* Shown whatever the printer is doing (#2849): this uploads a
  6433. file and queues it, which a busy or offline printer is no
  6434. reason to refuse -- it only means the item waits. Hiding it
  6435. while the drop zone accepted the same file would have left
  6436. the two routes into this flow disagreeing. */}
  6437. <Button
  6438. size="sm"
  6439. onClick={() => setShowUploadForPrint(true)}
  6440. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6441. title={
  6442. !hasPermission('library:upload')
  6443. ? t('fileManager.noPermissionUpload')
  6444. : !hasPermission('queue:create')
  6445. ? t('fileManager.noPermissionAddToQueue')
  6446. : t('common.print')
  6447. }
  6448. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6449. >
  6450. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6451. {t('common.print')}
  6452. </Button>
  6453. </div>
  6454. </div>
  6455. </div>
  6456. </div>
  6457. )}
  6458. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6459. card's horizontal padding instead of running full-bleed into the
  6460. rounded bottom edge. */}
  6461. <ScheduledDryingBanner
  6462. printerId={printer.id}
  6463. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6464. timeFormat={timeFormat}
  6465. />
  6466. </CardContent>
  6467. {/* File Manager Modal */}
  6468. {showFileManager && (
  6469. <FileManagerModal
  6470. printerId={printer.id}
  6471. printerName={printer.name}
  6472. onClose={() => setShowFileManager(false)}
  6473. />
  6474. )}
  6475. {/* Upload for Print Modal */}
  6476. {showUploadForPrint && (
  6477. <FileUploadModal
  6478. folderId={null}
  6479. onClose={() => setShowUploadForPrint(false)}
  6480. onUploadComplete={() => {}}
  6481. autoUpload
  6482. accept=".gcode,.3mf"
  6483. validateFile={(file) => {
  6484. const lower = file.name.toLowerCase();
  6485. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6486. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6487. }
  6488. }}
  6489. onFileUploaded={(uploadedFile) => {
  6490. // Check printer compatibility if sliced_for_model is available in metadata
  6491. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6492. const printerModel = mapModelCode(printer.model);
  6493. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6494. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6495. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6496. }
  6497. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6498. }}
  6499. />
  6500. )}
  6501. {/* Print Modal (after upload) */}
  6502. {printAfterUpload && (
  6503. <PrintModal
  6504. mode="create"
  6505. libraryFileId={printAfterUpload.id}
  6506. archiveName={printAfterUpload.filename}
  6507. initialSelectedPrinterIds={[printer.id]}
  6508. onClose={() => setPrintAfterUpload(null)}
  6509. onSuccess={() => setPrintAfterUpload(null)}
  6510. cleanupLibraryAfterDispatch
  6511. />
  6512. )}
  6513. {/* MQTT Debug Modal */}
  6514. {showMQTTDebug && (
  6515. <MQTTDebugModal
  6516. printerId={printer.id}
  6517. printerName={printer.name}
  6518. onClose={() => setShowMQTTDebug(false)}
  6519. />
  6520. )}
  6521. {showDiagnostic && (
  6522. <ConnectionDiagnosticModal
  6523. printerId={printer.id}
  6524. printerName={printer.name}
  6525. onClose={() => setShowDiagnostic(false)}
  6526. />
  6527. )}
  6528. {showPrinterInfo && (
  6529. <PrinterInfoModal
  6530. printer={printer}
  6531. status={status}
  6532. totalPrintHours={maintenanceInfo?.total_print_hours}
  6533. onClose={closePrinterInfo}
  6534. />
  6535. )}
  6536. {/* Plate Check Result Modal */}
  6537. {plateCheckResult && (
  6538. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6539. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6540. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6541. <div className="flex items-center gap-2">
  6542. {plateCheckResult.needs_calibration ? (
  6543. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6544. ) : plateCheckResult.is_empty ? (
  6545. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6546. ) : (
  6547. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6548. )}
  6549. <h2 className="text-lg font-semibold text-white">
  6550. Build Plate Check
  6551. </h2>
  6552. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6553. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6554. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6555. </span>
  6556. )}
  6557. </div>
  6558. <button
  6559. onClick={() => closePlateCheckModal()}
  6560. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6561. >
  6562. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6563. </button>
  6564. </div>
  6565. <div className="p-4 space-y-4">
  6566. {plateCheckResult.needs_calibration ? (
  6567. <>
  6568. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6569. <p className="font-medium text-blue-700 dark:text-blue-400">
  6570. {t('printers.plateDetection.calibrationRequired')}
  6571. </p>
  6572. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6573. </div>
  6574. <div className="text-sm text-bambu-gray space-y-2">
  6575. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6576. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6577. </div>
  6578. </>
  6579. ) : (
  6580. <>
  6581. <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'}`}>
  6582. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6583. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6584. </p>
  6585. <p className="text-sm text-bambu-gray mt-1">
  6586. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6587. </p>
  6588. </div>
  6589. {plateCheckResult.debug_image_url && (
  6590. <div>
  6591. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6592. <img
  6593. src={plateCheckResult.debug_image_url}
  6594. alt={t('printers.plateDetection.analysisPreview')}
  6595. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6596. />
  6597. <p className="text-xs text-bambu-gray mt-2">
  6598. {t('printers.plateDetection.analysisLegend')}
  6599. </p>
  6600. </div>
  6601. )}
  6602. <p className="text-xs text-bambu-gray">
  6603. {plateCheckResult.message}
  6604. </p>
  6605. </>
  6606. )}
  6607. {/* Saved References Grid */}
  6608. {plateReferences && plateReferences.references.length > 0 && (
  6609. <div className="mt-4">
  6610. <div className="flex items-center gap-2 mb-2">
  6611. <p className="text-sm font-medium text-white shrink-0">
  6612. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6613. </p>
  6614. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6615. </div>
  6616. <div className="grid grid-cols-5 gap-2">
  6617. {plateReferences.references.map((ref) => (
  6618. <div key={ref.index} className="relative group">
  6619. <img
  6620. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6621. alt={ref.label || `Reference ${ref.index + 1}`}
  6622. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6623. />
  6624. {/* Delete button */}
  6625. <button
  6626. onClick={() => handleDeleteRef(ref.index)}
  6627. 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"
  6628. title={t('printers.plateDetection.deleteReference')}
  6629. >
  6630. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6631. </button>
  6632. {/* Label */}
  6633. {editingRefLabel?.index === ref.index ? (
  6634. <input
  6635. type="text"
  6636. value={editingRefLabel.label}
  6637. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6638. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6639. onKeyDown={(e) => {
  6640. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6641. if (e.key === 'Escape') setEditingRefLabel(null);
  6642. }}
  6643. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6644. autoFocus
  6645. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6646. />
  6647. ) : (
  6648. <p
  6649. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6650. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6651. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6652. >
  6653. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6654. </p>
  6655. )}
  6656. {/* Timestamp */}
  6657. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6658. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6659. </p>
  6660. </div>
  6661. ))}
  6662. </div>
  6663. </div>
  6664. )}
  6665. {/* ROI Editor */}
  6666. {!plateCheckResult.needs_calibration && (
  6667. <div className="mt-4">
  6668. <div className="flex items-center justify-between mb-2">
  6669. <div className="flex min-w-0 flex-1 items-center gap-2">
  6670. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6671. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6672. </div>
  6673. {!editingRoi ? (
  6674. <Button
  6675. variant="ghost"
  6676. size="sm"
  6677. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6678. >
  6679. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6680. {t('common.edit')}
  6681. </Button>
  6682. ) : (
  6683. <div className="flex gap-1">
  6684. <Button
  6685. variant="ghost"
  6686. size="sm"
  6687. onClick={() => setEditingRoi(null)}
  6688. disabled={isSavingRoi}
  6689. >
  6690. {t('common.cancel')}
  6691. </Button>
  6692. <Button
  6693. size="sm"
  6694. onClick={handleSaveRoi}
  6695. disabled={isSavingRoi}
  6696. >
  6697. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6698. </Button>
  6699. </div>
  6700. )}
  6701. </div>
  6702. {editingRoi ? (
  6703. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6704. <div className="grid grid-cols-2 gap-3">
  6705. <div>
  6706. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6707. <input
  6708. type="range"
  6709. min="0"
  6710. max="0.9"
  6711. step="0.01"
  6712. value={editingRoi.x}
  6713. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6714. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6715. />
  6716. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6717. </div>
  6718. <div>
  6719. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6720. <input
  6721. type="range"
  6722. min="0"
  6723. max="0.9"
  6724. step="0.01"
  6725. value={editingRoi.y}
  6726. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6727. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6728. />
  6729. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6730. </div>
  6731. <div>
  6732. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6733. <input
  6734. type="range"
  6735. min="0.1"
  6736. max="1"
  6737. step="0.01"
  6738. value={editingRoi.w}
  6739. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6740. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6741. />
  6742. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6743. </div>
  6744. <div>
  6745. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6746. <input
  6747. type="range"
  6748. min="0.1"
  6749. max="1"
  6750. step="0.01"
  6751. value={editingRoi.h}
  6752. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6753. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6754. />
  6755. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6756. </div>
  6757. </div>
  6758. <p className="text-xs text-bambu-gray">
  6759. {t('printers.roi.instruction')}
  6760. </p>
  6761. </div>
  6762. ) : (
  6763. <p className="text-xs text-bambu-gray">
  6764. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6765. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6766. </p>
  6767. )}
  6768. </div>
  6769. )}
  6770. </div>
  6771. <div className="flex justify-end gap-2 p-4">
  6772. {plateCheckResult.needs_calibration ? (
  6773. <>
  6774. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6775. {t('common.cancel')}
  6776. </Button>
  6777. <Button
  6778. onClick={() => handleCalibratePlate()}
  6779. disabled={isCalibrating}
  6780. >
  6781. {isCalibrating ? (
  6782. <>
  6783. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6784. Calibrating...
  6785. </>
  6786. ) : (
  6787. 'Calibrate Empty Plate'
  6788. )}
  6789. </Button>
  6790. </>
  6791. ) : (
  6792. <>
  6793. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6794. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6795. </Button>
  6796. <Button onClick={() => closePlateCheckModal()}>
  6797. Close
  6798. </Button>
  6799. </>
  6800. )}
  6801. </div>
  6802. </div>
  6803. </div>
  6804. )}
  6805. {/* Power On Confirmation */}
  6806. {showPowerOnConfirm && smartPlug && (
  6807. <ConfirmModal
  6808. title={t('printers.confirm.powerOnTitle')}
  6809. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6810. confirmText={t('printers.confirm.powerOnButton')}
  6811. variant="default"
  6812. onConfirm={() => {
  6813. powerControlMutation.mutate('on');
  6814. setShowPowerOnConfirm(false);
  6815. }}
  6816. onCancel={() => setShowPowerOnConfirm(false)}
  6817. />
  6818. )}
  6819. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6820. disconnects MQTT, which stops progress tracking + completion
  6821. notifications for the in-flight job. Idle / FINISH / FAILED states
  6822. skip this dialog and toggle directly. */}
  6823. {confirmMaintenanceEnter && (
  6824. <ConfirmModal
  6825. title={t('printers.maintenance.confirmMidPrintTitle')}
  6826. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6827. confirmText={t('printers.maintenance.menuEnter')}
  6828. variant="danger"
  6829. onConfirm={() => {
  6830. maintenanceMutation.mutate(false);
  6831. setConfirmMaintenanceEnter(false);
  6832. }}
  6833. onCancel={() => setConfirmMaintenanceEnter(false)}
  6834. />
  6835. )}
  6836. {/* Power Off Confirmation */}
  6837. {showPowerOffConfirm && smartPlug && (
  6838. <ConfirmModal
  6839. title={t('printers.confirm.powerOffTitle')}
  6840. message={
  6841. status?.state === 'RUNNING'
  6842. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6843. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6844. }
  6845. confirmText={t('printers.confirm.powerOffButton')}
  6846. variant="danger"
  6847. onConfirm={() => {
  6848. powerControlMutation.mutate('off');
  6849. setShowPowerOffConfirm(false);
  6850. }}
  6851. onCancel={() => setShowPowerOffConfirm(false)}
  6852. />
  6853. )}
  6854. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6855. {haToggleConfirm && (
  6856. <ConfirmModal
  6857. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6858. message={
  6859. status?.state === 'RUNNING'
  6860. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6861. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6862. }
  6863. confirmText={t('printers.confirm.haToggleButton')}
  6864. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6865. onConfirm={() => {
  6866. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6867. setHaToggleConfirm(null);
  6868. }}
  6869. onCancel={() => setHaToggleConfirm(null)}
  6870. />
  6871. )}
  6872. {/* Stop Print Confirmation */}
  6873. {showStopConfirm && (
  6874. <ConfirmModal
  6875. title={t('printers.confirm.stopTitle')}
  6876. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6877. confirmText={t('printers.confirm.stopButton')}
  6878. variant="danger"
  6879. onConfirm={() => {
  6880. stopPrintMutation.mutate();
  6881. setShowStopConfirm(false);
  6882. }}
  6883. onCancel={() => setShowStopConfirm(false)}
  6884. />
  6885. )}
  6886. {/* Pause Print Confirmation */}
  6887. {showPauseConfirm && (
  6888. <ConfirmModal
  6889. title={t('printers.confirm.pauseTitle')}
  6890. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6891. confirmText={t('printers.confirm.pauseButton')}
  6892. variant="default"
  6893. onConfirm={() => {
  6894. pausePrintMutation.mutate();
  6895. setShowPauseConfirm(false);
  6896. }}
  6897. onCancel={() => setShowPauseConfirm(false)}
  6898. />
  6899. )}
  6900. {/* Resume Print Confirmation */}
  6901. {showResumeConfirm && (
  6902. <ConfirmModal
  6903. title={t('printers.confirm.resumeTitle')}
  6904. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6905. confirmText={t('printers.confirm.resumeButton')}
  6906. variant="default"
  6907. onConfirm={() => {
  6908. resumePrintMutation.mutate();
  6909. setShowResumeConfirm(false);
  6910. }}
  6911. onCancel={() => setShowResumeConfirm(false)}
  6912. />
  6913. )}
  6914. {/* Skip Objects Modal */}
  6915. <SkipObjectsModal
  6916. printerId={printer.id}
  6917. isOpen={showSkipObjectsModal}
  6918. onClose={() => setShowSkipObjectsModal(false)}
  6919. />
  6920. {/* HMS Error Modal */}
  6921. {showHMSModal && (
  6922. <HMSErrorModal
  6923. printerName={printer.name}
  6924. errors={status?.hms_errors || []}
  6925. onClose={() => setShowHMSModal(false)}
  6926. printerId={printer.id}
  6927. hasPermission={hasPermission}
  6928. runoutGuidance={runoutGuidance}
  6929. />
  6930. )}
  6931. {/* AI failure detection modal (#1546) */}
  6932. {showAiModal && (
  6933. <AiDetectionModal
  6934. printerName={printer.name}
  6935. detection={aiDetection}
  6936. lastError={aiLastError}
  6937. onClose={() => setShowAiModal(false)}
  6938. />
  6939. )}
  6940. {/* AMS Filament Backup status / control modal (#1762) */}
  6941. {amsBackupModalOpen && status && (
  6942. <AmsBackupModal
  6943. isOpen={amsBackupModalOpen}
  6944. state={status.ams_filament_backup}
  6945. amsUnits={status.ams}
  6946. amsExtruderMap={status.ams_extruder_map}
  6947. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6948. canToggle={hasPermission('printers:control')}
  6949. pending={setAmsBackupMutation.isPending}
  6950. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6951. onClose={() => setAmsBackupModalOpen(false)}
  6952. />
  6953. )}
  6954. {/* AMS History Modal */}
  6955. {amsHistoryModal && (
  6956. <AMSHistoryModal
  6957. isOpen={!!amsHistoryModal}
  6958. onClose={() => setAmsHistoryModal(null)}
  6959. printerId={printer.id}
  6960. printerName={printer.name}
  6961. amsId={amsHistoryModal.amsId}
  6962. amsLabel={amsHistoryModal.amsLabel}
  6963. initialMode={amsHistoryModal.mode}
  6964. thresholds={amsThresholds}
  6965. />
  6966. )}
  6967. {/* Heater History Modal (nozzle / bed / chamber) */}
  6968. {heaterHistoryModal && (
  6969. <HeaterHistoryModal
  6970. isOpen={!!heaterHistoryModal}
  6971. onClose={() => setHeaterHistoryModal(null)}
  6972. printerId={printer.id}
  6973. printerName={printer.name}
  6974. initialKind={heaterHistoryModal.initialKind}
  6975. availableKinds={heaterHistoryModal.availableKinds}
  6976. />
  6977. )}
  6978. {/* Link Spool Modal */}
  6979. {linkSpoolModal && (
  6980. <LinkSpoolModal
  6981. isOpen={!!linkSpoolModal}
  6982. onClose={() => setLinkSpoolModal(null)}
  6983. tagUid={linkSpoolModal.tagUid}
  6984. trayUuid={linkSpoolModal.trayUuid}
  6985. printerId={linkSpoolModal.printerId}
  6986. amsId={linkSpoolModal.amsId}
  6987. trayId={linkSpoolModal.trayId}
  6988. />
  6989. )}
  6990. {/* Assign Spool Modal */}
  6991. {assignSpoolModal && (
  6992. <AssignSpoolModal
  6993. isOpen={!!assignSpoolModal}
  6994. onClose={() => setAssignSpoolModal(null)}
  6995. printerId={assignSpoolModal.printerId}
  6996. amsId={assignSpoolModal.amsId}
  6997. trayId={assignSpoolModal.trayId}
  6998. trayInfo={assignSpoolModal.trayInfo}
  6999. spoolmanEnabled={!!spoolmanEnabled}
  7000. />
  7001. )}
  7002. {/* Configure AMS Slot Modal */}
  7003. {configureSlotModal && (
  7004. <ConfigureAmsSlotModal
  7005. isOpen={!!configureSlotModal}
  7006. onClose={() => setConfigureSlotModal(null)}
  7007. printerId={printer.id}
  7008. slotInfo={configureSlotModal}
  7009. printerModel={mapModelCode(printer.model) || undefined}
  7010. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  7011. onSuccess={() => {
  7012. // Refresh slot presets to show updated profile name
  7013. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7014. // Printer status will update automatically via WebSocket when AMS data changes
  7015. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7016. }}
  7017. />
  7018. )}
  7019. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7020. {feedDirectionRequest && (
  7021. <FeedDirectionModal
  7022. slotLabel={feedDirectionRequest.slotLabel}
  7023. amsId={feedDirectionRequest.amsId}
  7024. slotId={feedDirectionRequest.slotId}
  7025. extruderSlots={status?.extruder_slots ?? {}}
  7026. isLoading={loadAmsTrayMutation.isPending}
  7027. onConfirm={(extruderId) =>
  7028. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7029. }
  7030. onCancel={() => setFeedDirectionRequest(null)}
  7031. />
  7032. )}
  7033. {/* Edit Printer Modal */}
  7034. {showEditModal && (
  7035. <EditPrinterModal
  7036. printer={printer}
  7037. onClose={() => setShowEditModal(false)}
  7038. />
  7039. )}
  7040. {/* Firmware Update Modal */}
  7041. {showFirmwareModal && firmwareInfo && (
  7042. <FirmwareUpdateModal
  7043. printer={printer}
  7044. firmwareInfo={firmwareInfo}
  7045. onClose={() => setShowFirmwareModal(false)}
  7046. />
  7047. )}
  7048. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7049. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7050. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7051. const sliderMin = 35;
  7052. const sliderMax = maxTemp + 10;
  7053. return (
  7054. <>
  7055. {/* Backdrop */}
  7056. <div
  7057. className="fixed inset-0 z-[100]"
  7058. data-testid="drying-popover-backdrop"
  7059. onMouseDown={() => {
  7060. // The click that dismisses the native datetime picker lands
  7061. // here; it must not close the popover. The input is still
  7062. // focused at mousedown, so remember that and swallow the
  7063. // matching click.
  7064. dryingBackdropSkipCloseRef.current =
  7065. dryingAtTimeInputRef.current !== null &&
  7066. document.activeElement === dryingAtTimeInputRef.current;
  7067. }}
  7068. onClick={() => {
  7069. if (dryingBackdropSkipCloseRef.current) {
  7070. dryingBackdropSkipCloseRef.current = false;
  7071. return;
  7072. }
  7073. setDryingPopoverAmsId(null);
  7074. }}
  7075. />
  7076. {/* An 'above' popover is anchored by its bottom edge (CSS
  7077. bottom) so late-appearing content grows it upward, staying on
  7078. screen and glued to the trigger. maxHeight caps to the space
  7079. on the anchored side; when the viewport is too short the body
  7080. scrolls and the footer stays pinned. dvh so iOS Safari's
  7081. bottom toolbar doesn't clip the footer. */}
  7082. <div
  7083. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7084. style={{
  7085. left: dryingPopoverPos.left,
  7086. ...(dryingPopoverPos.placement === 'above'
  7087. ? {
  7088. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7089. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7090. }
  7091. : {
  7092. top: dryingPopoverPos.top,
  7093. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7094. }),
  7095. }}
  7096. onClick={e => e.stopPropagation()}
  7097. >
  7098. {/* Header */}
  7099. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7100. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7101. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7102. </div>
  7103. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7104. {/* Body */}
  7105. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7106. {/* Filament type select */}
  7107. <div>
  7108. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7109. <ToolbarDropdown
  7110. value={dryingFilament}
  7111. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7112. onChange={fil => {
  7113. setDryingFilament(fil);
  7114. const preset = dryingPresets[fil];
  7115. if (preset) {
  7116. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7117. setDryingTemp(preset[key]);
  7118. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7119. }
  7120. }}
  7121. fullWidth
  7122. />
  7123. </div>
  7124. {/* Temperature */}
  7125. <div>
  7126. <div className="flex items-center justify-between mb-1">
  7127. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7128. <div className="flex items-center gap-1">
  7129. <NumberInput
  7130. min={45}
  7131. max={maxTemp}
  7132. value={dryingTemp}
  7133. onChange={setDryingTemp}
  7134. fallback={45}
  7135. 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"
  7136. />
  7137. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7138. </div>
  7139. </div>
  7140. <input
  7141. type="range"
  7142. min={sliderMin}
  7143. max={sliderMax}
  7144. value={dryingTemp}
  7145. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7146. className="w-full h-1 accent-bambu-green cursor-pointer"
  7147. />
  7148. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7149. <span>45°C</span>
  7150. <span>{maxTemp}°C</span>
  7151. </div>
  7152. </div>
  7153. {/* Duration */}
  7154. <div>
  7155. <div className="flex items-center justify-between mb-1">
  7156. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7157. <div className="flex items-center gap-1">
  7158. <NumberInput
  7159. min={1}
  7160. max={24}
  7161. value={dryingDuration}
  7162. onChange={setDryingDuration}
  7163. fallback={1}
  7164. 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"
  7165. />
  7166. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7167. </div>
  7168. </div>
  7169. <input
  7170. type="range"
  7171. min={1}
  7172. max={24}
  7173. value={dryingDuration}
  7174. onChange={e => setDryingDuration(Number(e.target.value))}
  7175. className="w-full h-1 accent-bambu-green cursor-pointer"
  7176. />
  7177. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7178. <span>1h</span>
  7179. <span>24h</span>
  7180. </div>
  7181. </div>
  7182. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7183. filament threaded out into the feed tube. The whole AMS
  7184. rotates as one mechanism (all 4 spools turn together), so a
  7185. single loaded slot locks the entire unit. Bambu per-tray
  7186. `state`: 9 = empty, 10 = spool present but not loaded
  7187. (rotation possible), 11 = loaded into tube (rotation impossible).
  7188. Catches both mid-print (active feed) AND idle-with-threaded-
  7189. filament — the H2D's post-print state leaves filament in the
  7190. tube but tray_now resets to 255, which a tray_now-only check
  7191. would silently miss. */}
  7192. {(() => {
  7193. const targetAms = dryingPopoverAmsId !== null
  7194. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7195. : undefined;
  7196. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7197. tray => tray.state === 11,
  7198. );
  7199. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7200. return (
  7201. <button
  7202. type="button"
  7203. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7204. aria-pressed={rotateChecked}
  7205. disabled={trayLoadedInThisAms}
  7206. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7207. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7208. rotateChecked
  7209. ? 'bg-bambu-green border-bambu-green text-white'
  7210. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7211. }`}
  7212. >
  7213. {t('printers.drying.rotateTray')}
  7214. </button>
  7215. );
  7216. })()}
  7217. {/* Start mode: now / after delay / at time (#2638) */}
  7218. <div>
  7219. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7220. <div className="grid grid-cols-3 gap-1">
  7221. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7222. <button
  7223. key={mode}
  7224. type="button"
  7225. onClick={() => setDryingStartMode(mode)}
  7226. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7227. dryingStartMode === mode
  7228. ? 'bg-bambu-green border-bambu-green text-white'
  7229. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7230. }`}
  7231. >
  7232. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7233. </button>
  7234. ))}
  7235. </div>
  7236. {dryingStartMode === 'delay' && (
  7237. // Inline chips: a dropdown menu would be clipped by
  7238. // the popover's scrollable body.
  7239. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7240. {DRYING_DELAY_OPTIONS.map(min => (
  7241. <button
  7242. key={min}
  7243. type="button"
  7244. aria-pressed={dryingDelayMinutes === min}
  7245. onClick={() => setDryingDelayMinutes(min)}
  7246. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7247. dryingDelayMinutes === min
  7248. ? 'bg-bambu-green border-bambu-green text-white'
  7249. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7250. }`}
  7251. >
  7252. {formatDurationFromHours(min / 60)}
  7253. </button>
  7254. ))}
  7255. </div>
  7256. )}
  7257. {dryingStartMode === 'at_time' && (
  7258. <input
  7259. ref={dryingAtTimeInputRef}
  7260. type="datetime-local"
  7261. data-testid="drying-start-at"
  7262. value={dryingStartAt}
  7263. onChange={e => setDryingStartAt(e.target.value)}
  7264. 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]"
  7265. />
  7266. )}
  7267. </div>
  7268. </div>
  7269. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7270. {/* Footer */}
  7271. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7272. <button
  7273. onClick={() => {
  7274. if (dryingPopoverAmsId !== null) {
  7275. // Clamp rotateTray off when any tray in this AMS is loaded into
  7276. // the tube — the rotate UI is disabled there, but the state may
  7277. // linger as `true` from a previous AMS, or a print may have
  7278. // started while the popover was open. Without this clamp the
  7279. // Start payload would carry rotate_tray=true and firmware would
  7280. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7281. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7282. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7283. tray => tray.state === 11,
  7284. );
  7285. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7286. if (dryingStartMode === 'now') {
  7287. startDryingMutation.mutate({
  7288. amsId: dryingPopoverAmsId,
  7289. temp: dryingTemp,
  7290. duration: dryingDuration,
  7291. filament: dryingFilament,
  7292. rotateTray: rotate,
  7293. });
  7294. } else {
  7295. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7296. if (startAfter) {
  7297. scheduleDryingMutation.mutate({
  7298. amsId: dryingPopoverAmsId,
  7299. temp: dryingTemp,
  7300. duration: dryingDuration,
  7301. filament: dryingFilament,
  7302. rotateTray: rotate,
  7303. startAfter,
  7304. });
  7305. }
  7306. }
  7307. }
  7308. }}
  7309. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7310. data-testid="drying-start-confirm"
  7311. 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"
  7312. >
  7313. {dryingStartMode === 'now'
  7314. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7315. : t('printers.drying.schedule')}
  7316. </button>
  7317. </div>
  7318. </div>
  7319. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7320. since the popover clips its own overflow. */}
  7321. <div
  7322. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7323. style={{
  7324. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7325. top: dryingPopoverPos.anchorY - 5,
  7326. ...(dryingPopoverPos.placement === 'above'
  7327. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7328. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7329. }}
  7330. />
  7331. </>
  7332. );
  7333. })()}
  7334. </Card>
  7335. );
  7336. }
  7337. export function AddPrinterModal({
  7338. onClose,
  7339. onAdd,
  7340. existingSerials,
  7341. }: {
  7342. onClose: () => void;
  7343. onAdd: (data: PrinterCreate) => void;
  7344. existingSerials: string[];
  7345. }) {
  7346. const { t } = useTranslation();
  7347. const [form, setForm] = useState<PrinterCreate>({
  7348. name: '',
  7349. serial_number: '',
  7350. ip_address: '',
  7351. access_code: '',
  7352. model: '',
  7353. location: '',
  7354. auto_archive: true,
  7355. });
  7356. // Discovery state
  7357. const [discovering, setDiscovering] = useState(false);
  7358. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7359. const [discoveryError, setDiscoveryError] = useState('');
  7360. const [hasScanned, setHasScanned] = useState(false);
  7361. const [isDocker, setIsDocker] = useState(false);
  7362. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7363. const [subnet, setSubnet] = useState('');
  7364. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7365. // text input so users can scan a subnet Bambuddy isn't directly on
  7366. // (printer behind a router on a different L3 segment — SSDP multicast
  7367. // won't cross that boundary, only an active unicast scan will). #1564
  7368. const [customSubnet, setCustomSubnet] = useState('');
  7369. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7370. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7371. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7372. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7373. // (not block) when checks fail, so the user doesn't add a printer that
  7374. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7375. // failed result awaiting an explicit "save anyway".
  7376. const [checkingSave, setCheckingSave] = useState(false);
  7377. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7378. // Fetch discovery info on mount + restore the last custom CIDR the user
  7379. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7380. // time they open this modal).
  7381. useEffect(() => {
  7382. discoveryApi.getInfo().then(info => {
  7383. setIsDocker(info.is_docker);
  7384. if (info.subnets.length > 0) {
  7385. setDetectedSubnets(info.subnets);
  7386. setSubnet(info.subnets[0]);
  7387. }
  7388. }).catch(() => {
  7389. // Ignore errors, assume not Docker
  7390. });
  7391. try {
  7392. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7393. if (saved) setCustomSubnet(saved);
  7394. } catch {
  7395. // localStorage unavailable (private mode, quota); recall is opportunistic
  7396. }
  7397. }, []);
  7398. // Filter out already-added printers
  7399. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7400. const handleAddSubmit = async (e: React.FormEvent) => {
  7401. e.preventDefault();
  7402. setCheckingSave(true);
  7403. try {
  7404. const result = await api.diagnoseConnection({
  7405. ip_address: form.ip_address.trim(),
  7406. serial_number: form.serial_number.trim() || undefined,
  7407. access_code: form.access_code || undefined,
  7408. });
  7409. if (result.checks.some((c) => c.status === 'fail')) {
  7410. setSaveWarning(result);
  7411. return;
  7412. }
  7413. } catch {
  7414. // Diagnostic infrastructure failed — never block the save on it.
  7415. } finally {
  7416. setCheckingSave(false);
  7417. }
  7418. onAdd(form);
  7419. };
  7420. const startDiscovery = async () => {
  7421. setDiscoveryError('');
  7422. setDiscovered([]);
  7423. setDiscovering(true);
  7424. setHasScanned(false);
  7425. setScanProgress({ scanned: 0, total: 0 });
  7426. // Native installs fall back to subnet scanning when the user picks
  7427. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7428. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7429. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7430. const wantsSubnetScan = isDocker || useCustomSubnet;
  7431. if (wantsSubnetScan && useCustomSubnet) {
  7432. try {
  7433. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7434. } catch {
  7435. // localStorage write best-effort; user just retypes next time
  7436. }
  7437. }
  7438. try {
  7439. if (wantsSubnetScan) {
  7440. await discoveryApi.startSubnetScan(scanCidr);
  7441. // Poll for scan status and results
  7442. const pollInterval = setInterval(async () => {
  7443. try {
  7444. const status = await discoveryApi.getScanStatus();
  7445. setScanProgress({ scanned: status.scanned, total: status.total });
  7446. const printers = await discoveryApi.getDiscoveredPrinters();
  7447. setDiscovered(printers);
  7448. if (!status.running) {
  7449. clearInterval(pollInterval);
  7450. setDiscovering(false);
  7451. setHasScanned(true);
  7452. }
  7453. } catch (e) {
  7454. console.error('Failed to get scan status:', e);
  7455. }
  7456. }, 500);
  7457. } else {
  7458. // Use SSDP discovery for native installs
  7459. await discoveryApi.startDiscovery(10);
  7460. // Poll for discovered printers every second
  7461. const pollInterval = setInterval(async () => {
  7462. try {
  7463. const printers = await discoveryApi.getDiscoveredPrinters();
  7464. setDiscovered(printers);
  7465. } catch (e) {
  7466. console.error('Failed to get discovered printers:', e);
  7467. }
  7468. }, 1000);
  7469. // Stop after 10 seconds
  7470. setTimeout(async () => {
  7471. clearInterval(pollInterval);
  7472. try {
  7473. await discoveryApi.stopDiscovery();
  7474. } catch {
  7475. // Ignore stop errors
  7476. }
  7477. setDiscovering(false);
  7478. setHasScanned(true);
  7479. // Final fetch
  7480. try {
  7481. const printers = await discoveryApi.getDiscoveredPrinters();
  7482. setDiscovered(printers);
  7483. } catch (e) {
  7484. console.error('Failed to get final discovered printers:', e);
  7485. }
  7486. }, 10000);
  7487. }
  7488. } catch (e) {
  7489. console.error('Failed to start discovery:', e);
  7490. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7491. setDiscovering(false);
  7492. setHasScanned(true);
  7493. }
  7494. };
  7495. // Reuse module-level mapModelCode
  7496. const selectPrinter = (printer: DiscoveredPrinter) => {
  7497. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7498. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7499. setForm({
  7500. ...form,
  7501. name: printer.name || '',
  7502. serial_number: serialNumber,
  7503. ip_address: printer.ip_address,
  7504. model: mapModelCode(printer.model),
  7505. });
  7506. // Clear discovery results after selection
  7507. setDiscovered([]);
  7508. };
  7509. // Cleanup discovery on unmount
  7510. useEffect(() => {
  7511. return () => {
  7512. discoveryApi.stopDiscovery().catch(() => {});
  7513. discoveryApi.stopSubnetScan().catch(() => {});
  7514. };
  7515. }, []);
  7516. // Close on Escape key
  7517. useEffect(() => {
  7518. const handleKeyDown = (e: KeyboardEvent) => {
  7519. if (e.key === 'Escape') onClose();
  7520. };
  7521. window.addEventListener('keydown', handleKeyDown);
  7522. return () => window.removeEventListener('keydown', handleKeyDown);
  7523. }, [onClose]);
  7524. return (
  7525. <>
  7526. <div
  7527. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7528. onClick={onClose}
  7529. >
  7530. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7531. <CardContent>
  7532. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7533. {/* Discovery Section */}
  7534. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7535. {/* Subnet picker — always visible. The dropdown lists detected
  7536. interface subnets and a "Custom..." sentinel that reveals
  7537. a CIDR text input for printers on a different L3 segment
  7538. (router, VLAN, etc.). #1564 */}
  7539. <div className="mb-3">
  7540. <label className="block text-sm text-bambu-gray mb-1">
  7541. {t('printers.discovery.subnetToScan')}
  7542. </label>
  7543. {detectedSubnets.length > 0 ? (
  7544. <select
  7545. 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"
  7546. value={useCustomSubnet ? '__custom__' : subnet}
  7547. onChange={(e) => {
  7548. if (e.target.value === '__custom__') {
  7549. setUseCustomSubnet(true);
  7550. } else {
  7551. setUseCustomSubnet(false);
  7552. setSubnet(e.target.value);
  7553. }
  7554. }}
  7555. disabled={discovering}
  7556. >
  7557. {detectedSubnets.map(s => (
  7558. <option key={s} value={s}>{s}</option>
  7559. ))}
  7560. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7561. </select>
  7562. ) : (
  7563. <input
  7564. type="text"
  7565. 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"
  7566. value={subnet}
  7567. onChange={(e) => setSubnet(e.target.value)}
  7568. placeholder="192.168.1.0/24"
  7569. disabled={discovering}
  7570. />
  7571. )}
  7572. {useCustomSubnet && (
  7573. <input
  7574. type="text"
  7575. aria-label={t('printers.discovery.customSubnetLabel')}
  7576. 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"
  7577. value={customSubnet}
  7578. onChange={(e) => setCustomSubnet(e.target.value)}
  7579. placeholder="10.1.1.0/24"
  7580. disabled={discovering}
  7581. />
  7582. )}
  7583. <p className="mt-1 text-xs text-bambu-gray">
  7584. {isDocker
  7585. ? t('printers.discovery.dockerNote')
  7586. : t('printers.discovery.customSubnetNote')}
  7587. </p>
  7588. </div>
  7589. <Button
  7590. type="button"
  7591. variant="secondary"
  7592. onClick={startDiscovery}
  7593. disabled={discovering}
  7594. className="w-full"
  7595. >
  7596. {discovering ? (
  7597. <>
  7598. <Loader2 className="w-4 h-4 animate-spin" />
  7599. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7600. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7601. : t('printers.discovery.scanning')}
  7602. </>
  7603. ) : (
  7604. <>
  7605. <Search className="w-4 h-4" />
  7606. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7607. </>
  7608. )}
  7609. </Button>
  7610. {discoveryError && (
  7611. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7612. )}
  7613. {newPrinters.length > 0 && (
  7614. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7615. {newPrinters.map((printer) => (
  7616. <div
  7617. key={printer.serial}
  7618. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7619. onClick={() => selectPrinter(printer)}
  7620. >
  7621. <div className="min-w-0 flex-1">
  7622. <p className="font-medium text-white text-sm truncate">
  7623. {printer.name || printer.serial}
  7624. </p>
  7625. <p className="text-xs text-bambu-gray truncate">
  7626. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7627. {printer.serial.startsWith('unknown-') && (
  7628. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7629. )}
  7630. </p>
  7631. </div>
  7632. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7633. </div>
  7634. ))}
  7635. </div>
  7636. )}
  7637. {discovering && (
  7638. <p className="mt-2 text-sm text-bambu-gray text-center">
  7639. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7640. </p>
  7641. )}
  7642. {hasScanned && !discovering && discovered.length === 0 && (
  7643. <p className="mt-2 text-sm text-bambu-gray text-center">
  7644. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7645. </p>
  7646. )}
  7647. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7648. <p className="mt-2 text-sm text-bambu-gray text-center">
  7649. {t('printers.discovery.allConfigured')}
  7650. </p>
  7651. )}
  7652. </div>
  7653. <form onSubmit={handleAddSubmit} className="space-y-4">
  7654. <div>
  7655. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7656. <input
  7657. type="text"
  7658. required
  7659. 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"
  7660. value={form.name}
  7661. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7662. placeholder={t('printers.modal.myPrinter')}
  7663. />
  7664. </div>
  7665. <div>
  7666. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7667. <input
  7668. type="text"
  7669. required
  7670. 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])?)*)"
  7671. 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"
  7672. value={form.ip_address}
  7673. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7674. placeholder="192.168.1.100 or printer.local"
  7675. />
  7676. </div>
  7677. <div>
  7678. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7679. <input
  7680. type="text"
  7681. required
  7682. 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"
  7683. value={form.serial_number}
  7684. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7685. placeholder="01P00A000000000"
  7686. />
  7687. </div>
  7688. <div>
  7689. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7690. <input
  7691. type="password"
  7692. required
  7693. 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"
  7694. value={form.access_code}
  7695. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7696. placeholder={t('printers.modal.fromPrinterSettings')}
  7697. />
  7698. </div>
  7699. <div>
  7700. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7701. <select
  7702. 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"
  7703. value={form.model || ''}
  7704. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7705. >
  7706. <option value="">{t('printers.modal.selectModel')}</option>
  7707. <optgroup label="A1 Series">
  7708. <option value="A1">A1</option>
  7709. <option value="A1 Mini">A1 Mini</option>
  7710. </optgroup>
  7711. <optgroup label="A2 Series">
  7712. <option value="A2L">A2L</option>
  7713. </optgroup>
  7714. <optgroup label="H2 Series">
  7715. <option value="H2C">H2C</option>
  7716. <option value="H2D">H2D</option>
  7717. <option value="H2D Pro">H2D Pro</option>
  7718. <option value="H2S">H2S</option>
  7719. </optgroup>
  7720. <optgroup label="P Series">
  7721. <option value="P1P">P1P</option>
  7722. <option value="P1S">P1S</option>
  7723. <option value="P2S">P2S</option>
  7724. </optgroup>
  7725. <optgroup label="X1 Series">
  7726. <option value="X1">X1</option>
  7727. <option value="X1C">X1 Carbon</option>
  7728. <option value="X1E">X1E</option>
  7729. </optgroup>
  7730. <optgroup label="X2 Series">
  7731. <option value="X2D">X2D</option>
  7732. </optgroup>
  7733. </select>
  7734. </div>
  7735. <div>
  7736. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7737. <input
  7738. type="text"
  7739. 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"
  7740. value={form.location || ''}
  7741. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7742. placeholder={t('printers.modal.locationPlaceholder')}
  7743. maxLength={100}
  7744. />
  7745. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7746. </div>
  7747. <div className="flex items-center gap-2">
  7748. <input
  7749. type="checkbox"
  7750. id="auto_archive"
  7751. checked={form.auto_archive}
  7752. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7753. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7754. />
  7755. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7756. {t('printers.modal.autoArchiveLabel')}
  7757. </label>
  7758. </div>
  7759. <button
  7760. type="button"
  7761. onClick={() => setShowDiagnostic(true)}
  7762. disabled={!form.ip_address.trim()}
  7763. 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"
  7764. >
  7765. <Stethoscope className="w-4 h-4" />
  7766. {t('diagnostic.runButton')}
  7767. </button>
  7768. {saveWarning ? (
  7769. <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">
  7770. <div className="flex items-start gap-2">
  7771. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7772. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7773. </div>
  7774. <DiagnosticChecklist result={saveWarning} />
  7775. <div className="flex gap-3">
  7776. <Button
  7777. type="button"
  7778. variant="secondary"
  7779. onClick={() => setSaveWarning(null)}
  7780. className="flex-1"
  7781. >
  7782. {t('printers.addPreflight.back')}
  7783. </Button>
  7784. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7785. {t('printers.addPreflight.saveAnyway')}
  7786. </Button>
  7787. </div>
  7788. </div>
  7789. ) : (
  7790. <div className="flex gap-3 pt-2">
  7791. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7792. {t('common.cancel')}
  7793. </Button>
  7794. <Button type="submit" disabled={checkingSave} className="flex-1">
  7795. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7796. </Button>
  7797. </div>
  7798. )}
  7799. </form>
  7800. </CardContent>
  7801. </Card>
  7802. </div>
  7803. {showDiagnostic && (
  7804. <ConnectionDiagnosticModal
  7805. connection={{
  7806. ip_address: form.ip_address.trim(),
  7807. serial_number: form.serial_number.trim() || undefined,
  7808. access_code: form.access_code || undefined,
  7809. }}
  7810. printerName={form.name || null}
  7811. onClose={() => setShowDiagnostic(false)}
  7812. />
  7813. )}
  7814. </>
  7815. );
  7816. }
  7817. function FirmwareUpdateModal({
  7818. printer,
  7819. firmwareInfo,
  7820. onClose,
  7821. }: {
  7822. printer: Printer;
  7823. firmwareInfo: FirmwareUpdateInfo;
  7824. onClose: () => void;
  7825. }) {
  7826. const { t } = useTranslation();
  7827. const queryClient = useQueryClient();
  7828. const { showToast } = useToast();
  7829. const { hasPermission } = useAuth();
  7830. const canUpdate = hasPermission('firmware:update');
  7831. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7832. const [isUploading, setIsUploading] = useState(false);
  7833. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7834. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7835. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7836. );
  7837. // Prepare check query — runs when a version is selected and user can update
  7838. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7839. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7840. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7841. staleTime: 30000,
  7842. enabled: !!selectedVersion && canUpdate && !isUploading,
  7843. });
  7844. // Start upload mutation
  7845. const uploadMutation = useMutation({
  7846. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7847. onSuccess: () => {
  7848. setIsUploading(true);
  7849. // Start polling for status
  7850. const interval = setInterval(async () => {
  7851. try {
  7852. const status = await firmwareApi.getUploadStatus(printer.id);
  7853. setUploadStatus(status);
  7854. if (status.status === 'complete' || status.status === 'error') {
  7855. clearInterval(interval);
  7856. setPollInterval(null);
  7857. setIsUploading(false);
  7858. if (status.status === 'complete') {
  7859. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7860. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7861. }
  7862. }
  7863. } catch {
  7864. // Ignore errors during polling
  7865. }
  7866. }, 2000);
  7867. setPollInterval(interval);
  7868. },
  7869. onError: (error: Error) => {
  7870. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7871. setIsUploading(false);
  7872. },
  7873. });
  7874. // Cleanup on unmount
  7875. useEffect(() => {
  7876. return () => {
  7877. if (pollInterval) clearInterval(pollInterval);
  7878. };
  7879. }, [pollInterval]);
  7880. const handleStartUpload = () => {
  7881. setUploadStatus(null);
  7882. uploadMutation.mutate();
  7883. };
  7884. return (
  7885. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7886. <Card className="w-full max-w-md mx-4">
  7887. <CardContent>
  7888. <div className="flex items-start gap-3 mb-4">
  7889. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7890. {firmwareInfo.update_available
  7891. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7892. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7893. </div>
  7894. <div className="flex-1">
  7895. <h3 className="text-lg font-semibold text-white">
  7896. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7897. </h3>
  7898. <p className="text-sm text-bambu-gray mt-1">
  7899. {printer.name}
  7900. </p>
  7901. </div>
  7902. </div>
  7903. {/* Version Info */}
  7904. {(() => {
  7905. const selectedEntry = selectedVersion
  7906. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7907. : null;
  7908. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7909. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7910. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7911. return (
  7912. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7913. <div className="flex justify-between items-center text-sm">
  7914. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7915. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7916. {firmwareInfo.current_version || t('common.unknown')}
  7917. </span>
  7918. </div>
  7919. {showSecondLine && (
  7920. <div className="flex justify-between items-center text-sm mt-1">
  7921. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7922. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7923. </div>
  7924. )}
  7925. {displayNotes && (
  7926. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7927. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7928. {t('printers.firmwareModal.releaseNotes')}
  7929. </summary>
  7930. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7931. {displayNotes}
  7932. </div>
  7933. </details>
  7934. )}
  7935. </div>
  7936. );
  7937. })()}
  7938. {/* Available versions list */}
  7939. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7940. <div className="mb-4">
  7941. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7942. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7943. {firmwareInfo.available_versions.map((v) => {
  7944. const isCurrent = firmwareInfo.current_version === v.version;
  7945. const isSelected = selectedVersion === v.version;
  7946. const cmp = firmwareInfo.current_version
  7947. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7948. : 0;
  7949. const relLabel = isCurrent
  7950. ? t('printers.firmwareModal.currentBadge')
  7951. : cmp > 0
  7952. ? t('printers.firmwareModal.newerBadge')
  7953. : t('printers.firmwareModal.olderBadge');
  7954. const relClass = isCurrent
  7955. ? 'text-bambu-gray'
  7956. : cmp > 0
  7957. ? 'text-orange-700 dark:text-orange-400'
  7958. : 'text-blue-700 dark:text-blue-400';
  7959. return (
  7960. <button
  7961. key={v.version}
  7962. type="button"
  7963. disabled={!v.file_available || !canUpdate || isCurrent}
  7964. onClick={() => setSelectedVersion(v.version)}
  7965. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7966. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7967. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7968. >
  7969. <div className="flex items-center gap-2 min-w-0">
  7970. <span className="font-mono text-white">{v.version}</span>
  7971. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7972. </div>
  7973. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7974. isCurrent
  7975. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7976. : v.file_available
  7977. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7978. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7979. }`}>
  7980. {isCurrent
  7981. ? t('printers.firmwareModal.installed')
  7982. : v.file_available
  7983. ? t('printers.firmwareModal.usable')
  7984. : t('printers.firmwareModal.unavailable')}
  7985. </span>
  7986. </button>
  7987. );
  7988. })}
  7989. </div>
  7990. </div>
  7991. )}
  7992. {/* Status / Progress (only when a version is selected) */}
  7993. {!selectedVersion ? null : isPreparing ? (
  7994. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7995. <Loader2 className="w-4 h-4 animate-spin" />
  7996. {t('printers.firmwareModal.checkingPrereqs')}
  7997. </div>
  7998. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7999. <div className="mb-4">
  8000. {prepareInfo.can_proceed ? (
  8001. <div className="flex items-center gap-2 text-bambu-green text-sm">
  8002. <Box className="w-4 h-4" />
  8003. {t('printers.firmwareModal.sdCardReady')}
  8004. </div>
  8005. ) : (
  8006. <div className="space-y-1">
  8007. {prepareInfo.errors.map((error, i) => (
  8008. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  8009. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  8010. {error}
  8011. </div>
  8012. ))}
  8013. </div>
  8014. )}
  8015. </div>
  8016. ) : null}
  8017. {/* Upload Progress */}
  8018. {(isUploading || uploadStatus) && uploadStatus && (
  8019. <div className="mb-4">
  8020. <div className="flex items-center justify-between text-sm mb-1">
  8021. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8022. <span className="text-white">{uploadStatus.progress}%</span>
  8023. </div>
  8024. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8025. <div
  8026. className={`h-2 rounded-full transition-all ${
  8027. uploadStatus.status === 'error' ? 'bg-status-error' :
  8028. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8029. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8030. style={{ width: `${uploadStatus.progress}%` }}
  8031. />
  8032. </div>
  8033. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8034. {uploadStatus.error && (
  8035. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8036. )}
  8037. </div>
  8038. )}
  8039. {/* Success Message */}
  8040. {uploadStatus?.status === 'complete' && (
  8041. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8042. <p className="text-sm text-bambu-green font-medium mb-2">
  8043. {t('printers.firmwareModal.uploadedSuccess')}
  8044. </p>
  8045. <p className="text-xs text-bambu-gray">
  8046. {t('printers.firmwareModal.applyInstructions')}
  8047. </p>
  8048. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8049. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8050. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8051. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8052. <li>{t('printers.firmwareModal.step4')}</li>
  8053. </ol>
  8054. </div>
  8055. )}
  8056. {/* Buttons */}
  8057. <div className="flex gap-2 justify-end">
  8058. <Button variant="secondary" onClick={onClose}>
  8059. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8060. </Button>
  8061. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8062. <Button
  8063. onClick={handleStartUpload}
  8064. disabled={uploadMutation.isPending}
  8065. >
  8066. {uploadMutation.isPending ? (
  8067. <>
  8068. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8069. {t('printers.firmwareModal.starting')}
  8070. </>
  8071. ) : (
  8072. <>
  8073. <Download className="w-4 h-4 mr-2" />
  8074. {t('printers.firmwareModal.uploadFirmware')}
  8075. </>
  8076. )}
  8077. </Button>
  8078. )}
  8079. </div>
  8080. </CardContent>
  8081. </Card>
  8082. </div>
  8083. );
  8084. }
  8085. function EditPrinterModal({
  8086. printer,
  8087. onClose,
  8088. }: {
  8089. printer: Printer;
  8090. onClose: () => void;
  8091. }) {
  8092. const { t } = useTranslation();
  8093. const queryClient = useQueryClient();
  8094. const { showToast } = useToast();
  8095. const { authEnabled, isAdmin } = useAuth();
  8096. const [form, setForm] = useState({
  8097. name: printer.name,
  8098. ip_address: printer.ip_address,
  8099. access_code: '',
  8100. model: printer.model || '',
  8101. location: printer.location || '',
  8102. auto_archive: printer.auto_archive,
  8103. is_active: printer.is_active,
  8104. wear_cost_per_hour: printer.wear_cost_per_hour ? String(printer.wear_cost_per_hour) : '',
  8105. });
  8106. const { data: settings } = useQuery({ queryKey: ['settings'], queryFn: api.getSettings });
  8107. const currency = getCurrencySymbol(settings?.currency || 'USD');
  8108. // Groups can be given a location (#1727), so a move changes who can use the
  8109. // printer. Non-admins can't read groups; the server refuses their move instead.
  8110. const { data: groups } = useQuery({
  8111. queryKey: ['groups'],
  8112. queryFn: () => api.getGroups(),
  8113. enabled: authEnabled && isAdmin,
  8114. });
  8115. const newLocation = form.location.trim();
  8116. const accessChangedFor =
  8117. newLocation !== (printer.location || '')
  8118. ? (groups ?? [])
  8119. .filter(
  8120. (g) =>
  8121. g.restrict_printers &&
  8122. (g.locations ?? []).some((loc) => loc === printer.location || loc === newLocation)
  8123. )
  8124. .map((g) => g.name)
  8125. : [];
  8126. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8127. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8128. const [checkingSave, setCheckingSave] = useState(false);
  8129. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8130. const updateMutation = useMutation({
  8131. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8132. onSuccess: () => {
  8133. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8134. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8135. onClose();
  8136. },
  8137. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8138. });
  8139. // Close on Escape key
  8140. useEffect(() => {
  8141. const handleKeyDown = (e: KeyboardEvent) => {
  8142. if (e.key === 'Escape') onClose();
  8143. };
  8144. window.addEventListener('keydown', handleKeyDown);
  8145. return () => window.removeEventListener('keydown', handleKeyDown);
  8146. }, [onClose]);
  8147. const doSave = () => {
  8148. const data: Partial<PrinterCreate> = {
  8149. name: form.name,
  8150. ip_address: form.ip_address,
  8151. model: form.model || undefined,
  8152. // null clears it; leaving it out kept the old location
  8153. location: form.location.trim() || null,
  8154. auto_archive: form.auto_archive,
  8155. is_active: form.is_active,
  8156. // Empty or 0 turns wear cost off for this printer (#694)
  8157. wear_cost_per_hour: Number(form.wear_cost_per_hour) > 0 ? Number(form.wear_cost_per_hour) : null,
  8158. };
  8159. // Only include access_code if it was changed
  8160. if (form.access_code) {
  8161. data.access_code = form.access_code;
  8162. }
  8163. updateMutation.mutate(data);
  8164. };
  8165. const handleSubmit = async (e: React.FormEvent) => {
  8166. e.preventDefault();
  8167. setCheckingSave(true);
  8168. try {
  8169. const result = await api.diagnoseConnection({
  8170. ip_address: form.ip_address.trim(),
  8171. serial_number: printer.serial_number,
  8172. access_code: form.access_code || undefined,
  8173. });
  8174. if (result.checks.some((c) => c.status === 'fail')) {
  8175. setSaveWarning(result);
  8176. return;
  8177. }
  8178. } catch {
  8179. // Diagnostic infrastructure failed — never block the save on it.
  8180. } finally {
  8181. setCheckingSave(false);
  8182. }
  8183. doSave();
  8184. };
  8185. return (
  8186. <div
  8187. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8188. onClick={onClose}
  8189. >
  8190. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8191. <CardContent>
  8192. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8193. <form onSubmit={handleSubmit} className="space-y-4">
  8194. <div>
  8195. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8196. <input
  8197. type="text"
  8198. required
  8199. 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"
  8200. value={form.name}
  8201. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8202. placeholder={t('printers.modal.myPrinter')}
  8203. />
  8204. </div>
  8205. <div>
  8206. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8207. <input
  8208. type="text"
  8209. required
  8210. 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])?)*)"
  8211. 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"
  8212. value={form.ip_address}
  8213. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8214. placeholder="192.168.1.100 or printer.local"
  8215. />
  8216. </div>
  8217. <div>
  8218. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8219. <input
  8220. type="text"
  8221. disabled
  8222. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8223. value={printer.serial_number}
  8224. />
  8225. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8226. </div>
  8227. <div>
  8228. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8229. <input
  8230. type="password"
  8231. 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"
  8232. value={form.access_code}
  8233. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8234. placeholder={t('printers.accessCodePlaceholder')}
  8235. />
  8236. </div>
  8237. <div>
  8238. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8239. <select
  8240. 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"
  8241. value={form.model}
  8242. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8243. >
  8244. <option value="">{t('printers.modal.selectModel')}</option>
  8245. <optgroup label="A1 Series">
  8246. <option value="A1">A1</option>
  8247. <option value="A1 Mini">A1 Mini</option>
  8248. </optgroup>
  8249. <optgroup label="A2 Series">
  8250. <option value="A2L">A2L</option>
  8251. </optgroup>
  8252. <optgroup label="H2 Series">
  8253. <option value="H2C">H2C</option>
  8254. <option value="H2D">H2D</option>
  8255. <option value="H2D Pro">H2D Pro</option>
  8256. <option value="H2S">H2S</option>
  8257. </optgroup>
  8258. <optgroup label="P Series">
  8259. <option value="P1P">P1P</option>
  8260. <option value="P1S">P1S</option>
  8261. <option value="P2S">P2S</option>
  8262. </optgroup>
  8263. <optgroup label="X1 Series">
  8264. <option value="X1">X1</option>
  8265. <option value="X1C">X1 Carbon</option>
  8266. <option value="X1E">X1E</option>
  8267. </optgroup>
  8268. <optgroup label="X2 Series">
  8269. <option value="X2D">X2D</option>
  8270. </optgroup>
  8271. </select>
  8272. </div>
  8273. <div>
  8274. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8275. <input
  8276. type="text"
  8277. 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"
  8278. value={form.location}
  8279. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8280. placeholder={t('printers.modal.locationPlaceholder')}
  8281. maxLength={100}
  8282. />
  8283. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8284. {accessChangedFor.length > 0 && (
  8285. <p className="flex items-start gap-1.5 text-xs text-yellow-700 dark:text-yellow-400 mt-1">
  8286. <AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-px" />
  8287. {t('printerAccess.moveWarning', { groups: accessChangedFor.join(', ') })}
  8288. </p>
  8289. )}
  8290. </div>
  8291. <div className="flex items-center gap-2">
  8292. <input
  8293. type="checkbox"
  8294. id="edit_auto_archive"
  8295. checked={form.auto_archive}
  8296. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8297. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8298. />
  8299. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8300. {t('printers.modal.autoArchiveLabel')}
  8301. </label>
  8302. </div>
  8303. <div>
  8304. <label htmlFor="edit_wear_cost" className="block text-sm text-bambu-gray mb-1">
  8305. {t('printers.modal.wearCostLabel', { currency })}
  8306. </label>
  8307. <input
  8308. id="edit_wear_cost"
  8309. type="number"
  8310. min={0}
  8311. step="0.01"
  8312. inputMode="decimal"
  8313. 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"
  8314. value={form.wear_cost_per_hour}
  8315. onChange={(e) => setForm({ ...form, wear_cost_per_hour: e.target.value })}
  8316. placeholder="0.00"
  8317. />
  8318. <p className="text-xs text-bambu-gray mt-1">{t('printers.modal.wearCostHelp')}</p>
  8319. </div>
  8320. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8321. is_active because the user-facing concept is "is this printer
  8322. in maintenance" not "is it active". */}
  8323. <div>
  8324. <div className="flex items-center gap-2">
  8325. <input
  8326. type="checkbox"
  8327. id="edit_maintenance_mode"
  8328. checked={!form.is_active}
  8329. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8330. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8331. />
  8332. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8333. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8334. {t('printers.maintenance.editFieldLabel')}
  8335. </label>
  8336. </div>
  8337. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8338. {t('printers.maintenance.editFieldHelp')}
  8339. </p>
  8340. </div>
  8341. {saveWarning ? (
  8342. <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">
  8343. <div className="flex items-start gap-2">
  8344. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8345. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8346. </div>
  8347. <DiagnosticChecklist result={saveWarning} />
  8348. <div className="flex gap-3">
  8349. <Button
  8350. type="button"
  8351. variant="secondary"
  8352. onClick={() => setSaveWarning(null)}
  8353. className="flex-1"
  8354. >
  8355. {t('printers.addPreflight.back')}
  8356. </Button>
  8357. <Button
  8358. type="button"
  8359. onClick={doSave}
  8360. className="flex-1"
  8361. disabled={updateMutation.isPending}
  8362. >
  8363. {t('printers.addPreflight.saveAnyway')}
  8364. </Button>
  8365. </div>
  8366. </div>
  8367. ) : (
  8368. <div className="flex gap-3 pt-4">
  8369. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8370. {t('common.cancel')}
  8371. </Button>
  8372. <Button
  8373. type="submit"
  8374. className="flex-1"
  8375. disabled={updateMutation.isPending || checkingSave}
  8376. >
  8377. {checkingSave
  8378. ? t('printers.addPreflight.checking')
  8379. : updateMutation.isPending
  8380. ? t('common.saving')
  8381. : t('printers.modal.saveChanges')}
  8382. </Button>
  8383. </div>
  8384. )}
  8385. </form>
  8386. </CardContent>
  8387. </Card>
  8388. </div>
  8389. );
  8390. }
  8391. // Component to check if a printer is offline (for power dropdown)
  8392. function usePrinterOfflineStatus(printerId: number) {
  8393. const { data: status } = useQuery({
  8394. queryKey: ['printerStatus', printerId],
  8395. queryFn: () => api.getPrinterStatus(printerId),
  8396. refetchInterval: 30000,
  8397. });
  8398. return !status?.connected;
  8399. }
  8400. // Power dropdown item for an offline printer
  8401. function PowerDropdownItem({
  8402. printer,
  8403. plug,
  8404. onPowerOn,
  8405. isPowering,
  8406. }: {
  8407. printer: Printer;
  8408. plug: { id: number; name: string };
  8409. onPowerOn: (plugId: number) => void;
  8410. isPowering: boolean;
  8411. }) {
  8412. const isOffline = usePrinterOfflineStatus(printer.id);
  8413. // Fetch plug status
  8414. const { data: plugStatus } = useQuery({
  8415. queryKey: ['smartPlugStatus', plug.id],
  8416. queryFn: () => api.getSmartPlugStatus(plug.id),
  8417. refetchInterval: 10000,
  8418. });
  8419. // Only show if printer is offline
  8420. if (!isOffline) {
  8421. return null;
  8422. }
  8423. return (
  8424. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8425. <div className="flex items-center gap-2 min-w-0">
  8426. <span className="text-sm text-white truncate">{printer.name}</span>
  8427. {plugStatus && (
  8428. <span
  8429. className={`text-xs px-1.5 py-0.5 rounded ${
  8430. plugStatus.state === 'ON'
  8431. ? 'bg-bambu-green/20 text-bambu-green'
  8432. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8433. }`}
  8434. >
  8435. {plugStatus.state || '?'}
  8436. </span>
  8437. )}
  8438. </div>
  8439. <button
  8440. onClick={() => onPowerOn(plug.id)}
  8441. disabled={isPowering || plugStatus?.state === 'ON'}
  8442. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8443. plugStatus?.state === 'ON'
  8444. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8445. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8446. }`}
  8447. >
  8448. <Power className="w-3 h-3" />
  8449. {isPowering ? '...' : 'On'}
  8450. </button>
  8451. </div>
  8452. );
  8453. }
  8454. export function PrintersPage() {
  8455. const { t } = useTranslation();
  8456. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8457. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8458. const accentButtonClass = {
  8459. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8460. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8461. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8462. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8463. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8464. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8465. }[activeAccent];
  8466. const [showAddModal, setShowAddModal] = useState(false);
  8467. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8468. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8469. });
  8470. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8471. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8472. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8473. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8474. });
  8475. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8476. return localStorage.getItem('printerSortAsc') !== 'false';
  8477. });
  8478. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8479. const [cardSize, setCardSize] = useState<number>(() => {
  8480. const saved = localStorage.getItem('printerCardSize');
  8481. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8482. });
  8483. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8484. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8485. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8486. });
  8487. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8488. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8489. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8490. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8491. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8492. });
  8493. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8494. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8495. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8496. });
  8497. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8498. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8499. // Defaulting to 'full' because the cards already show this info — users who
  8500. // pick cam-wall view still want to glance the same details without flipping.
  8501. // Kept apart from the card size: S on the cards also means the compact
  8502. // layout, and a wall of 2 cameras wants big tiles next to small cards (#2735).
  8503. const [camWallTileSize, setCamWallTileSize] = useState<number>(() => {
  8504. const saved = parseInt(localStorage.getItem('camWallTileSize') || '', 10);
  8505. return saved >= 1 && saved <= 4 ? saved : DEFAULT_CAM_WALL_TILE_SIZE;
  8506. });
  8507. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8508. const saved = localStorage.getItem('camWallStatusMode');
  8509. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8510. });
  8511. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8512. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8513. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8514. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8515. requestAnimationFrame(() => {
  8516. requestAnimationFrame(() => {
  8517. const card = document.getElementById(`printer-card-${printerId}`);
  8518. if (!card) return;
  8519. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8520. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8521. window.scrollTo({
  8522. top: Math.max(0, top),
  8523. behavior: 'smooth',
  8524. });
  8525. });
  8526. });
  8527. }, []);
  8528. const openCompactCard = useCallback((printerId: number) => {
  8529. setCompactDrilldownPrinterId(printerId);
  8530. setCardSize(2);
  8531. localStorage.setItem('printerCardSize', '2');
  8532. scrollPrinterIntoView(printerId);
  8533. }, [scrollPrinterIntoView]);
  8534. const returnToCompactCards = useCallback(() => {
  8535. const printerId = compactDrilldownPrinterId;
  8536. setCompactDrilldownPrinterId(null);
  8537. setCardSize(1);
  8538. localStorage.setItem('printerCardSize', '1');
  8539. if (printerId != null) {
  8540. scrollPrinterIntoView(printerId);
  8541. }
  8542. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8543. const [search, setSearch] = useState('');
  8544. // Both filters persist like every other preference on this page (#2833).
  8545. // `search` deliberately does not: a box that silently refills itself on
  8546. // return is more surprising than a dropdown that remembers.
  8547. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8548. // Validated on read: a value the dropdown no longer offers would filter
  8549. // every printer out, and nothing would explain why.
  8550. const saved = localStorage.getItem('printerStatusFilter');
  8551. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8552. });
  8553. const [locationFilter, setLocationFilter] = useState<string>(
  8554. () => localStorage.getItem('printerLocationFilter') || 'all'
  8555. );
  8556. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8557. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8558. try {
  8559. const saved = localStorage.getItem('printerCollapsedSections');
  8560. return saved ? JSON.parse(saved) : {};
  8561. } catch { return {}; }
  8562. });
  8563. const queryClient = useQueryClient();
  8564. const { showToast } = useToast();
  8565. const { hasPermission } = useAuth();
  8566. // Which way the camera buttons open a stream. Chosen per click from the
  8567. // button's own menu; null until this browser has made a choice, so the
  8568. // stored setting below can act as the default a fresh browser starts from.
  8569. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8570. () => readStoredCameraViewMode()
  8571. );
  8572. // Embedded camera viewer state - supports multiple simultaneous viewers
  8573. // Persisted to localStorage so cameras reopen after navigation
  8574. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8575. const saved = localStorage.getItem('openEmbeddedCameras');
  8576. if (saved) {
  8577. try {
  8578. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8579. return new Map(cameras.map(c => [c.id, c]));
  8580. } catch {
  8581. return new Map();
  8582. }
  8583. }
  8584. return new Map();
  8585. });
  8586. // Persist open cameras to localStorage when they change
  8587. useEffect(() => {
  8588. const cameras = Array.from(embeddedCameraPrinters.values());
  8589. if (cameras.length > 0) {
  8590. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8591. } else {
  8592. localStorage.removeItem('openEmbeddedCameras');
  8593. }
  8594. }, [embeddedCameraPrinters]);
  8595. const { data: printers, isLoading } = useQuery({
  8596. queryKey: ['printers'],
  8597. queryFn: api.getPrinters,
  8598. });
  8599. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8600. // so users with printers:read but no settings:read still get the values needed
  8601. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8602. const { data: settings } = useQuery({
  8603. queryKey: ['ui-preferences'],
  8604. queryFn: api.getUiPreferences,
  8605. });
  8606. // Only once the preferences are in: deciding on `undefined` meant a check
  8607. // switched off still went out once per printer on every page load.
  8608. const firmwareChecksOn = settings !== undefined && settings.check_printer_firmware !== false;
  8609. // Parse user-configured temperature/fan presets once, with defensive fallback
  8610. // to built-in defaults on parse failure (validators on the backend already
  8611. // reject malformed writes, so this is just forward-compat).
  8612. const effectiveNozzleTempPresets = useMemo(
  8613. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8614. [settings?.nozzle_temp_presets],
  8615. );
  8616. const effectiveBedTempPresets = useMemo(
  8617. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8618. [settings?.bed_temp_presets],
  8619. );
  8620. const effectiveChamberTempPresets = useMemo(
  8621. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8622. [settings?.chamber_temp_presets],
  8623. );
  8624. const effectiveFanSpeedPresets = useMemo(
  8625. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8626. [settings?.fan_speed_presets],
  8627. );
  8628. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8629. const effectiveDryingPresets = useMemo(() => {
  8630. if (settings?.drying_presets) {
  8631. try {
  8632. const userPresets = JSON.parse(settings.drying_presets);
  8633. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8634. return { ...DRYING_PRESETS, ...userPresets };
  8635. }
  8636. } catch { /* ignore parse errors, use defaults */ }
  8637. }
  8638. return DRYING_PRESETS;
  8639. }, [settings?.drying_presets]);
  8640. // The local choice wins over the stored one: someone without settings:update
  8641. // cannot write their pick back, and a preference that silently reverted on
  8642. // the next render would be worse than none at all.
  8643. const cameraViewMode: CameraViewMode =
  8644. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8645. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8646. storeCameraViewMode(mode);
  8647. setChosenCameraViewMode(mode);
  8648. // Best effort, and only a default for other browsers -- the choice is
  8649. // already in effect here. Users below settings:update simply keep theirs
  8650. // locally, which is why the failure is logged rather than surfaced.
  8651. if (hasPermission('settings:update')) {
  8652. api.updateSettings({ camera_view_mode: mode })
  8653. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8654. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8655. }
  8656. }, [hasPermission, queryClient]);
  8657. // Fetch all smart plugs to know which printers have them
  8658. const { data: smartPlugs } = useQuery({
  8659. queryKey: ['smart-plugs'],
  8660. queryFn: api.getSmartPlugs,
  8661. });
  8662. // Fetch maintenance overview for all printers to show badges
  8663. const { data: maintenanceOverview } = useQuery({
  8664. queryKey: ['maintenanceOverview'],
  8665. queryFn: api.getMaintenanceOverview,
  8666. staleTime: 60 * 1000, // 1 minute
  8667. });
  8668. // Live AI failure detection state for the card badges (#1546). Matches the
  8669. // 10s refetch of the Failure Detection settings panel.
  8670. const { data: obicoPrinterStatus } = useQuery({
  8671. queryKey: ['obico-printer-status'],
  8672. queryFn: api.getObicoPrinterStatus,
  8673. refetchInterval: 10000,
  8674. });
  8675. // Badge visibility: detection enabled AND this printer in the monitored set
  8676. // (monitored_printers null = all). Live per-print state is passed separately.
  8677. const isAiMonitored = useCallback(
  8678. (printerId: number) =>
  8679. obicoPrinterStatus?.enabled === true &&
  8680. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8681. [obicoPrinterStatus],
  8682. );
  8683. // Fetch Spoolman status to enable link spool feature
  8684. const { data: spoolmanStatus } = useQuery({
  8685. queryKey: ['spoolman-status'],
  8686. queryFn: api.getSpoolmanStatus,
  8687. staleTime: 60 * 1000, // 1 minute
  8688. });
  8689. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8690. // Fetch Spoolman settings to get sync mode
  8691. const { data: spoolmanSettings } = useQuery({
  8692. queryKey: ['spoolman-settings'],
  8693. queryFn: api.getSpoolmanSettings,
  8694. enabled: !!spoolmanEnabled,
  8695. staleTime: 60 * 1000, // 1 minute
  8696. });
  8697. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8698. // Fetch unlinked spools to know if link button should be enabled
  8699. const { data: unlinkedSpools } = useQuery({
  8700. queryKey: ['unlinked-spools'],
  8701. queryFn: api.getUnlinkedSpools,
  8702. enabled: !!spoolmanEnabled,
  8703. staleTime: 30 * 1000, // 30 seconds
  8704. });
  8705. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8706. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8707. const { data: linkedSpoolsData } = useQuery({
  8708. queryKey: ['linked-spools'],
  8709. queryFn: api.getLinkedSpools,
  8710. enabled: !!spoolmanEnabled,
  8711. staleTime: 30 * 1000, // 30 seconds
  8712. });
  8713. const linkedSpools = linkedSpoolsData?.linked;
  8714. // Fetch spool assignments for inventory feature
  8715. const { data: spoolAssignments } = useQuery({
  8716. queryKey: ['spool-assignments'],
  8717. queryFn: () => api.getAssignments(),
  8718. enabled: hasPermission('inventory:view_assignments'),
  8719. staleTime: 30 * 1000,
  8720. });
  8721. const unassignMutation = useMutation({
  8722. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8723. api.unassignSpool(printerId, amsId, trayId),
  8724. onSuccess: () => {
  8725. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8726. },
  8727. });
  8728. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8729. queryKey: ['spoolman-inventory-spools'],
  8730. queryFn: () => api.getSpoolmanInventorySpools(false),
  8731. enabled: !!spoolmanEnabled,
  8732. staleTime: 30 * 1000,
  8733. });
  8734. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8735. queryKey: ['spoolman-slot-assignments'],
  8736. queryFn: () => api.getSpoolmanSlotAssignments(),
  8737. enabled: !!spoolmanEnabled,
  8738. staleTime: 30 * 1000,
  8739. });
  8740. const unassignSpoolmanMutation = useMutation({
  8741. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8742. onSuccess: () => {
  8743. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8744. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8745. },
  8746. });
  8747. // Helper to find assignment for a specific slot
  8748. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8749. return spoolAssignments?.find(
  8750. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8751. );
  8752. };
  8753. // Create a map of printer_id -> maintenance info for quick lookup
  8754. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8755. (acc, overview) => {
  8756. acc[overview.printer_id] = {
  8757. due_count: overview.due_count,
  8758. warning_count: overview.warning_count,
  8759. total_print_hours: overview.total_print_hours,
  8760. };
  8761. return acc;
  8762. },
  8763. {} as Record<number, PrinterMaintenanceInfo>
  8764. ) || {};
  8765. // Create a map of printer_id -> smart plug
  8766. const smartPlugByPrinter = smartPlugs?.reduce(
  8767. (acc, plug) => {
  8768. if (plug.printer_id) {
  8769. acc[plug.printer_id] = plug;
  8770. }
  8771. return acc;
  8772. },
  8773. {} as Record<number, typeof smartPlugs[0]>
  8774. ) || {};
  8775. const addMutation = useMutation({
  8776. mutationFn: api.createPrinter,
  8777. onSuccess: () => {
  8778. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8779. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8780. setShowAddModal(false);
  8781. },
  8782. onError: (error: Error) => {
  8783. // Localized message when the backend returns a stable error code;
  8784. // the raw message is an English fallback for non-UI clients.
  8785. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8786. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8787. return;
  8788. }
  8789. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8790. },
  8791. });
  8792. const powerOnMutation = useMutation({
  8793. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8794. onSuccess: () => {
  8795. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8796. setPoweringOn(null);
  8797. },
  8798. onError: () => {
  8799. setPoweringOn(null);
  8800. },
  8801. });
  8802. // Bulk selection state
  8803. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8804. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8805. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8806. const [bulkActionPending, setBulkActionPending] = useState(false);
  8807. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8808. const toggleSelect = useCallback((id: number) => {
  8809. setSelectedPrinterIds(prev => {
  8810. const next = new Set(prev);
  8811. if (next.has(id)) next.delete(id);
  8812. else next.add(id);
  8813. return next;
  8814. });
  8815. }, []);
  8816. const clearSelection = useCallback(() => {
  8817. setSelectedPrinterIds(new Set());
  8818. setIsSelectionMode(false);
  8819. }, []);
  8820. // Escape key exits selection mode
  8821. useEffect(() => {
  8822. const handleKeyDown = (e: KeyboardEvent) => {
  8823. if (e.key === 'Escape' && selectionMode) {
  8824. clearSelection();
  8825. }
  8826. };
  8827. window.addEventListener('keydown', handleKeyDown);
  8828. return () => window.removeEventListener('keydown', handleKeyDown);
  8829. }, [selectionMode, clearSelection]);
  8830. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8831. setBulkActionPending(true);
  8832. const ids = Array.from(selectedPrinterIds);
  8833. // Filter to only applicable printers based on cached state
  8834. const applicableIds = ids.filter(id => {
  8835. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8836. // clearPlate is checked before the connection filter: it only releases a
  8837. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8838. // down — every other action here needs to reach the machine (#2864).
  8839. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8840. if (!status?.connected) return false;
  8841. switch (action) {
  8842. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8843. case 'pause': return status.state === 'RUNNING';
  8844. case 'resume': return status.state === 'PAUSE';
  8845. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8846. default: return false;
  8847. }
  8848. });
  8849. if (applicableIds.length === 0) {
  8850. showToast(t('printers.bulk.noneApplicable'), 'error');
  8851. setBulkActionPending(false);
  8852. setBulkConfirmAction(null);
  8853. return;
  8854. }
  8855. const apiCall = {
  8856. stop: api.stopPrint,
  8857. pause: api.pausePrint,
  8858. resume: api.resumePrint,
  8859. clearPlate: api.clearPlate,
  8860. clearHMS: api.clearHMSErrors,
  8861. }[action];
  8862. const results = await Promise.allSettled(
  8863. applicableIds.map(id => apiCall(id))
  8864. );
  8865. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8866. const failed = results.filter(r => r.status === 'rejected').length;
  8867. if (failed === 0) {
  8868. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8869. } else {
  8870. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8871. }
  8872. // Invalidate status queries for affected printers
  8873. applicableIds.forEach(id => {
  8874. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8875. });
  8876. setBulkActionPending(false);
  8877. setBulkConfirmAction(null);
  8878. }, [selectedPrinterIds, queryClient, showToast, t]);
  8879. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8880. // Actions that need confirmation
  8881. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8882. setBulkConfirmAction(action);
  8883. } else {
  8884. executeBulkAction(action);
  8885. }
  8886. }, [executeBulkAction]);
  8887. const toggleHideDisconnected = () => {
  8888. const newValue = !hideDisconnected;
  8889. setHideDisconnected(newValue);
  8890. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8891. };
  8892. const handleSortChange = (newSort: SortOption) => {
  8893. setSortBy(newSort);
  8894. localStorage.setItem('printerSortBy', newSort);
  8895. };
  8896. const handleStatusFilterChange = (value: string) => {
  8897. setStatusFilter(value);
  8898. localStorage.setItem('printerStatusFilter', value);
  8899. };
  8900. const handleLocationFilterChange = (value: string) => {
  8901. setLocationFilter(value);
  8902. localStorage.setItem('printerLocationFilter', value);
  8903. };
  8904. const toggleSortDirection = () => {
  8905. const newAsc = !sortAsc;
  8906. setSortAsc(newAsc);
  8907. localStorage.setItem('printerSortAsc', String(newAsc));
  8908. };
  8909. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8910. const getGridClasses = () => {
  8911. switch (cardSize) {
  8912. 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
  8913. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8914. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8915. case 4: return 'grid-cols-1'; // XL: single column, full width
  8916. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8917. }
  8918. };
  8919. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8920. // Increment version counter whenever a printer status cache entry is updated so
  8921. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8922. useEffect(() => {
  8923. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8924. if (
  8925. event.type === 'updated' &&
  8926. Array.isArray(event.query.queryKey) &&
  8927. event.query.queryKey[0] === 'printerStatus'
  8928. ) {
  8929. setStatusCacheVersion(v => v + 1);
  8930. }
  8931. });
  8932. return unsubscribe;
  8933. }, [queryClient]);
  8934. // Filter printers by search term, status, and location
  8935. const filteredPrinters = useMemo(() => {
  8936. if (!printers) return [];
  8937. let result = printers;
  8938. // Text search
  8939. if (search.trim()) {
  8940. const q = search.trim().toLowerCase();
  8941. result = result.filter(p =>
  8942. p.name.toLowerCase().includes(q) ||
  8943. (p.model || '').toLowerCase().includes(q) ||
  8944. (p.location || '').toLowerCase().includes(q) ||
  8945. (p.serial_number || '').toLowerCase().includes(q)
  8946. );
  8947. }
  8948. // Location filter
  8949. if (locationFilter !== 'all') {
  8950. result = result.filter(p => (p.location || '') === locationFilter);
  8951. }
  8952. // Status filter
  8953. if (statusFilter !== 'all') {
  8954. result = result.filter(p => {
  8955. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8956. if (!status?.connected) return statusFilter === 'offline';
  8957. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8958. switch (statusFilter) {
  8959. case 'printing': return status.state === 'RUNNING';
  8960. case 'paused': return status.state === 'PAUSE';
  8961. case 'finished': return status.state === 'FINISH';
  8962. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8963. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8964. case 'offline': return false; // Connected printers are never offline
  8965. default: return true;
  8966. }
  8967. });
  8968. }
  8969. return result;
  8970. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8971. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8972. // Derive unique locations for the location filter dropdown
  8973. const availableLocations = useMemo(() => {
  8974. if (!printers) return [];
  8975. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8976. }, [printers]);
  8977. // A saved location can outlive what it matched -- renamed, cleared, or the
  8978. // only printer that had it deleted. The dropdown is rendered only while some
  8979. // printer has a location, so a stale one would hide every printer *and* the
  8980. // control to undo it, leaving an empty page and no way back (#2833).
  8981. // Deliberately waits for `printers`: it is undefined while the query is in
  8982. // flight, and acting on the empty list that produces would throw the saved
  8983. // filter away every time the page loads.
  8984. useEffect(() => {
  8985. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8986. setLocationFilter('all');
  8987. localStorage.setItem('printerLocationFilter', 'all');
  8988. }, [printers, availableLocations, locationFilter]);
  8989. // Sort printers based on selected option
  8990. const sortedPrinters = useMemo(() => {
  8991. const sorted = [...filteredPrinters];
  8992. switch (sortBy) {
  8993. case 'name':
  8994. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8995. break;
  8996. case 'model':
  8997. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8998. break;
  8999. case 'location':
  9000. // Sort by location, with ungrouped printers last
  9001. sorted.sort((a, b) => {
  9002. const locA = a.location || '';
  9003. const locB = b.location || '';
  9004. if (!locA && locB) return 1;
  9005. if (locA && !locB) return -1;
  9006. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  9007. });
  9008. break;
  9009. case 'status':
  9010. // Sort by status: HMS errors > printing > idle > offline
  9011. sorted.sort((a, b) => {
  9012. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  9013. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  9014. const getPriority = (s: typeof statusA) => {
  9015. if (!s?.connected) return 3; // offline
  9016. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  9017. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  9018. if (s.state === 'RUNNING') return 1; // printing
  9019. return 2; // idle
  9020. };
  9021. return getPriority(statusA) - getPriority(statusB);
  9022. });
  9023. break;
  9024. case 'eta':
  9025. sorted.sort((a, b) => {
  9026. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  9027. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  9028. const tier = (s: typeof statusA) => {
  9029. if (!s?.connected) return 3; // offline last
  9030. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  9031. if (s.state === 'RUNNING') return 1; // printing without ETA
  9032. return 2; // idle
  9033. };
  9034. const ta = tier(statusA);
  9035. const tb = tier(statusB);
  9036. if (ta !== tb) return ta - tb;
  9037. if (ta === 0) {
  9038. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  9039. if (diff !== 0) return diff;
  9040. }
  9041. return a.name.localeCompare(b.name);
  9042. });
  9043. break;
  9044. }
  9045. // Apply ascending/descending
  9046. if (!sortAsc) {
  9047. sorted.reverse();
  9048. }
  9049. return sorted;
  9050. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  9051. const selectAll = useCallback(() => {
  9052. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  9053. setIsSelectionMode(true);
  9054. }, [sortedPrinters]);
  9055. const selectByState = useCallback((state: PrinterState) => {
  9056. setSelectedPrinterIds(prev => {
  9057. const next = new Set(prev);
  9058. sortedPrinters.forEach(p => {
  9059. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  9060. if (classifyPrinterStatus(status) === state) next.add(p.id);
  9061. });
  9062. return next;
  9063. });
  9064. setIsSelectionMode(true);
  9065. }, [sortedPrinters, queryClient]);
  9066. const selectByLocation = useCallback((location: string) => {
  9067. setSelectedPrinterIds(prev => {
  9068. const next = new Set(prev);
  9069. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9070. return next;
  9071. });
  9072. setIsSelectionMode(true);
  9073. }, [sortedPrinters]);
  9074. const selectByModel = useCallback((model: string) => {
  9075. setSelectedPrinterIds(prev => {
  9076. const next = new Set(prev);
  9077. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9078. return next;
  9079. });
  9080. setIsSelectionMode(true);
  9081. }, [sortedPrinters]);
  9082. const toggleSectionCollapse = useCallback((key: string) => {
  9083. setCollapsedSections(prev => {
  9084. const next = { ...prev, [key]: !prev[key] };
  9085. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9086. return next;
  9087. });
  9088. }, []);
  9089. // Group printers when sorted by location, status, or model
  9090. const groupedPrinters = useMemo(() => {
  9091. if (sortBy === 'name' || sortBy === 'eta') return null;
  9092. const groups: Record<string, typeof sortedPrinters> = {};
  9093. if (sortBy === 'location') {
  9094. sortedPrinters.forEach(printer => {
  9095. const location = printer.location || 'Ungrouped';
  9096. if (!groups[location]) groups[location] = [];
  9097. groups[location].push(printer);
  9098. });
  9099. } else if (sortBy === 'model') {
  9100. sortedPrinters.forEach(printer => {
  9101. const model = printer.model || 'Unknown';
  9102. if (!groups[model]) groups[model] = [];
  9103. groups[model].push(printer);
  9104. });
  9105. } else if (sortBy === 'status') {
  9106. sortedPrinters.forEach(printer => {
  9107. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9108. const group = classifyPrinterStatus(status);
  9109. if (!groups[group]) groups[group] = [];
  9110. groups[group].push(printer);
  9111. });
  9112. }
  9113. return groups;
  9114. // 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
  9115. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9116. const toolbarRef = useRef<HTMLDivElement>(null);
  9117. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9118. const expandedToolbarWidthRef = useRef(0);
  9119. const [compactToolbar, setCompactToolbar] = useState(false);
  9120. const measureToolbar = useCallback(() => {
  9121. const toolbar = toolbarRef.current;
  9122. if (!toolbar) return;
  9123. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9124. if (measuredControlsWidth) {
  9125. expandedToolbarWidthRef.current = measuredControlsWidth;
  9126. }
  9127. const searchMinimumWidth = 220;
  9128. const gapWidth = 8;
  9129. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9130. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9131. }, []);
  9132. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9133. useLayoutEffect(() => {
  9134. measureToolbar();
  9135. const toolbar = toolbarRef.current;
  9136. if (!toolbar) return;
  9137. if (typeof ResizeObserver === 'undefined') {
  9138. window.addEventListener('resize', measureToolbar);
  9139. return () => window.removeEventListener('resize', measureToolbar);
  9140. }
  9141. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9142. resizeObserver.observe(toolbar);
  9143. window.addEventListener('resize', measureToolbar);
  9144. return () => {
  9145. resizeObserver.disconnect();
  9146. window.removeEventListener('resize', measureToolbar);
  9147. };
  9148. }, [
  9149. measureToolbar,
  9150. printers?.length,
  9151. availableLocations.length,
  9152. hideDisconnected,
  9153. smartPlugCount,
  9154. ]);
  9155. const renderFilterControls = (inMenu = false) => (
  9156. <>
  9157. {/* Status filter */}
  9158. {printers && printers.length > 0 && (
  9159. <ToolbarDropdown
  9160. value={statusFilter}
  9161. onChange={handleStatusFilterChange}
  9162. fullWidth={inMenu}
  9163. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9164. />
  9165. )}
  9166. {/* Location filter — only shown when at least one printer has a location */}
  9167. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9168. <ToolbarDropdown
  9169. value={locationFilter}
  9170. onChange={handleLocationFilterChange}
  9171. fullWidth={inMenu}
  9172. options={[
  9173. { value: 'all', label: t('printers.filter.allLocations') },
  9174. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9175. ]}
  9176. />
  9177. )}
  9178. <button
  9179. type="button"
  9180. onClick={toggleHideDisconnected}
  9181. aria-pressed={hideDisconnected}
  9182. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9183. hideDisconnected
  9184. ? 'bg-bambu-green border-bambu-green text-white'
  9185. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9186. }`}
  9187. >
  9188. {t('printers.hideOffline')}
  9189. </button>
  9190. </>
  9191. );
  9192. const renderViewControls = (inMenu = false) => (
  9193. <>
  9194. {/* Sort dropdown */}
  9195. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9196. <ToolbarDropdown<SortOption>
  9197. value={sortBy}
  9198. onChange={handleSortChange}
  9199. fullWidth={inMenu}
  9200. options={[
  9201. { value: 'name', label: t('printers.sort.name') },
  9202. { value: 'status', label: t('printers.sort.status') },
  9203. { value: 'model', label: t('printers.sort.model') },
  9204. { value: 'location', label: t('printers.sort.location') },
  9205. { value: 'eta', label: t('printers.sort.eta') },
  9206. ]}
  9207. />
  9208. <button
  9209. onClick={toggleSortDirection}
  9210. 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"
  9211. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9212. >
  9213. {sortAsc ? (
  9214. <ArrowUp className="w-4 h-4 text-white" />
  9215. ) : (
  9216. <ArrowDown className="w-4 h-4 text-white" />
  9217. )}
  9218. </button>
  9219. <RouterLink
  9220. to="/printer-locations"
  9221. 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"
  9222. title={t('printers.locations.title')}
  9223. aria-label={t('printers.locations.title')}
  9224. >
  9225. <Box className="w-4 h-4 text-bambu-green" />
  9226. </RouterLink>
  9227. </div>
  9228. {/* Page view toggle: Cards / Cam Wall */}
  9229. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9230. <button
  9231. type="button"
  9232. onClick={() => {
  9233. setPageView('cards');
  9234. localStorage.setItem('printerPageView', 'cards');
  9235. }}
  9236. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9237. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9238. }`}
  9239. title={t('printers.pageView.cards')}
  9240. aria-pressed={pageView === 'cards'}
  9241. >
  9242. <LayoutGrid className="w-3.5 h-3.5" />
  9243. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9244. </button>
  9245. <button
  9246. type="button"
  9247. onClick={() => {
  9248. setPageView('camwall');
  9249. localStorage.setItem('printerPageView', 'camwall');
  9250. }}
  9251. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9252. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9253. }`}
  9254. title={t('printers.pageView.camWall')}
  9255. aria-pressed={pageView === 'camwall'}
  9256. disabled={!hasPermission('camera:view')}
  9257. >
  9258. <MonitorPlay className="w-3.5 h-3.5" />
  9259. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9260. </button>
  9261. </div>
  9262. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9263. view, and the page a kiosk token points at. Only offered once the wall
  9264. is the active view, so it doesn't compete with the toggle above. */}
  9265. {pageView === 'camwall' && hasPermission('camera:view') && (
  9266. <RouterLink
  9267. to="/camwall"
  9268. 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' : ''}`}
  9269. title={t('printers.pageView.openCamWallPage')}
  9270. >
  9271. <ExternalLink className="w-3.5 h-3.5" />
  9272. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9273. </RouterLink>
  9274. )}
  9275. {/* Card size selector */}
  9276. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9277. {cardSizeLabels.map((label, index) => {
  9278. const size = index + 1;
  9279. const isSelected = (pageView === 'camwall' ? camWallTileSize : cardSize) === size;
  9280. return (
  9281. <button
  9282. key={label}
  9283. onClick={() => {
  9284. if (pageView === 'camwall') {
  9285. setCamWallTileSize(size);
  9286. localStorage.setItem('camWallTileSize', String(size));
  9287. return;
  9288. }
  9289. setCompactDrilldownPrinterId(null);
  9290. setCardSize(size);
  9291. localStorage.setItem('printerCardSize', String(size));
  9292. }}
  9293. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9294. index === 0 ? 'rounded-l-lg' : ''
  9295. } ${
  9296. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9297. } ${
  9298. isSelected
  9299. ? 'bg-bambu-green text-white'
  9300. : 'text-white hover:bg-bambu-dark-tertiary'
  9301. }`}
  9302. title={t(`printers.${pageView === 'camwall' ? 'camWall.tileSize' : 'cardSize'}.${['small', 'medium', 'large', 'extraLarge'][index]}`)}
  9303. >
  9304. {label}
  9305. </button>
  9306. );
  9307. })}
  9308. </div>
  9309. </>
  9310. );
  9311. const renderActionControls = (inMenu = false) => (
  9312. <>
  9313. {/* Bulk select toggle */}
  9314. <button
  9315. onClick={() => {
  9316. if (selectionMode) clearSelection();
  9317. else setIsSelectionMode(true);
  9318. }}
  9319. 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' : ''} ${
  9320. selectionMode
  9321. ? 'bg-bambu-green border-bambu-green text-white'
  9322. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9323. }`}
  9324. title={t('printers.bulk.select')}
  9325. disabled={!hasPermission('printers:control')}
  9326. >
  9327. <CheckSquare className="w-4 h-4" />
  9328. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9329. </button>
  9330. {/* Power dropdown for offline printers with smart plugs */}
  9331. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9332. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9333. <button
  9334. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9335. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9336. inMenu
  9337. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9338. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9339. }`}
  9340. >
  9341. <span className="flex items-center gap-1.5">
  9342. <Power className="w-4 h-4" />
  9343. {t('printers.powerOn')}
  9344. </span>
  9345. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9346. </button>
  9347. {showPowerDropdown && (
  9348. <>
  9349. {/* Backdrop to close dropdown */}
  9350. <div
  9351. className="fixed inset-0 z-10"
  9352. onClick={() => setShowPowerDropdown(false)}
  9353. />
  9354. <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">
  9355. <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">
  9356. {t('printers.offlinePrintersWithPlugs')}
  9357. </div>
  9358. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9359. <PowerDropdownItem
  9360. key={printer.id}
  9361. printer={printer}
  9362. plug={smartPlugByPrinter[printer.id]}
  9363. onPowerOn={(plugId) => {
  9364. setPoweringOn(plugId);
  9365. powerOnMutation.mutate(plugId);
  9366. }}
  9367. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9368. />
  9369. ))}
  9370. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9371. <div className="px-3 py-2 text-sm text-bambu-gray">
  9372. No printers with smart plugs
  9373. </div>
  9374. )}
  9375. </div>
  9376. </>
  9377. )}
  9378. </div>
  9379. )}
  9380. <Button
  9381. onClick={() => setShowAddModal(true)}
  9382. disabled={!hasPermission('printers:create')}
  9383. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9384. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9385. >
  9386. <Plus className="w-4 h-4" />
  9387. {t('printers.addPrinter')}
  9388. </Button>
  9389. </>
  9390. );
  9391. return (
  9392. <div className="p-4 md:p-8">
  9393. <div className="space-y-3 mb-6">
  9394. <div>
  9395. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9396. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9397. {t('printers.title')}
  9398. </h1>
  9399. <StatusSummaryBar printers={printers} />
  9400. </div>
  9401. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9402. {/* Only show search bar when printers exist */}
  9403. {printers && printers.length > 0 && (
  9404. <div className="relative min-w-0 flex-1">
  9405. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9406. <input
  9407. type="search"
  9408. name="printer-search"
  9409. autoComplete="off"
  9410. data-1p-ignore
  9411. data-lpignore="true"
  9412. value={search}
  9413. onChange={(e) => setSearch(e.target.value)}
  9414. placeholder={t('printers.search')}
  9415. aria-label={t('printers.search')}
  9416. 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"
  9417. />
  9418. {search && (
  9419. <button
  9420. type="button"
  9421. aria-label={t('common.clear')}
  9422. onClick={() => setSearch('')}
  9423. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9424. >
  9425. <X className="w-4 h-4" />
  9426. </button>
  9427. )}
  9428. </div>
  9429. )}
  9430. <div
  9431. ref={expandedToolbarControlsRef}
  9432. aria-hidden={compactToolbar}
  9433. inert={compactToolbar}
  9434. 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`}
  9435. >
  9436. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9437. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9438. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9439. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9440. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9441. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9442. </div>
  9443. {compactToolbar && (
  9444. <div className="ml-auto flex items-center justify-end gap-1">
  9445. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9446. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9447. </ToolbarMenu>
  9448. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9449. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9450. </ToolbarMenu>
  9451. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9452. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9453. </ToolbarMenu>
  9454. </div>
  9455. )}
  9456. </div>
  9457. </div>
  9458. {isLoading ? (
  9459. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9460. ) : printers?.length === 0 ? (
  9461. <Card>
  9462. <CardContent className="text-center py-12">
  9463. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9464. <Button
  9465. onClick={() => setShowAddModal(true)}
  9466. disabled={!hasPermission('printers:create')}
  9467. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9468. >
  9469. <Plus className="w-4 h-4" />
  9470. {t('printers.addPrinter')}
  9471. </Button>
  9472. </CardContent>
  9473. </Card>
  9474. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9475. <Card>
  9476. <CardContent className="text-center py-12">
  9477. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9478. </CardContent>
  9479. </Card>
  9480. ) : pageView === 'camwall' ? (
  9481. <CameraWall
  9482. printers={sortedPrinters}
  9483. maxLive={camWallMaxLive}
  9484. snapshotIntervalSec={camWallSnapshotSec}
  9485. tileSize={camWallTileSize}
  9486. onTileClick={(id, name) => {
  9487. // A wall tile has no room for a split button, so it follows the
  9488. // mode the card buttons last chose.
  9489. if (cameraViewMode === 'embedded') {
  9490. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9491. } else {
  9492. openCameraWindow(id);
  9493. }
  9494. }}
  9495. statusMode={camWallStatusMode}
  9496. onChangeMaxLive={(next) => {
  9497. setCamWallMaxLive(next);
  9498. localStorage.setItem('camWallMaxLive', String(next));
  9499. }}
  9500. onChangeSnapshotIntervalSec={(next) => {
  9501. setCamWallSnapshotSec(next);
  9502. localStorage.setItem('camWallSnapshotSec', String(next));
  9503. }}
  9504. onChangeStatusMode={(next) => {
  9505. setCamWallStatusMode(next);
  9506. localStorage.setItem('camWallStatusMode', next);
  9507. }}
  9508. />
  9509. ) : groupedPrinters ? (
  9510. /* Grouped view (location, status, or model) */
  9511. <div className="space-y-6">
  9512. {(() => {
  9513. const keys = sortBy === 'status'
  9514. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9515. : Object.keys(groupedPrinters);
  9516. // For status grouping, asc/desc flips the fixed priority order
  9517. // (asc = error→offline, desc = offline→error). This matches the
  9518. // sort-toggle behaviour for other groupings.
  9519. return (sortAsc ? keys : [...keys].reverse());
  9520. })().map((groupKey) => {
  9521. const groupPrinters = groupedPrinters[groupKey];
  9522. const collapseKey = `${sortBy}:${groupKey}`;
  9523. const isOpen = !collapsedSections[collapseKey];
  9524. const dot = sortBy === 'status'
  9525. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9526. : 'bg-bambu-green';
  9527. const label = sortBy === 'status'
  9528. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9529. : groupKey;
  9530. return (
  9531. <Collapsible
  9532. key={groupKey}
  9533. open={isOpen}
  9534. onToggle={() => toggleSectionCollapse(collapseKey)}
  9535. summaryClassName="py-1"
  9536. summary={
  9537. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9538. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9539. {label}
  9540. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9541. {selectionMode && (
  9542. <button
  9543. onClick={(e) => {
  9544. e.stopPropagation();
  9545. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9546. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9547. else if (sortBy === 'model') selectByModel(groupKey);
  9548. }}
  9549. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9550. >
  9551. {t('printers.bulk.selectAll')}
  9552. </button>
  9553. )}
  9554. </h2>
  9555. }
  9556. >
  9557. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9558. {groupPrinters.map((printer) => (
  9559. <PrinterCard
  9560. key={printer.id}
  9561. printer={printer}
  9562. hideIfDisconnected={hideDisconnected}
  9563. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9564. viewMode={viewMode}
  9565. cardSize={cardSize}
  9566. amsThresholds={settings ? {
  9567. humidityGood: Number(settings.ams_humidity_good) || 40,
  9568. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9569. tempGood: Number(settings.ams_temp_good) || 28,
  9570. tempFair: Number(settings.ams_temp_fair) || 35,
  9571. } : undefined}
  9572. spoolmanEnabled={spoolmanEnabled}
  9573. hasUnlinkedSpools={hasUnlinkedSpools}
  9574. linkedSpools={linkedSpools}
  9575. spoolmanUrl={spoolmanStatus?.url}
  9576. spoolmanSyncMode={spoolmanSyncMode}
  9577. onGetAssignment={getAssignment}
  9578. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9579. spoolmanSpools={spoolmanSpools}
  9580. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9581. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9582. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9583. timeFormat={settings?.time_format || 'system'}
  9584. cameraViewMode={cameraViewMode}
  9585. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9586. onSelectCameraViewMode={selectCameraViewMode}
  9587. checkPrinterFirmware={firmwareChecksOn}
  9588. dryingPresets={effectiveDryingPresets}
  9589. nozzleTempPresets={effectiveNozzleTempPresets}
  9590. bedTempPresets={effectiveBedTempPresets}
  9591. chamberTempPresets={effectiveChamberTempPresets}
  9592. fanSpeedPresets={effectiveFanSpeedPresets}
  9593. requirePlateClear={settings?.require_plate_clear === true}
  9594. selectionMode={selectionMode}
  9595. isSelected={selectedPrinterIds.has(printer.id)}
  9596. onToggleSelect={toggleSelect}
  9597. onOpenCompactCard={openCompactCard}
  9598. aiDetectionEnabled={isAiMonitored(printer.id)}
  9599. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9600. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9601. />
  9602. ))}
  9603. </div>
  9604. </Collapsible>
  9605. );
  9606. })}
  9607. </div>
  9608. ) : (
  9609. /* Regular grid view */
  9610. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9611. {sortedPrinters.map((printer) => (
  9612. <PrinterCard
  9613. key={printer.id}
  9614. printer={printer}
  9615. hideIfDisconnected={hideDisconnected}
  9616. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9617. viewMode={viewMode}
  9618. cardSize={cardSize}
  9619. spoolmanEnabled={spoolmanEnabled}
  9620. hasUnlinkedSpools={hasUnlinkedSpools}
  9621. linkedSpools={linkedSpools}
  9622. spoolmanUrl={spoolmanStatus?.url}
  9623. spoolmanSyncMode={spoolmanSyncMode}
  9624. onGetAssignment={getAssignment}
  9625. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9626. spoolmanSpools={spoolmanSpools}
  9627. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9628. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9629. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9630. amsThresholds={settings ? {
  9631. humidityGood: Number(settings.ams_humidity_good) || 40,
  9632. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9633. tempGood: Number(settings.ams_temp_good) || 28,
  9634. tempFair: Number(settings.ams_temp_fair) || 35,
  9635. } : undefined}
  9636. timeFormat={settings?.time_format || 'system'}
  9637. cameraViewMode={cameraViewMode}
  9638. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9639. onSelectCameraViewMode={selectCameraViewMode}
  9640. checkPrinterFirmware={firmwareChecksOn}
  9641. dryingPresets={effectiveDryingPresets}
  9642. nozzleTempPresets={effectiveNozzleTempPresets}
  9643. bedTempPresets={effectiveBedTempPresets}
  9644. chamberTempPresets={effectiveChamberTempPresets}
  9645. fanSpeedPresets={effectiveFanSpeedPresets}
  9646. requirePlateClear={settings?.require_plate_clear === true}
  9647. selectionMode={selectionMode}
  9648. isSelected={selectedPrinterIds.has(printer.id)}
  9649. onToggleSelect={toggleSelect}
  9650. onOpenCompactCard={openCompactCard}
  9651. aiDetectionEnabled={isAiMonitored(printer.id)}
  9652. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9653. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9654. />
  9655. ))}
  9656. </div>
  9657. )}
  9658. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9659. <button
  9660. type="button"
  9661. onClick={returnToCompactCards}
  9662. 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}`}
  9663. title={t('common.back', 'Back')}
  9664. >
  9665. <ArrowLeft className="w-4 h-4" />
  9666. {t('common.back', 'Back')}
  9667. </button>
  9668. )}
  9669. {showAddModal && (
  9670. <AddPrinterModal
  9671. onClose={() => setShowAddModal(false)}
  9672. onAdd={(data) => addMutation.mutate(data)}
  9673. existingSerials={printers?.map(p => p.serial_number) || []}
  9674. />
  9675. )}
  9676. {/* Bulk selection toolbar */}
  9677. {selectionMode && printers && (
  9678. <BulkPrinterToolbar
  9679. selectedIds={selectedPrinterIds}
  9680. printers={printers}
  9681. onClose={clearSelection}
  9682. onSelectAll={selectAll}
  9683. onSelectByLocation={selectByLocation}
  9684. onSelectByState={selectByState}
  9685. onAction={handleBulkAction}
  9686. actionPending={bulkActionPending}
  9687. />
  9688. )}
  9689. {/* Bulk action confirmation modals */}
  9690. {bulkConfirmAction === 'stop' && (
  9691. <ConfirmModal
  9692. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9693. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9694. confirmText={t('printers.bulk.confirm.stopButton')}
  9695. variant="danger"
  9696. isLoading={bulkActionPending}
  9697. onConfirm={() => executeBulkAction('stop')}
  9698. onCancel={() => setBulkConfirmAction(null)}
  9699. />
  9700. )}
  9701. {bulkConfirmAction === 'pause' && (
  9702. <ConfirmModal
  9703. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9704. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9705. confirmText={t('printers.bulk.confirm.pauseButton')}
  9706. isLoading={bulkActionPending}
  9707. onConfirm={() => executeBulkAction('pause')}
  9708. onCancel={() => setBulkConfirmAction(null)}
  9709. />
  9710. )}
  9711. {bulkConfirmAction === 'clearPlate' && (
  9712. <ConfirmModal
  9713. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9714. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9715. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9716. isLoading={bulkActionPending}
  9717. onConfirm={() => executeBulkAction('clearPlate')}
  9718. onCancel={() => setBulkConfirmAction(null)}
  9719. />
  9720. )}
  9721. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9722. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9723. <EmbeddedCameraViewer
  9724. key={camera.id}
  9725. printerId={camera.id}
  9726. printerName={camera.name}
  9727. viewerIndex={index}
  9728. onClose={() => setEmbeddedCameraPrinters(prev => {
  9729. const next = new Map(prev);
  9730. next.delete(camera.id);
  9731. return next;
  9732. })}
  9733. />
  9734. ))}
  9735. </div>
  9736. );
  9737. }