PrintersPage.tsx 427 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { formatPrintName } from '../utils/printName';
  5. import { computePopoverPosition } from '../utils/popoverPosition';
  6. import {
  7. BED_TEMP_DEFAULTS,
  8. CHAMBER_TEMP_DEFAULTS,
  9. FAN_SPEED_DEFAULTS,
  10. NOZZLE_TEMP_DEFAULTS,
  11. buildPresetOptions,
  12. parsePresetTriple,
  13. } from '../utils/temperatureFanPresets';
  14. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  15. // covers header + filament select + temp slider + duration + rotate-tray
  16. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  17. // earlier); under-estimating leaves the popover clipped off the bottom (the
  18. // original bug at #1447).
  19. const DRYING_POPOVER_WIDTH = 240;
  20. const DRYING_POPOVER_ESTIMATED_HEIGHT = 320;
  21. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  22. import { useTranslation } from 'react-i18next';
  23. import { useTheme } from '../contexts/ThemeContext';
  24. import { useAuth } from '../contexts/AuthContext';
  25. import {
  26. Plus,
  27. Link,
  28. Unlink,
  29. Signal,
  30. Clock,
  31. MoreVertical,
  32. Trash2,
  33. RefreshCw,
  34. RotateCw,
  35. Box,
  36. HardDrive,
  37. AlertTriangle,
  38. AlertCircle,
  39. Terminal,
  40. Power,
  41. Zap,
  42. Wrench,
  43. ChevronDown,
  44. Filter,
  45. Pencil,
  46. ArrowLeft,
  47. ArrowRight,
  48. ArrowUp,
  49. ArrowDown,
  50. Layers,
  51. Video,
  52. Search,
  53. Loader2,
  54. Square,
  55. Pause,
  56. Play,
  57. X,
  58. Fan,
  59. Wind,
  60. AirVent,
  61. Download,
  62. ScanSearch,
  63. CheckCircle,
  64. CheckSquare,
  65. XCircle,
  66. User,
  67. Home,
  68. Printer as PrinterIcon,
  69. Info,
  70. Cable,
  71. Flame,
  72. Repeat,
  73. Snowflake,
  74. Gauge,
  75. DoorOpen,
  76. DoorClosed,
  77. Move,
  78. LogIn,
  79. LogOut,
  80. MoreHorizontal,
  81. SlidersHorizontal,
  82. Stethoscope,
  83. LineChart as LineChartIcon,
  84. LayoutGrid,
  85. MonitorPlay,
  86. ExternalLink,
  87. } from 'lucide-react';
  88. // Aliased: lucide-react already exports a `Link` icon into this module.
  89. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  90. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  91. import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
  92. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  93. import { Card, CardContent } from '../components/Card';
  94. import { Button } from '../components/Button';
  95. import { ConfirmModal } from '../components/ConfirmModal';
  96. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  97. import { FileManagerModal } from '../components/FileManagerModal';
  98. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  99. import { CameraWall } from '../components/CameraWall';
  100. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  101. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  102. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  103. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  104. import { AmsBackupModal } from '../components/AmsBackupModal';
  105. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  106. import type { HeaterSensorKind } from '../api/client';
  107. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  108. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  109. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  110. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  111. import { useToast } from '../contexts/ToastContext';
  112. import { ChamberLight } from '../components/icons/ChamberLight';
  113. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  114. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  115. import { FileUploadModal } from '../components/FileUploadModal';
  116. import { PrintModal } from '../components/PrintModal';
  117. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  118. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool, resolveSlotNozzleDiameter } from '../utils/amsHelpers';
  119. import { getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
  120. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  121. import { Collapsible } from '../components/Collapsible';
  122. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  123. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  124. export interface SpoolmanSlotAssignmentRow {
  125. printer_id: number;
  126. ams_id: number;
  127. tray_id: number;
  128. spoolman_spool_id: number;
  129. }
  130. // Color names resolve via getColorName() which reads the backend color_catalog
  131. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  132. // Format K value with 3 decimal places, default to 0.020 if null
  133. function formatKValue(k: number | null | undefined): string {
  134. const value = k ?? 0.020;
  135. return value.toFixed(3);
  136. }
  137. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  138. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  139. const { mode } = useTheme();
  140. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  141. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  142. return (
  143. <span
  144. className="inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded"
  145. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  146. >
  147. {side}
  148. </span>
  149. );
  150. }
  151. // Expand nozzle type codes to material names
  152. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  153. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  154. function nozzleTypeName(type: string, t: (key: string) => string): string {
  155. if (!type) return '';
  156. // Full text names (from main nozzle info)
  157. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  158. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  159. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  160. // 4-char codes (e.g. "HS01"): last 2 digits = material
  161. if (type.length >= 4) {
  162. const material = type.slice(2, 4);
  163. if (material === '00') return t('printers.nozzleStainlessSteel');
  164. if (material === '01') return t('printers.nozzleHardenedSteel');
  165. if (material === '05') return t('printers.nozzleTungstenCarbide');
  166. }
  167. // 2-digit numeric codes
  168. if (type === '00') return t('printers.nozzleStainlessSteel');
  169. if (type === '01') return t('printers.nozzleHardenedSteel');
  170. if (type === '05') return t('printers.nozzleTungstenCarbide');
  171. // 2-char alpha codes: H prefix = hardened steel
  172. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  173. return type;
  174. }
  175. // Parse flow type from nozzle type code
  176. // HH = high flow, HS = standard/normal
  177. function nozzleFlowName(type: string, t: (key: string) => string): string {
  178. if (!type) return '';
  179. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  180. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  181. return '';
  182. }
  183. // Per-slot hover card for nozzle rack
  184. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  185. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  186. slot: import('../api/client').NozzleRackSlot;
  187. index: number;
  188. activeStatus?: boolean;
  189. filamentName?: string;
  190. children: React.ReactNode;
  191. }) {
  192. const { t } = useTranslation();
  193. const [isVisible, setIsVisible] = useState(false);
  194. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  195. const triggerRef = useRef<HTMLDivElement>(null);
  196. const cardRef = useRef<HTMLDivElement>(null);
  197. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  198. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  199. const isMounted = slot.stat === 1;
  200. useEffect(() => {
  201. if (isVisible && triggerRef.current && cardRef.current) {
  202. const triggerRect = triggerRef.current.getBoundingClientRect();
  203. const cardHeight = cardRef.current.offsetHeight;
  204. const headerHeight = 56;
  205. const spaceAbove = triggerRect.top - headerHeight;
  206. const spaceBelow = window.innerHeight - triggerRect.bottom;
  207. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  208. setPosition('bottom');
  209. } else {
  210. setPosition('top');
  211. }
  212. }
  213. }, [isVisible]);
  214. const handleMouseEnter = () => {
  215. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  216. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  217. };
  218. const handleMouseLeave = () => {
  219. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  220. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  221. };
  222. useEffect(() => {
  223. return () => {
  224. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  225. };
  226. }, []);
  227. const filamentCss = parseFilamentColor(slot.filament_color);
  228. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  229. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  230. return (
  231. <div
  232. ref={triggerRef}
  233. className="relative"
  234. onMouseEnter={handleMouseEnter}
  235. onMouseLeave={handleMouseLeave}
  236. >
  237. {children}
  238. {isVisible && (
  239. <div
  240. ref={cardRef}
  241. className={`
  242. absolute left-1/2 -translate-x-1/2 z-50
  243. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  244. animate-in fade-in-0 zoom-in-95 duration-150
  245. `}
  246. style={{ maxWidth: 'calc(100vw - 24px)' }}
  247. >
  248. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  249. {isEmpty ? (
  250. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  251. Slot {index + 1} — Empty
  252. </div>
  253. ) : (
  254. <div className="p-2.5 space-y-1.5">
  255. {/* Diameter */}
  256. <div className="flex items-center justify-between">
  257. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  258. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  259. </div>
  260. {/* Type */}
  261. {typeFull && (
  262. <div className="flex items-center justify-between">
  263. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  264. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  265. </div>
  266. )}
  267. {/* Flow (hide if empty) */}
  268. {flowFull && (
  269. <div className="flex items-center justify-between">
  270. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  271. <span className="text-xs text-white font-semibold">{flowFull}</span>
  272. </div>
  273. )}
  274. {/* Status badge */}
  275. <div className="flex items-center justify-between">
  276. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  277. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  278. activeStatus || isMounted
  279. ? 'bg-green-900/50 text-green-400'
  280. : 'bg-bambu-dark-tertiary text-bambu-gray'
  281. }`}>
  282. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  283. </span>
  284. </div>
  285. {/* Wear (hide if null) */}
  286. {slot.wear != null && (
  287. <div className="flex items-center justify-between">
  288. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  289. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  290. </div>
  291. )}
  292. {/* Max Temp (hide if 0) */}
  293. {slot.max_temp > 0 && (
  294. <div className="flex items-center justify-between">
  295. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  296. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  297. </div>
  298. )}
  299. {/* Serial (hide if empty) */}
  300. {slot.serial_number && (
  301. <div className="flex items-center justify-between">
  302. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  303. <span className="text-[10px] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  304. </div>
  305. )}
  306. {/* Filament: material type + color swatch (hide if no color) */}
  307. {(filamentCss || slot.filament_type) && (
  308. <div className="flex items-center justify-between">
  309. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  310. <div className="flex items-center gap-1">
  311. {filamentCss && (
  312. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  313. )}
  314. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  315. </div>
  316. </div>
  317. )}
  318. </div>
  319. )}
  320. </div>
  321. {/* Arrow pointer */}
  322. <div
  323. className={`
  324. absolute left-1/2 -translate-x-1/2 w-0 h-0
  325. border-l-[6px] border-l-transparent
  326. border-r-[6px] border-r-transparent
  327. ${position === 'top'
  328. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  329. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  330. `}
  331. />
  332. </div>
  333. )}
  334. </div>
  335. );
  336. }
  337. // Dual-nozzle hover card showing L and R nozzle details side by side
  338. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  339. leftSlot?: import('../api/client').NozzleRackSlot;
  340. rightSlot?: import('../api/client').NozzleRackSlot;
  341. activeNozzle: 'L' | 'R';
  342. filamentInfo?: Record<string, { name: string; k: number | null }>;
  343. children: React.ReactNode;
  344. }) {
  345. const { t } = useTranslation();
  346. const [isVisible, setIsVisible] = useState(false);
  347. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  348. const triggerRef = useRef<HTMLDivElement>(null);
  349. const cardRef = useRef<HTMLDivElement>(null);
  350. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  351. useEffect(() => {
  352. if (isVisible && triggerRef.current && cardRef.current) {
  353. const triggerRect = triggerRef.current.getBoundingClientRect();
  354. const cardHeight = cardRef.current.offsetHeight;
  355. const headerHeight = 56;
  356. const spaceAbove = triggerRect.top - headerHeight;
  357. const spaceBelow = window.innerHeight - triggerRect.bottom;
  358. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  359. setPosition('bottom');
  360. } else {
  361. setPosition('top');
  362. }
  363. }
  364. }, [isVisible]);
  365. const handleMouseEnter = () => {
  366. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  367. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  368. };
  369. const handleMouseLeave = () => {
  370. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  371. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  372. };
  373. useEffect(() => {
  374. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  375. }, []);
  376. if (!leftSlot && !rightSlot) return <>{children}</>;
  377. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  378. const isActive = activeNozzle === side;
  379. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  380. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  381. const filamentCss = parseFilamentColor(slot.filament_color);
  382. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  383. return (
  384. <div className="flex-1 space-y-1.5">
  385. <div className={`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-700 dark:text-amber-400' : 'text-bambu-gray'}`}>
  386. {side === 'L' ? t('common.left') : t('common.right')}
  387. </div>
  388. {slot.nozzle_diameter && (
  389. <div className="flex items-center justify-between">
  390. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  391. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  392. </div>
  393. )}
  394. {typeFull && (
  395. <div className="flex items-center justify-between">
  396. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleType')}</span>
  397. <span className="text-[10px] text-white font-semibold">{typeFull}</span>
  398. </div>
  399. )}
  400. {flowFull && (
  401. <div className="flex items-center justify-between">
  402. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  403. <span className="text-[10px] text-white font-semibold">{flowFull}</span>
  404. </div>
  405. )}
  406. <div className="flex items-center justify-between">
  407. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  408. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  409. isActive
  410. ? 'bg-green-900/50 text-green-400'
  411. : 'bg-bambu-dark-tertiary text-bambu-gray'
  412. }`}>
  413. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  414. </span>
  415. </div>
  416. {slot.wear != null && (
  417. <div className="flex items-center justify-between">
  418. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleWear')}</span>
  419. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  420. </div>
  421. )}
  422. {/* Serial and max temp only available on the right (removable) nozzle */}
  423. {side === 'R' && slot.max_temp > 0 && (
  424. <div className="flex items-center justify-between">
  425. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  426. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  427. </div>
  428. )}
  429. {side === 'R' && slot.serial_number && (
  430. <div className="flex items-center justify-between">
  431. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  432. <span className="text-[10px] text-white font-mono">{slot.serial_number}</span>
  433. </div>
  434. )}
  435. {(filamentCss || slot.filament_type || slot.filament_id) && (
  436. <div className="flex items-center justify-between">
  437. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  438. <div className="flex items-center gap-1">
  439. {filamentCss && (
  440. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  441. )}
  442. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">
  443. {filamentName || slot.filament_type || slot.filament_id || ''}
  444. </span>
  445. </div>
  446. </div>
  447. )}
  448. </div>
  449. );
  450. };
  451. return (
  452. <div
  453. ref={triggerRef}
  454. className="relative flex-1"
  455. onMouseEnter={handleMouseEnter}
  456. onMouseLeave={handleMouseLeave}
  457. >
  458. {children}
  459. {isVisible && (
  460. <div
  461. ref={cardRef}
  462. className={`
  463. absolute left-1/2 -translate-x-1/2 z-50
  464. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  465. animate-in fade-in-0 zoom-in-95 duration-150
  466. `}
  467. style={{ maxWidth: 'calc(100vw - 24px)' }}
  468. >
  469. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  470. <div className="p-2.5 flex gap-3">
  471. {leftSlot && renderColumn(leftSlot, 'L')}
  472. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  473. {rightSlot && renderColumn(rightSlot, 'R')}
  474. </div>
  475. </div>
  476. {/* Arrow pointer */}
  477. <div
  478. className={`
  479. absolute left-1/2 -translate-x-1/2 w-0 h-0
  480. border-l-[6px] border-l-transparent
  481. border-r-[6px] border-r-transparent
  482. ${position === 'top'
  483. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  484. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  485. `}
  486. />
  487. </div>
  488. )}
  489. </div>
  490. );
  491. }
  492. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  493. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  494. const { t } = useTranslation();
  495. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  496. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  497. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  498. // base — computing it from min(present IDs) shifts everything left when slot 16
  499. // is the one currently mounted (#943).
  500. const rackNozzles = slots.filter(s => s.id >= 2);
  501. const RACK_SIZE = 6;
  502. const RACK_BASE_ID = 16;
  503. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  504. { length: RACK_SIZE },
  505. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  506. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  507. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  508. },
  509. );
  510. return (
  511. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center">
  512. <p className="text-[9px] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  513. <div className="flex gap-[3px] justify-center">
  514. {rackSlots.map((slot, i) => {
  515. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  516. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  517. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  518. return (
  519. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  520. <div
  521. className={`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  522. isEmpty
  523. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  524. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  525. }`}
  526. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  527. >
  528. <span className={`text-[10px] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  529. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  530. >
  531. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  532. </span>
  533. </div>
  534. </NozzleSlotHoverCard>
  535. );
  536. })}
  537. </div>
  538. </div>
  539. );
  540. }
  541. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  542. function WaterDropEmpty({ className }: { className?: string }) {
  543. return (
  544. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  545. <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"/>
  546. </svg>
  547. );
  548. }
  549. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  550. function WaterDropHalf({ className }: { className?: string }) {
  551. return (
  552. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  553. <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"/>
  554. <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"/>
  555. </svg>
  556. );
  557. }
  558. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  559. function WaterDropFull({ className }: { className?: string }) {
  560. return (
  561. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  562. <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"/>
  563. <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"/>
  564. </svg>
  565. );
  566. }
  567. // Thermometer SVG - empty outline
  568. function ThermometerEmpty({ className }: { className?: string }) {
  569. return (
  570. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  571. <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"/>
  572. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  573. </svg>
  574. );
  575. }
  576. // Thermometer SVG - half filled (gold - same as humidity fair)
  577. function ThermometerHalf({ className }: { className?: string }) {
  578. return (
  579. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  580. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  581. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  582. <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"/>
  583. </svg>
  584. );
  585. }
  586. // Thermometer SVG - fully filled (red - same as humidity bad)
  587. function ThermometerFull({ className }: { className?: string }) {
  588. return (
  589. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  590. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  591. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  592. <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"/>
  593. </svg>
  594. );
  595. }
  596. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  597. // Added for visual parity with the thermometer icons on the dual-nozzle card
  598. // that previously had no icon at all (#1115, design by @m4rtini2).
  599. function NozzleIcon({ className }: { className?: string }) {
  600. return (
  601. <svg
  602. className={className}
  603. viewBox="0 0 24 24"
  604. fill="none"
  605. xmlns="http://www.w3.org/2000/svg"
  606. stroke="currentColor"
  607. strokeWidth="1.5"
  608. strokeLinecap="round"
  609. strokeLinejoin="round"
  610. >
  611. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  612. <rect x="6" y="11.5" width="12.1" height="3.7" />
  613. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  614. </svg>
  615. );
  616. }
  617. // Heater thermometer icon - filled when heating, outline when off
  618. interface HeaterThermometerProps {
  619. className?: string;
  620. color: string; // The color class (e.g., "text-orange-400")
  621. isHeating: boolean;
  622. }
  623. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  624. // Extract the actual color from Tailwind class for SVG fill
  625. const colorMap: Record<string, string> = {
  626. 'text-orange-400': '#fb923c',
  627. 'text-blue-400': '#60a5fa',
  628. 'text-green-400': '#4ade80',
  629. };
  630. const fillColor = colorMap[color] || '#888';
  631. // Glow style when heating
  632. const glowStyle = isHeating ? {
  633. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  634. } : {};
  635. if (isHeating) {
  636. // Filled thermometer with glow - heater is ON
  637. return (
  638. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  639. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  640. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  641. <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"/>
  642. </svg>
  643. );
  644. }
  645. // Empty thermometer - heater is OFF
  646. return (
  647. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  648. <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"/>
  649. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  650. </svg>
  651. );
  652. }
  653. // AMS Filament Backup tri-state indicator + toggle.
  654. // state=true → ON, click to disable
  655. // state=false → OFF, click opens modal
  656. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  657. interface AmsBackupBadgeProps {
  658. state: boolean | null;
  659. onClick: () => void;
  660. }
  661. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  662. const { t } = useTranslation();
  663. const known = state !== null;
  664. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors ';
  665. let title: string;
  666. if (state === true) {
  667. className += known
  668. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  669. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  670. title = t('printers.amsBackup.titleOn');
  671. } else if (state === false) {
  672. className += known
  673. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  674. : 'bg-bambu-dark text-bambu-gray cursor-default';
  675. title = t('printers.amsBackup.titleOff');
  676. } else {
  677. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  678. title = t('printers.amsBackup.titleUnknown');
  679. }
  680. return (
  681. <button
  682. type="button"
  683. disabled={!known}
  684. onClick={() => known && onClick()}
  685. className={className}
  686. title={title}
  687. aria-label={title}
  688. >
  689. {known ? <Repeat className="w-3 h-3" /> : <span>?</span>}
  690. </button>
  691. );
  692. }
  693. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  694. // Reference: https://github.com/theicedmango/bambu-humidity
  695. interface HumidityIndicatorProps {
  696. humidity: number | string;
  697. goodThreshold?: number; // <= this is green
  698. fairThreshold?: number; // <= this is orange, > is red
  699. onClick?: () => void;
  700. compact?: boolean; // Smaller version for grid layout
  701. }
  702. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  703. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  704. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  705. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  706. // Status thresholds (configurable via settings)
  707. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  708. let textColor: string;
  709. let statusText: string;
  710. if (isNaN(humidityValue)) {
  711. textColor = '#C3C2C1';
  712. statusText = 'Unknown';
  713. } else if (humidityValue <= good) {
  714. textColor = '#22a352'; // Green - Good
  715. statusText = 'Good';
  716. } else if (humidityValue <= fair) {
  717. textColor = '#d4a017'; // Gold - Fair
  718. statusText = 'Fair';
  719. } else {
  720. textColor = '#c62828'; // Red - Bad
  721. statusText = 'Bad';
  722. }
  723. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  724. let DropComponent: React.FC<{ className?: string }>;
  725. if (isNaN(humidityValue)) {
  726. DropComponent = WaterDropEmpty;
  727. } else if (humidityValue <= good) {
  728. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  729. } else if (humidityValue <= fair) {
  730. DropComponent = WaterDropHalf; // Fair - half filled
  731. } else {
  732. DropComponent = WaterDropFull; // Bad - full (too humid)
  733. }
  734. return (
  735. <button
  736. type="button"
  737. onClick={onClick}
  738. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  739. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  740. >
  741. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  742. <span className={`font-medium tabular-nums ${compact ? 'text-[10px]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  743. </button>
  744. );
  745. }
  746. // Temperature indicator with dynamic icon and coloring
  747. interface TemperatureIndicatorProps {
  748. temp: number;
  749. goodThreshold?: number; // <= this is blue
  750. fairThreshold?: number; // <= this is orange, > is red
  751. onClick?: () => void;
  752. compact?: boolean; // Smaller version for grid layout
  753. }
  754. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  755. // Ensure thresholds are numbers
  756. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  757. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  758. let textColor: string;
  759. let statusText: string;
  760. let ThermoComponent: React.FC<{ className?: string }>;
  761. if (temp <= good) {
  762. textColor = '#22a352'; // Green - good (same as humidity)
  763. statusText = 'Good';
  764. ThermoComponent = ThermometerEmpty;
  765. } else if (temp <= fair) {
  766. textColor = '#d4a017'; // Gold - fair (same as humidity)
  767. statusText = 'Fair';
  768. ThermoComponent = ThermometerHalf;
  769. } else {
  770. textColor = '#c62828'; // Red - bad (same as humidity)
  771. statusText = 'Bad';
  772. ThermoComponent = ThermometerFull;
  773. }
  774. return (
  775. <button
  776. type="button"
  777. onClick={onClick}
  778. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  779. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  780. >
  781. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  782. <span className={`tabular-nums text-right ${compact ? 'text-[10px] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  783. </button>
  784. );
  785. }
  786. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  787. *
  788. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  789. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  790. * every empty-by-bitmask slot lands here regardless of firmware payload
  791. * shape.
  792. *
  793. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  794. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  795. * the user cleared with "Reset Slot" where a physical spool may still be
  796. * loaded but unassigned.
  797. *
  798. * Returns null when the slot is loaded (tray_type is present).
  799. */
  800. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  801. if (tray?.tray_type) return null;
  802. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  803. // spool the firmware can't identify is physically present (exists === true)
  804. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  805. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  806. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  807. if (tray?.exists === true) return 'reset';
  808. if (tray?.exists === false) return 'physical';
  809. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  810. }
  811. // How long to wait for an AMS to report a live drying cycle after the printer
  812. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  813. // within a couple of seconds; 30s covers the slowest observed push cadence
  814. // without leaving the user waiting on a verdict.
  815. const DRY_START_CONFIRM_MS = 30_000;
  816. function CoverImage({
  817. url,
  818. printName,
  819. className = 'w-20 h-20',
  820. radiusClass = 'rounded-lg',
  821. }: {
  822. url: string | null;
  823. printName?: string;
  824. className?: string;
  825. radiusClass?: string;
  826. }) {
  827. const { t } = useTranslation();
  828. const [loaded, setLoaded] = useState(false);
  829. const [error, setError] = useState(false);
  830. const [showOverlay, setShowOverlay] = useState(false);
  831. // Cache-bust the image URL when the print name changes so the browser
  832. // fetches the new cover instead of serving the stale cached image.
  833. const cacheBustedUrl = useMemo(() => {
  834. if (!url) return null;
  835. const sep = url.includes('?') ? '&' : '?';
  836. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  837. }, [url, printName]);
  838. // Reset loaded/error state when the image URL changes
  839. useEffect(() => {
  840. setLoaded(false);
  841. setError(false);
  842. }, [cacheBustedUrl]);
  843. return (
  844. <>
  845. <div
  846. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  847. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  848. >
  849. {cacheBustedUrl && !error ? (
  850. <>
  851. <img
  852. src={cacheBustedUrl}
  853. alt={t('printers.printPreview')}
  854. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  855. onLoad={() => setLoaded(true)}
  856. onError={() => setError(true)}
  857. />
  858. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  859. </>
  860. ) : (
  861. <Box className="w-8 h-8 text-bambu-gray" />
  862. )}
  863. </div>
  864. {/* Cover Image Overlay */}
  865. {showOverlay && cacheBustedUrl && (
  866. <div
  867. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  868. onClick={() => setShowOverlay(false)}
  869. >
  870. <div className="relative max-w-2xl max-h-full">
  871. <img
  872. src={cacheBustedUrl}
  873. alt={t('printers.printPreview')}
  874. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  875. />
  876. {printName && (
  877. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  878. )}
  879. </div>
  880. </div>
  881. )}
  882. </>
  883. );
  884. }
  885. interface PrinterMaintenanceInfo {
  886. due_count: number;
  887. warning_count: number;
  888. total_print_hours: number;
  889. }
  890. // Status summary bar component - uses queryClient to read cached statuses
  891. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  892. const { t } = useTranslation();
  893. const queryClient = useQueryClient();
  894. // Subscribe to query cache changes to re-render when status updates
  895. // Throttled to prevent rapid re-renders from causing tab crashes
  896. const [cacheTick, setCacheTick] = useState(0);
  897. useEffect(() => {
  898. let pending = false;
  899. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  900. if (!pending) {
  901. pending = true;
  902. requestAnimationFrame(() => {
  903. setCacheTick(t => t + 1);
  904. pending = false;
  905. });
  906. }
  907. });
  908. return () => unsubscribe();
  909. }, [queryClient]);
  910. const { counts, nextFinish } = useMemo(() => {
  911. let printing = 0;
  912. let paused = 0;
  913. let finished = 0;
  914. let idle = 0;
  915. let offline = 0;
  916. let loading = 0;
  917. let error = 0;
  918. let nextPrinterName: string | null = null;
  919. let nextRemainingMin: number | null = null;
  920. let nextProgress: number = 0;
  921. printers?.forEach((printer) => {
  922. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  923. if (status === undefined) {
  924. // Status not yet loaded - don't count as offline yet
  925. loading++;
  926. } else if (!status.connected) {
  927. offline++;
  928. } else {
  929. // Count printers with active HMS errors as problems
  930. const knownHmsCount =
  931. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  932. if (knownHmsCount > 0) {
  933. error++;
  934. }
  935. switch (status.state) {
  936. case 'RUNNING':
  937. printing++;
  938. if (status.remaining_time != null && status.remaining_time > 0) {
  939. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  940. nextRemainingMin = status.remaining_time;
  941. nextPrinterName = printer.name;
  942. nextProgress = status.progress || 0;
  943. }
  944. }
  945. break;
  946. case 'PAUSE':
  947. paused++;
  948. break;
  949. case 'FINISH':
  950. finished++;
  951. break;
  952. case 'FAILED':
  953. // FAILED is the printer's terminal gcode_state after a print stops —
  954. // including user cancellations, where there's no actual fault. Only
  955. // count it as a "problem" when an HMS error is also active; otherwise
  956. // it's just a print that ended unsuccessfully and the plate needs
  957. // clearing (same as FINISH from the operator's perspective).
  958. if (knownHmsCount > 0) {
  959. // Already counted above
  960. } else {
  961. finished++;
  962. }
  963. break;
  964. default:
  965. idle++;
  966. break;
  967. }
  968. }
  969. });
  970. return {
  971. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  972. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  973. };
  974. // eslint-disable-next-line react-hooks/exhaustive-deps
  975. }, [printers, queryClient, cacheTick]);
  976. if (!printers?.length) return null;
  977. const badges: { count: number; dot: string; label: string }[] = [
  978. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  979. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  980. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  981. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  982. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  983. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  984. ];
  985. return (
  986. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  987. {badges.map(({ count, dot, label }) => count > 0 && (
  988. <div key={label} className="flex items-center gap-1.5">
  989. <div className={`w-2 h-2 rounded-full ${dot}`} />
  990. <span className="text-bambu-gray">
  991. <span className="text-white font-medium">{count}</span> {label}
  992. </span>
  993. </div>
  994. ))}
  995. {nextFinish && (
  996. <>
  997. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  998. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  999. <div className="flex items-center gap-2">
  1000. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1001. <span className="text-white font-medium">{nextFinish.name}</span>
  1002. </div>
  1003. <div className="flex items-center gap-2 w-full sm:w-auto">
  1004. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1005. <div
  1006. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1007. style={{ width: `${nextFinish.progress}%` }}
  1008. />
  1009. </div>
  1010. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1011. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1012. </div>
  1013. </div>
  1014. </>
  1015. )}
  1016. </div>
  1017. );
  1018. }
  1019. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1020. type ViewMode = 'expanded' | 'compact';
  1021. type ToolbarDropdownOption<T extends string> = {
  1022. value: T;
  1023. label: string;
  1024. };
  1025. function ToolbarDropdown<T extends string>({
  1026. value,
  1027. options,
  1028. onChange,
  1029. fullWidth = false,
  1030. }: {
  1031. value: T;
  1032. options: ToolbarDropdownOption<T>[];
  1033. onChange: (value: T) => void;
  1034. fullWidth?: boolean;
  1035. }) {
  1036. const [isOpen, setIsOpen] = useState(false);
  1037. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1038. return (
  1039. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1040. <button
  1041. type="button"
  1042. onClick={() => setIsOpen(open => !open)}
  1043. 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'}`}
  1044. >
  1045. <span className="truncate">{selectedOption?.label}</span>
  1046. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1047. </button>
  1048. {isOpen && (
  1049. <>
  1050. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1051. <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">
  1052. {options.map(option => (
  1053. <button
  1054. key={option.value}
  1055. type="button"
  1056. onClick={() => {
  1057. onChange(option.value);
  1058. setIsOpen(false);
  1059. }}
  1060. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1061. option.value === value ? 'text-bambu-green' : 'text-white'
  1062. }`}
  1063. >
  1064. {option.label}
  1065. </button>
  1066. ))}
  1067. </div>
  1068. </>
  1069. )}
  1070. </div>
  1071. );
  1072. }
  1073. function ToolbarMenu({
  1074. label,
  1075. icon,
  1076. children,
  1077. }: {
  1078. label: string;
  1079. icon: React.ReactNode;
  1080. children: React.ReactNode;
  1081. }) {
  1082. const [isOpen, setIsOpen] = useState(false);
  1083. return (
  1084. <div className="relative">
  1085. <button
  1086. type="button"
  1087. onClick={() => setIsOpen(open => !open)}
  1088. 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"
  1089. aria-label={label}
  1090. title={label}
  1091. >
  1092. {icon}
  1093. </button>
  1094. {isOpen && (
  1095. <>
  1096. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1097. <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">
  1098. {children}
  1099. </div>
  1100. </>
  1101. )}
  1102. </div>
  1103. );
  1104. }
  1105. function IndicatorControlPopover({
  1106. title,
  1107. options = [],
  1108. unit,
  1109. customMin,
  1110. customMax,
  1111. customStep = 1,
  1112. widthClass = 'w-[240px]',
  1113. popoverWidth = 240,
  1114. popoverHeight = 280,
  1115. isPending,
  1116. onClose,
  1117. onSubmit,
  1118. children,
  1119. }: {
  1120. title: string;
  1121. options?: Array<{ label: string; value: number }>;
  1122. unit?: string;
  1123. customMin?: number;
  1124. customMax?: number;
  1125. customStep?: number;
  1126. widthClass?: string;
  1127. popoverWidth?: number;
  1128. popoverHeight?: number;
  1129. isPending?: boolean;
  1130. onClose: () => void;
  1131. onSubmit?: (value: number) => void;
  1132. children?: React.ReactNode;
  1133. }) {
  1134. const anchorRef = useRef<HTMLSpanElement>(null);
  1135. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1136. const [customValue, setCustomValue] = useState('');
  1137. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1138. // can position via fixed coords. Portaling to document.body escapes
  1139. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1140. // own contexts and would otherwise cover the popover even at z-[60].
  1141. useLayoutEffect(() => {
  1142. const trigger = anchorRef.current?.parentElement;
  1143. if (!trigger) return;
  1144. const measure = () => {
  1145. const rect = trigger.getBoundingClientRect();
  1146. setCoords(computePopoverPosition({
  1147. triggerRect: rect,
  1148. popoverWidth,
  1149. estimatedHeight: popoverHeight,
  1150. horizontalAlign: 'center',
  1151. }));
  1152. };
  1153. measure();
  1154. window.addEventListener('resize', measure);
  1155. window.addEventListener('scroll', measure, true);
  1156. return () => {
  1157. window.removeEventListener('resize', measure);
  1158. window.removeEventListener('scroll', measure, true);
  1159. };
  1160. }, [popoverWidth, popoverHeight]);
  1161. const showCustomInput = unit !== undefined;
  1162. const submitCustom = () => {
  1163. const value = Number(customValue);
  1164. if (!Number.isFinite(value)) return;
  1165. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1166. onSubmit?.(Math.round(bounded));
  1167. };
  1168. return (
  1169. <>
  1170. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1171. {createPortal(
  1172. <>
  1173. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1174. <div
  1175. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1176. style={{
  1177. top: coords?.top ?? -9999,
  1178. left: coords?.left ?? -9999,
  1179. visibility: coords ? 'visible' : 'hidden',
  1180. }}
  1181. onClick={e => e.stopPropagation()}
  1182. >
  1183. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1184. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1185. {options.length > 0 && (
  1186. <div className="px-3 py-2.5">
  1187. <div className="grid grid-cols-2 gap-1.5">
  1188. {options.map(option => (
  1189. <button
  1190. key={`${option.label}-${option.value}`}
  1191. type="button"
  1192. disabled={isPending}
  1193. onClick={() => onSubmit?.(option.value)}
  1194. 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"
  1195. >
  1196. {option.label}
  1197. </button>
  1198. ))}
  1199. </div>
  1200. </div>
  1201. )}
  1202. {children}
  1203. {showCustomInput && (
  1204. <>
  1205. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1206. <form
  1207. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1208. onSubmit={(e) => {
  1209. e.preventDefault();
  1210. submitCustom();
  1211. }}
  1212. >
  1213. <input
  1214. type="number"
  1215. min={customMin}
  1216. max={customMax}
  1217. step={customStep}
  1218. value={customValue}
  1219. onChange={e => setCustomValue(e.target.value)}
  1220. placeholder="Custom"
  1221. 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"
  1222. />
  1223. <button
  1224. type="submit"
  1225. disabled={isPending || customValue.trim() === ''}
  1226. 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"
  1227. >
  1228. Set
  1229. </button>
  1230. </form>
  1231. </>
  1232. )}
  1233. </div>
  1234. </>,
  1235. document.body
  1236. )}
  1237. </>
  1238. );
  1239. }
  1240. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1241. function NozzleTemperatureControlBox({
  1242. label,
  1243. current,
  1244. target,
  1245. isActive,
  1246. isPending,
  1247. onSubmit,
  1248. options = NOZZLE_TEMPERATURE_OPTIONS,
  1249. }: {
  1250. label: string;
  1251. current?: number;
  1252. target?: number;
  1253. isActive: boolean;
  1254. isPending?: boolean;
  1255. onSubmit: (value: number) => void;
  1256. options?: Array<{ label: string; value: number }>;
  1257. }) {
  1258. const [customValue, setCustomValue] = useState('');
  1259. const submitCustom = () => {
  1260. const value = Number(customValue);
  1261. if (!Number.isFinite(value)) return;
  1262. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1263. };
  1264. return (
  1265. <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'}`}>
  1266. <div className="mb-1.5 flex items-center justify-between gap-2">
  1267. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1268. <span className="text-[10px] text-bambu-gray">
  1269. {Math.round(current ?? 0)}°C
  1270. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1271. </span>
  1272. </div>
  1273. <div className="grid grid-cols-2 gap-1">
  1274. {options.map(option => (
  1275. <button
  1276. key={`${label}-${option.value}`}
  1277. type="button"
  1278. disabled={isPending}
  1279. onClick={() => onSubmit(option.value)}
  1280. 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"
  1281. >
  1282. {option.label}
  1283. </button>
  1284. ))}
  1285. </div>
  1286. <form
  1287. className="mt-1.5 flex gap-1"
  1288. onSubmit={(e) => {
  1289. e.preventDefault();
  1290. submitCustom();
  1291. }}
  1292. >
  1293. <input
  1294. type="number"
  1295. min={0}
  1296. max={320}
  1297. step={1}
  1298. value={customValue}
  1299. onChange={e => setCustomValue(e.target.value)}
  1300. placeholder="Custom"
  1301. 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"
  1302. />
  1303. <button
  1304. type="submit"
  1305. disabled={isPending || customValue.trim() === ''}
  1306. 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"
  1307. >
  1308. Set
  1309. </button>
  1310. </form>
  1311. </div>
  1312. );
  1313. }
  1314. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1315. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1316. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1317. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1318. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1319. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1320. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1321. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1322. };
  1323. /** Classify a printer into one of the UI status buckets. */
  1324. function classifyPrinterStatus(
  1325. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1326. ): PrinterState {
  1327. if (!status?.connected) return 'offline';
  1328. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1329. if (hmsErrors.length > 0) return 'error';
  1330. switch (status.state) {
  1331. case 'RUNNING': return 'printing';
  1332. case 'PAUSE': return 'paused';
  1333. case 'FINISH': return 'finished';
  1334. // FAILED without an active HMS error is the printer's terminal state after
  1335. // any unsuccessful end — including user-cancellations. Treat the same as
  1336. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1337. // HMS code is actually attached (handled by the early-return above).
  1338. case 'FAILED': return 'finished';
  1339. default: return 'idle';
  1340. }
  1341. }
  1342. /**
  1343. * Get human-readable status display text for a printer.
  1344. * Uses stg_cur_name for detailed calibration/preparation stages,
  1345. * otherwise formats the gcode_state nicely.
  1346. */
  1347. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1348. // If we have a specific stage name (calibration, heating, etc.), use it
  1349. if (stg_cur_name) {
  1350. return stg_cur_name;
  1351. }
  1352. // Format the gcode_state nicely
  1353. switch (state) {
  1354. case 'RUNNING':
  1355. return 'Printing';
  1356. case 'PAUSE':
  1357. return 'Paused';
  1358. case 'FINISH':
  1359. return 'Finished';
  1360. case 'FAILED':
  1361. return 'Failed';
  1362. case 'IDLE':
  1363. return 'Idle';
  1364. default:
  1365. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1366. }
  1367. }
  1368. // Bambu models that ship with an enclosure chamber fan (firmware field
  1369. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1370. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1371. // widget is hidden in fanItems instead of rendered greyed-out.
  1372. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1373. 'X1C',
  1374. 'X1',
  1375. 'X1E',
  1376. 'X2D',
  1377. 'P1S',
  1378. 'P2S',
  1379. 'H2D',
  1380. 'H2D Pro',
  1381. 'H2C',
  1382. 'H2S',
  1383. ]);
  1384. // Map SSDP model codes to display names
  1385. function mapModelCode(ssdpModel: string | null): string {
  1386. if (!ssdpModel) return '';
  1387. const modelMap: Record<string, string> = {
  1388. // H2 Series
  1389. 'O1D': 'H2D',
  1390. 'O1E': 'H2D Pro',
  1391. 'O2D': 'H2D Pro',
  1392. 'O1C': 'H2C',
  1393. 'O1C2': 'H2C',
  1394. 'O1S': 'H2S',
  1395. // X1 Series
  1396. 'BL-P001': 'X1C',
  1397. 'BL-P002': 'X1',
  1398. 'BL-P003': 'X1E',
  1399. // X2 Series
  1400. 'N6': 'X2D',
  1401. // A2 Series
  1402. 'N9': 'A2L',
  1403. // P Series
  1404. 'C11': 'P1S',
  1405. 'C12': 'P1P',
  1406. 'C13': 'P2S',
  1407. // A1 Series
  1408. 'N2S': 'A1',
  1409. 'N1': 'A1 Mini',
  1410. // Direct matches
  1411. 'X1C': 'X1C',
  1412. 'X1': 'X1',
  1413. 'X1E': 'X1E',
  1414. 'X2D': 'X2D',
  1415. 'P1S': 'P1S',
  1416. 'P1P': 'P1P',
  1417. 'P2S': 'P2S',
  1418. 'A1': 'A1',
  1419. 'A1 Mini': 'A1 Mini',
  1420. 'A2L': 'A2L',
  1421. 'H2D': 'H2D',
  1422. 'H2D Pro': 'H2D Pro',
  1423. 'H2C': 'H2C',
  1424. 'H2S': 'H2S',
  1425. };
  1426. return modelMap[ssdpModel] || ssdpModel;
  1427. }
  1428. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1429. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1430. // • User-defined friendly name (editable, protected by printers:update)
  1431. // • AMS serial number
  1432. // • AMS firmware version
  1433. export function AmsNameHoverCard({
  1434. ams,
  1435. printerId,
  1436. label,
  1437. amsLabels,
  1438. canEdit,
  1439. onSaved,
  1440. children,
  1441. }: {
  1442. ams: import('../api/client').AMSUnit;
  1443. printerId: number;
  1444. label: string; // auto-generated label, e.g. "AMS-A"
  1445. amsLabels?: Record<number, string>;
  1446. canEdit: boolean;
  1447. onSaved: () => void;
  1448. children: React.ReactNode;
  1449. }) {
  1450. const { t } = useTranslation();
  1451. const [isVisible, setIsVisible] = useState(false);
  1452. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1453. const [editValue, setEditValue] = useState('');
  1454. const [isSaving, setIsSaving] = useState(false);
  1455. const [saveError, setSaveError] = useState<string | null>(null);
  1456. const [isInputFocused, setIsInputFocused] = useState(false);
  1457. const triggerRef = useRef<HTMLDivElement>(null);
  1458. const cardRef = useRef<HTMLDivElement>(null);
  1459. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1460. useEffect(() => {
  1461. if (isVisible) {
  1462. setEditValue(amsLabels?.[ams.id] ?? '');
  1463. setSaveError(null);
  1464. requestAnimationFrame(() => {
  1465. if (triggerRef.current && cardRef.current) {
  1466. const rect = triggerRef.current.getBoundingClientRect();
  1467. const spaceAbove = rect.top - 56;
  1468. const spaceBelow = window.innerHeight - rect.bottom;
  1469. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1470. }
  1471. });
  1472. }
  1473. }, [isVisible, amsLabels, ams.id]);
  1474. const handleMouseEnter = () => {
  1475. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1476. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1477. };
  1478. const handleMouseLeave = () => {
  1479. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1480. if (!isInputFocused) {
  1481. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1482. }
  1483. };
  1484. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1485. const handleSave = async () => {
  1486. if (!canEdit) return;
  1487. setIsSaving(true);
  1488. setSaveError(null);
  1489. try {
  1490. const trimmed = editValue.trim();
  1491. if (trimmed) {
  1492. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1493. } else {
  1494. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1495. }
  1496. onSaved();
  1497. setIsVisible(false);
  1498. } catch (err) {
  1499. setSaveError(err instanceof Error ? err.message : String(err));
  1500. } finally {
  1501. setIsSaving(false);
  1502. }
  1503. };
  1504. const handleClear = async () => {
  1505. if (!canEdit) return;
  1506. setIsSaving(true);
  1507. setSaveError(null);
  1508. try {
  1509. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1510. onSaved();
  1511. setIsVisible(false);
  1512. } catch (err) {
  1513. setSaveError(err instanceof Error ? err.message : String(err));
  1514. } finally {
  1515. setIsSaving(false);
  1516. }
  1517. };
  1518. return (
  1519. <div
  1520. ref={triggerRef}
  1521. className="relative inline-block"
  1522. onMouseEnter={handleMouseEnter}
  1523. onMouseLeave={handleMouseLeave}
  1524. >
  1525. {children}
  1526. {isVisible && (
  1527. <div
  1528. ref={cardRef}
  1529. className={`
  1530. absolute left-0 z-50
  1531. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1532. animate-in fade-in-0 zoom-in-95 duration-150
  1533. `}
  1534. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1535. onMouseEnter={handleMouseEnter}
  1536. onMouseLeave={handleMouseLeave}
  1537. >
  1538. <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">
  1539. {/* AMS auto-label */}
  1540. <div className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1541. {/* Serial number */}
  1542. <div className="flex items-center justify-between gap-2">
  1543. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1544. {t('printers.amsPopup.serialNumber')}
  1545. </span>
  1546. <span className="text-[10px] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1547. </div>
  1548. {/* Firmware version */}
  1549. <div className="flex items-center justify-between gap-2">
  1550. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1551. {t('printers.amsPopup.firmwareVersion')}
  1552. </span>
  1553. <span className="text-[10px] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1554. </div>
  1555. {/* Friendly name editor */}
  1556. <div className="space-y-1">
  1557. <div className="flex items-center gap-2">
  1558. <span className="text-[10px] text-bambu-gray font-medium shrink-0">
  1559. {t('printers.amsPopup.friendlyName')}
  1560. </span>
  1561. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1562. </div>
  1563. <input
  1564. type="text"
  1565. value={editValue}
  1566. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1567. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1568. onFocus={() => setIsInputFocused(true)}
  1569. onBlur={() => {
  1570. setIsInputFocused(false);
  1571. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1572. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1573. }}
  1574. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1575. disabled={!canEdit}
  1576. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1577. 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"
  1578. maxLength={100}
  1579. />
  1580. {canEdit && (
  1581. <div className="space-y-1">
  1582. {saveError && (
  1583. <p className="text-[10px] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1584. )}
  1585. <div className="flex gap-1 justify-end">
  1586. <button
  1587. onClick={handleSave}
  1588. disabled={isSaving}
  1589. className="px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1590. >
  1591. {t('printers.amsPopup.save')}
  1592. </button>
  1593. {amsLabels?.[ams.id] && (
  1594. <button
  1595. onClick={handleClear}
  1596. disabled={isSaving}
  1597. className="px-2 py-0.5 text-[10px] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1598. >
  1599. {t('printers.amsPopup.clear')}
  1600. </button>
  1601. )}
  1602. </div>
  1603. </div>
  1604. )}
  1605. </div>
  1606. </div>
  1607. </div>
  1608. )}
  1609. </div>
  1610. );
  1611. }
  1612. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1613. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1614. const DRYING_PRESETS: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }> = {
  1615. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1616. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1617. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1618. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1619. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1620. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1621. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1622. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1623. };
  1624. function PrinterCard({
  1625. printer,
  1626. hideIfDisconnected,
  1627. maintenanceInfo,
  1628. viewMode = 'expanded',
  1629. cardSize = 2,
  1630. amsThresholds,
  1631. spoolmanEnabled = false,
  1632. linkedSpools,
  1633. spoolmanUrl,
  1634. spoolmanSyncMode,
  1635. onGetAssignment,
  1636. onUnassignSpool,
  1637. spoolmanSpools,
  1638. spoolmanSlotAssignments,
  1639. spoolmanLoading = false,
  1640. onUnassignSpoolmanSpool,
  1641. timeFormat = 'system',
  1642. cameraViewMode = 'window',
  1643. onOpenEmbeddedCamera,
  1644. checkPrinterFirmware = true,
  1645. dryingPresets = DRYING_PRESETS,
  1646. requirePlateClear = false,
  1647. selectionMode = false,
  1648. isSelected = false,
  1649. onToggleSelect,
  1650. onOpenCompactCard,
  1651. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1652. bedTempPresets = BED_TEMP_DEFAULTS,
  1653. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1654. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1655. }: {
  1656. printer: Printer;
  1657. hideIfDisconnected?: boolean;
  1658. maintenanceInfo?: PrinterMaintenanceInfo;
  1659. viewMode?: ViewMode;
  1660. cardSize?: number;
  1661. amsThresholds?: {
  1662. humidityGood: number;
  1663. humidityFair: number;
  1664. tempGood: number;
  1665. tempFair: number;
  1666. };
  1667. spoolmanEnabled?: boolean;
  1668. hasUnlinkedSpools?: boolean;
  1669. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1670. spoolmanUrl?: string | null;
  1671. spoolmanSyncMode?: string | null;
  1672. spoolAssignments?: SpoolAssignment[];
  1673. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1674. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1675. spoolmanSpools?: InventorySpool[];
  1676. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1677. spoolmanLoading?: boolean;
  1678. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1679. timeFormat?: 'system' | '12h' | '24h';
  1680. cameraViewMode?: 'window' | 'embedded';
  1681. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1682. checkPrinterFirmware?: boolean;
  1683. dryingPresets?: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }>;
  1684. requirePlateClear?: boolean;
  1685. selectionMode?: boolean;
  1686. isSelected?: boolean;
  1687. onToggleSelect?: (id: number) => void;
  1688. onOpenCompactCard?: (id: number) => void;
  1689. nozzleTempPresets?: readonly [number, number, number];
  1690. bedTempPresets?: readonly [number, number, number];
  1691. chamberTempPresets?: readonly [number, number, number];
  1692. fanSpeedPresets?: readonly [number, number, number];
  1693. }) {
  1694. const { t } = useTranslation();
  1695. const queryClient = useQueryClient();
  1696. const navigate = useNavigate();
  1697. const { showToast } = useToast();
  1698. const { hasPermission } = useAuth();
  1699. const [showMenu, setShowMenu] = useState(false);
  1700. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1701. const [deleteArchives, setDeleteArchives] = useState(true);
  1702. const [showEditModal, setShowEditModal] = useState(false);
  1703. const [showFileManager, setShowFileManager] = useState(false);
  1704. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1705. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1706. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1707. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1708. const [showHMSModal, setShowHMSModal] = useState(false);
  1709. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1710. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1711. const [showStopConfirm, setShowStopConfirm] = useState(false);
  1712. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  1713. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  1714. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  1715. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  1716. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  1717. const [bedJogStep, setBedJogStep] = useState<number>(10);
  1718. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  1719. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  1720. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  1721. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  1722. const [showDiagnostic, setShowDiagnostic] = useState(false);
  1723. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  1724. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  1725. // AMS drying popover state: which AMS unit has the popover open
  1726. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  1727. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  1728. const [dryingFilament, setDryingFilament] = useState('PLA');
  1729. const [dryingTemp, setDryingTemp] = useState(50);
  1730. const [dryingDuration, setDryingDuration] = useState(4);
  1731. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  1732. const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
  1733. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  1734. // an object rather than a bare id so restarting drying on the SAME unit produces
  1735. // a new identity and rearms the timeout below.
  1736. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  1737. const [isDraggingFile, setIsDraggingFile] = useState(false);
  1738. const [isDropUploading, setIsDropUploading] = useState(false);
  1739. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  1740. const dragCounterRef = useRef(0);
  1741. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  1742. amsId: number;
  1743. amsLabel: string;
  1744. mode: 'humidity' | 'temperature';
  1745. } | null>(null);
  1746. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  1747. initialKind: HeaterSensorKind;
  1748. availableKinds: HeaterSensorKind[];
  1749. } | null>(null);
  1750. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  1751. tagUid: string;
  1752. trayUuid: string;
  1753. printerId: number;
  1754. amsId: number;
  1755. trayId: number;
  1756. } | null>(null);
  1757. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  1758. printerId: number;
  1759. amsId: number;
  1760. trayId: number;
  1761. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  1762. } | null>(null);
  1763. const [configureSlotModal, setConfigureSlotModal] = useState<{
  1764. amsId: number;
  1765. trayId: number;
  1766. trayCount: number;
  1767. trayType?: string;
  1768. trayColor?: string;
  1769. traySubBrands?: string;
  1770. trayInfoIdx?: string;
  1771. extruderId?: number;
  1772. caliIdx?: number | null;
  1773. savedPresetId?: string;
  1774. } | null>(null);
  1775. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  1776. const [plateCheckResult, setPlateCheckResult] = useState<{
  1777. is_empty: boolean;
  1778. confidence: number;
  1779. difference_percent: number;
  1780. message: string;
  1781. debug_image_url?: string;
  1782. needs_calibration: boolean;
  1783. light_warning?: boolean;
  1784. reference_count?: number;
  1785. max_references?: number;
  1786. roi?: { x: number; y: number; w: number; h: number };
  1787. } | null>(null);
  1788. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  1789. const [isCalibrating, setIsCalibrating] = useState(false);
  1790. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  1791. const [isSavingRoi, setIsSavingRoi] = useState(false);
  1792. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  1793. const { data: status } = useQuery({
  1794. queryKey: ['printerStatus', printer.id],
  1795. queryFn: () => api.getPrinterStatus(printer.id),
  1796. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  1797. });
  1798. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  1799. const { data: firmwareInfo } = useQuery({
  1800. queryKey: ['firmwareUpdate', printer.id],
  1801. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  1802. staleTime: 5 * 60 * 1000,
  1803. refetchInterval: 5 * 60 * 1000,
  1804. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  1805. });
  1806. // Collect unique tray_info_idx values for cloud filament info lookup
  1807. const trayInfoIds = useMemo(() => {
  1808. const ids = new Set<string>();
  1809. if (status?.ams) {
  1810. for (const ams of status.ams) {
  1811. for (const tray of ams.tray || []) {
  1812. if (tray.tray_info_idx) {
  1813. ids.add(tray.tray_info_idx);
  1814. }
  1815. }
  1816. }
  1817. }
  1818. for (const vt of status?.vt_tray ?? []) {
  1819. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  1820. }
  1821. if (status?.nozzle_rack) {
  1822. for (const slot of status.nozzle_rack) {
  1823. if (slot.filament_id) {
  1824. ids.add(slot.filament_id);
  1825. }
  1826. }
  1827. }
  1828. return Array.from(ids);
  1829. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  1830. // Collect loaded filament types for queue widget filtering
  1831. const loadedFilamentTypes = useMemo(() => {
  1832. const types = new Set<string>();
  1833. if (status?.ams) {
  1834. for (const ams of status.ams) {
  1835. for (const tray of ams.tray || []) {
  1836. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  1837. }
  1838. }
  1839. }
  1840. for (const vt of status?.vt_tray ?? []) {
  1841. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  1842. }
  1843. return types;
  1844. }, [status?.ams, status?.vt_tray]);
  1845. // Collect loaded filament type+color pairs for queue widget override matching
  1846. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  1847. const loadedFilaments = useMemo(() => {
  1848. const filaments = new Set<string>();
  1849. if (status?.ams) {
  1850. for (const ams of status.ams) {
  1851. for (const tray of ams.tray || []) {
  1852. if (tray.tray_type && tray.tray_color) {
  1853. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1854. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  1855. }
  1856. }
  1857. }
  1858. }
  1859. for (const vt of status?.vt_tray ?? []) {
  1860. if (vt.tray_type && vt.tray_color) {
  1861. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1862. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  1863. }
  1864. }
  1865. return filaments;
  1866. }, [status?.ams, status?.vt_tray]);
  1867. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  1868. const { data: filamentInfo } = useQuery({
  1869. queryKey: ['filamentInfo', trayInfoIds],
  1870. queryFn: () => api.getFilamentInfo(trayInfoIds),
  1871. enabled: trayInfoIds.length > 0,
  1872. staleTime: 5 * 60 * 1000, // 5 minutes
  1873. });
  1874. // Fetch slot preset mappings (stores preset name for user-configured slots)
  1875. const { data: slotPresets } = useQuery({
  1876. queryKey: ['slotPresets', printer.id],
  1877. queryFn: () => api.getSlotPresets(printer.id),
  1878. staleTime: 2 * 60 * 1000, // 2 minutes
  1879. });
  1880. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  1881. // Only queried when there's a running print backed by an archive; shared
  1882. // React Query cache with the Queue / Archives pages keeps it cheap.
  1883. const activeArchiveId =
  1884. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  1885. const { data: activeArchivePlates } = useQuery({
  1886. queryKey: ['archive-plates', activeArchiveId],
  1887. queryFn: () => api.getArchivePlates(activeArchiveId!),
  1888. enabled: activeArchiveId != null,
  1889. staleTime: 5 * 60 * 1000,
  1890. });
  1891. const activePlateLabel = (() => {
  1892. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  1893. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  1894. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  1895. })();
  1896. // Fetch user-defined AMS friendly names from the database
  1897. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  1898. queryKey: ['amsLabels', printer.id],
  1899. queryFn: () => api.getAmsLabels(printer.id),
  1900. staleTime: 5 * 60 * 1000, // 5 minutes
  1901. });
  1902. // Cache WiFi signal to prevent it disappearing on updates
  1903. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  1904. useEffect(() => {
  1905. if (status?.wifi_signal != null) {
  1906. setCachedWifiSignal(status.wifi_signal);
  1907. }
  1908. }, [status?.wifi_signal]);
  1909. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  1910. // Cache connected state to prevent flicker when status briefly becomes undefined
  1911. const cachedConnected = useRef<boolean | undefined>(undefined);
  1912. useEffect(() => {
  1913. if (status?.connected !== undefined) {
  1914. cachedConnected.current = status.connected;
  1915. }
  1916. }, [status?.connected]);
  1917. const isConnected = status?.connected ?? cachedConnected.current;
  1918. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  1919. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  1920. useEffect(() => {
  1921. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  1922. cachedAmsExtruderMap.current = status.ams_extruder_map;
  1923. }
  1924. }, [status?.ams_extruder_map]);
  1925. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  1926. ? status.ams_extruder_map
  1927. : cachedAmsExtruderMap.current;
  1928. // Cache AMS data to prevent it disappearing on idle/offline printers
  1929. const cachedAmsData = useRef<AMSUnit[]>([]);
  1930. useEffect(() => {
  1931. if (status?.ams && status.ams.length > 0) {
  1932. cachedAmsData.current = status.ams;
  1933. }
  1934. }, [status?.ams]);
  1935. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  1936. // Confirm a drying cycle actually started (#2533). Firmware answers
  1937. // ams_filament_drying with result=success even when it then silently declines,
  1938. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  1939. // reason guard is blind there and the card just sits unchanged. Watch the unit
  1940. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  1941. // means the printer took the command and dropped it.
  1942. useEffect(() => {
  1943. if (!dryStartWatch) return;
  1944. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  1945. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  1946. }, [dryStartWatch, amsData]);
  1947. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  1948. // otherwise rearm the timeout on every frame, so it would never elapse.
  1949. useEffect(() => {
  1950. if (!dryStartWatch) return;
  1951. const timer = setTimeout(() => {
  1952. setDryStartWatch(null);
  1953. showToast(t('printers.drying.toastNotStarted'), 'error');
  1954. }, DRY_START_CONFIRM_MS);
  1955. return () => clearTimeout(timer);
  1956. }, [dryStartWatch, showToast, t]);
  1957. // Cache tray_now to prevent flickering when undefined values come in
  1958. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  1959. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  1960. const cachedTrayNow = useRef<number | undefined>(undefined);
  1961. const currentTrayNow = status?.tray_now;
  1962. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  1963. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  1964. cachedTrayNow.current = currentTrayNow;
  1965. } else if (currentTrayNow === 255) {
  1966. cachedTrayNow.current = undefined;
  1967. }
  1968. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  1969. ? currentTrayNow
  1970. : cachedTrayNow.current;
  1971. // Runout / filament-replacement guidance (#2587). The backend fills these only
  1972. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  1973. // expectedTray = the slot the firmware now expects filament in
  1974. // previousTray = the slot that ran out
  1975. // With AMS Filament Backup the firmware advances to the next compatible slot,
  1976. // so these are often different — the graphic highlights the expected one.
  1977. const expectedTray = status?.expected_tray ?? null;
  1978. const previousTray = status?.previous_tray ?? null;
  1979. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  1980. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  1981. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  1982. if (globalId === null) return null;
  1983. if (globalId === 254) return t('printers.expectedSlot.external');
  1984. if (globalId >= 128 && globalId <= 135) {
  1985. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  1986. }
  1987. const amsId = Math.floor(globalId / 4);
  1988. const slot = globalId % 4;
  1989. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  1990. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  1991. };
  1992. const runoutGuidance = status?.state === 'PAUSE'
  1993. ? {
  1994. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  1995. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  1996. }
  1997. : null;
  1998. // Fetch smart plug for this printer
  1999. const { data: smartPlug } = useQuery({
  2000. queryKey: ['smartPlugByPrinter', printer.id],
  2001. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2002. });
  2003. // Fetch script plugs for this printer (for multi-device control)
  2004. const { data: scriptPlugs } = useQuery({
  2005. queryKey: ['scriptPlugsByPrinter', printer.id],
  2006. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2007. });
  2008. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2009. const { data: plugStatus } = useQuery({
  2010. queryKey: ['smartPlugStatus', smartPlug?.id],
  2011. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2012. enabled: !!smartPlug,
  2013. refetchInterval: 10000, // 10 seconds for real-time power display
  2014. });
  2015. // Fetch queue count for this printer
  2016. const { data: queueItems } = useQuery({
  2017. queryKey: ['queue', printer.id, 'pending'],
  2018. queryFn: () => api.getQueue(printer.id, 'pending'),
  2019. });
  2020. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2021. // so the badge only shows on printers that can actually run the queued jobs.
  2022. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2023. const queueCount = useMemo(() => {
  2024. if (!queueItems?.length) return 0;
  2025. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments).length;
  2026. }, [queueItems, loadedFilamentTypes, loadedFilaments]);
  2027. // Fetch currently printing queue item to show who started it (Issue #206)
  2028. const { data: printingQueueItems } = useQuery({
  2029. queryKey: ['queue', printer.id, 'printing'],
  2030. queryFn: () => api.getQueue(printer.id, 'printing'),
  2031. enabled: status?.state === 'RUNNING',
  2032. });
  2033. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2034. const { data: reprintUser } = useQuery({
  2035. queryKey: ['currentPrintUser', printer.id],
  2036. queryFn: () => api.getCurrentPrintUser(printer.id),
  2037. enabled: status?.state === 'RUNNING',
  2038. });
  2039. // Combine both sources: queue item user takes precedence, then reprint user
  2040. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2041. // Fetch last completed print for this printer
  2042. const { data: lastPrints } = useQuery({
  2043. queryKey: ['archives', printer.id, 'last'],
  2044. queryFn: () => api.getArchives(printer.id, 1, 0),
  2045. enabled: status?.connected && status?.state !== 'RUNNING',
  2046. });
  2047. const lastPrint = lastPrints?.[0];
  2048. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2049. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2050. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  2051. const activePrintName = status?.current_print && isPrintingOrPaused
  2052. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2053. : null;
  2054. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2055. useEffect(() => {
  2056. if (activePrintName) {
  2057. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2058. } else if (!needsPlateClear) {
  2059. setRetainedPrintJob(null);
  2060. }
  2061. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2062. const plateStatus = (() => {
  2063. if (!requirePlateClear || !status?.connected) return null;
  2064. if (isPrintingOrPaused) {
  2065. return {
  2066. label: t('printers.plateStatus.inUse'),
  2067. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2068. };
  2069. }
  2070. if (status.awaiting_plate_clear) {
  2071. return {
  2072. label: t('printers.plateStatus.notCleared'),
  2073. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2074. };
  2075. }
  2076. return {
  2077. label: t('printers.plateStatus.cleared'),
  2078. className: 'bg-status-ok/20 text-status-ok',
  2079. };
  2080. })();
  2081. const plateStatusPill = plateStatus ? (
  2082. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${plateStatus.className}`}>
  2083. {plateStatus.label}
  2084. </span>
  2085. ) : null;
  2086. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2087. const shouldHide = hideIfDisconnected && isConnected === false;
  2088. const deleteMutation = useMutation({
  2089. mutationFn: (options: { deleteArchives: boolean }) =>
  2090. api.deletePrinter(printer.id, options.deleteArchives),
  2091. onSuccess: () => {
  2092. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2093. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2094. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2095. },
  2096. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2097. });
  2098. const connectMutation = useMutation({
  2099. mutationFn: () => api.connectPrinter(printer.id),
  2100. onSuccess: () => {
  2101. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2102. },
  2103. });
  2104. const forceRefreshMutation = useMutation({
  2105. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2106. onSuccess: () => {
  2107. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2108. showToast(t('printers.forceRefreshSuccess'), 'success');
  2109. },
  2110. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2111. });
  2112. const unlinkSpoolMutation = useMutation({
  2113. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2114. onSuccess: (result) => {
  2115. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2116. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2117. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2118. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2119. },
  2120. onError: (error: Error) => {
  2121. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2122. },
  2123. });
  2124. // AMS drying mutations
  2125. const startDryingMutation = useMutation({
  2126. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2127. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2128. onSuccess: (_data, { amsId }) => {
  2129. setDryingPopoverAmsId(null);
  2130. setDryStartWatch({ amsId });
  2131. // "Command sent", not "drying started" — at this point the printer has only
  2132. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2133. // the cycle is genuinely live; the watcher below covers the case where it
  2134. // never appears.
  2135. showToast(t('printers.drying.toastCommandSent'), 'success');
  2136. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2137. },
  2138. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2139. });
  2140. const stopDryingMutation = useMutation({
  2141. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2142. onSuccess: () => {
  2143. setDryStartWatch(null);
  2144. showToast(t('printers.drying.toastStopped'), 'success');
  2145. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2146. },
  2147. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2148. });
  2149. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2150. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2151. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2152. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2153. // showing the old backup state until the user reopens it.
  2154. const setAmsBackupMutation = useMutation({
  2155. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2156. onSuccess: (_data, enabled) => {
  2157. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2158. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2159. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2160. },
  2161. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2162. });
  2163. // Smart plug control mutations
  2164. const powerControlMutation = useMutation({
  2165. mutationFn: (action: 'on' | 'off') =>
  2166. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2167. onSuccess: () => {
  2168. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2169. },
  2170. });
  2171. const toggleAutoOffMutation = useMutation({
  2172. mutationFn: (enabled: boolean) =>
  2173. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2174. onSuccess: () => {
  2175. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2176. // Also invalidate the smart-plugs list to keep Settings page in sync
  2177. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2178. },
  2179. });
  2180. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2181. const runScriptMutation = useMutation({
  2182. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2183. onSuccess: () => {
  2184. showToast(t('printers.toast.scriptTriggered'));
  2185. },
  2186. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2187. });
  2188. // Print control mutations
  2189. const stopPrintMutation = useMutation({
  2190. mutationFn: () => api.stopPrint(printer.id),
  2191. onSuccess: () => {
  2192. showToast(t('printers.toast.printStopped'));
  2193. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2194. },
  2195. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2196. });
  2197. const pausePrintMutation = useMutation({
  2198. mutationFn: () => api.pausePrint(printer.id),
  2199. onSuccess: () => {
  2200. showToast(t('printers.toast.printPaused'));
  2201. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2202. },
  2203. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2204. });
  2205. const resumePrintMutation = useMutation({
  2206. mutationFn: () => api.resumePrint(printer.id),
  2207. onSuccess: () => {
  2208. showToast(t('printers.toast.printResumed'));
  2209. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2210. },
  2211. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2212. });
  2213. const clearPlateMutation = useMutation({
  2214. mutationFn: () => api.clearPlate(printer.id),
  2215. onSuccess: () => {
  2216. showToast(t('queue.clearPlateSuccess'));
  2217. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2218. old ? { ...old, awaiting_plate_clear: false } : old
  2219. );
  2220. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2221. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2222. },
  2223. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2224. });
  2225. const nozzleTemperatureMutation = useMutation({
  2226. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2227. api.setNozzleTemperature(printer.id, target, nozzle),
  2228. onSuccess: (result) => {
  2229. setStatusControlMenu(null);
  2230. showToast(result.message);
  2231. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2232. },
  2233. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2234. });
  2235. const bedTemperatureMutation = useMutation({
  2236. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2237. onSuccess: (result) => {
  2238. setStatusControlMenu(null);
  2239. showToast(result.message);
  2240. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2241. },
  2242. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2243. });
  2244. const chamberTemperatureMutation = useMutation({
  2245. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2246. onSuccess: (result) => {
  2247. setStatusControlMenu(null);
  2248. showToast(result.message);
  2249. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2250. },
  2251. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2252. });
  2253. const fanSpeedMutation = useMutation({
  2254. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'chamber'; speed: number }) =>
  2255. api.setFanSpeed(printer.id, fan, speed),
  2256. onMutate: async ({ fan, speed }) => {
  2257. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2258. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2259. const fanField = {
  2260. part: 'cooling_fan_speed',
  2261. aux: 'big_fan1_speed',
  2262. chamber: 'big_fan2_speed',
  2263. }[fan];
  2264. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2265. old ? { ...old, [fanField]: speed } : old
  2266. );
  2267. return { previousStatus };
  2268. },
  2269. onSuccess: (result) => {
  2270. setStatusControlMenu(null);
  2271. showToast(result.message);
  2272. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2273. },
  2274. onError: (error: Error, _variables, context) => {
  2275. if (context?.previousStatus) {
  2276. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2277. }
  2278. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2279. },
  2280. });
  2281. const selectExtruderMutation = useMutation({
  2282. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2283. onMutate: async (extruder) => {
  2284. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2285. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2286. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2287. old ? { ...old, active_extruder: extruder } : old
  2288. );
  2289. return { previousStatus };
  2290. },
  2291. onSuccess: (result) => {
  2292. setStatusControlMenu(null);
  2293. showToast(result.message);
  2294. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2295. },
  2296. onError: (error: Error, _extruder, context) => {
  2297. if (context?.previousStatus) {
  2298. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2299. }
  2300. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2301. },
  2302. });
  2303. // Chamber light mutation with optimistic update
  2304. const chamberLightMutation = useMutation({
  2305. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2306. onMutate: async (on) => {
  2307. // Cancel any outgoing refetches
  2308. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2309. // Snapshot the previous value
  2310. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2311. // Optimistically update
  2312. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2313. ...old,
  2314. chamber_light: on,
  2315. }));
  2316. return { previousStatus };
  2317. },
  2318. onSuccess: (_, on) => {
  2319. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2320. },
  2321. onError: (error: Error, _, context) => {
  2322. // Rollback on error
  2323. if (context?.previousStatus) {
  2324. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2325. }
  2326. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2327. },
  2328. });
  2329. // Print speed mutation with optimistic update
  2330. const printSpeedMutation = useMutation({
  2331. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2332. onMutate: async (mode) => {
  2333. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2334. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2335. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2336. ...old,
  2337. speed_level: mode,
  2338. }));
  2339. return { previousStatus };
  2340. },
  2341. onError: (error: Error, _, context) => {
  2342. if (context?.previousStatus) {
  2343. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2344. }
  2345. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2346. },
  2347. });
  2348. const airductMutation = useMutation({
  2349. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2350. onMutate: async (mode) => {
  2351. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2352. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2353. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2354. ...old,
  2355. airduct_mode: mode === 'cooling' ? 0 : 1,
  2356. }));
  2357. return { previousStatus };
  2358. },
  2359. onError: (error: Error, _, context) => {
  2360. if (context?.previousStatus) {
  2361. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2362. }
  2363. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2364. },
  2365. });
  2366. const bedJogMutation = useMutation({
  2367. mutationFn: ({ distance }: { distance: number }) =>
  2368. api.bedJog(printer.id, distance),
  2369. onError: (error: Error) =>
  2370. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2371. });
  2372. const xyJogMutation = useMutation({
  2373. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2374. api.xyJog(printer.id, x, y),
  2375. onError: (error: Error) =>
  2376. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2377. });
  2378. const extruderJogMutation = useMutation({
  2379. mutationFn: (distance: number) =>
  2380. api.extruderJog(printer.id, distance),
  2381. onError: (error: Error) =>
  2382. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2383. });
  2384. const homeAxesMutation = useMutation({
  2385. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2386. onSuccess: () => {
  2387. showToast(t('printers.bedJog.homingStarted'));
  2388. },
  2389. onError: (error: Error) =>
  2390. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2391. });
  2392. // Plate detection setting mutation
  2393. const plateDetectionMutation = useMutation({
  2394. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2395. onSuccess: () => {
  2396. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2397. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2398. },
  2399. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2400. });
  2401. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2402. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2403. // metrics, and the print picker — so flipping this flag puts the printer
  2404. // out of service across every consumer in one place. Used from the
  2405. // overflow menu and EditPrinterModal.
  2406. const maintenanceMutation = useMutation({
  2407. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2408. onSuccess: (_data, isActive) => {
  2409. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2410. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2411. showToast(
  2412. isActive
  2413. ? t('printers.maintenance.toastExited', { name: printer.name })
  2414. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2415. 'success',
  2416. );
  2417. },
  2418. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2419. });
  2420. // Confirm before entering maintenance on a printing printer (entering mode
  2421. // disconnects MQTT, which stops progress tracking + completion notifications
  2422. // for the in-flight job).
  2423. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2424. const handleEnterMaintenance = () => {
  2425. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2426. setConfirmMaintenanceEnter(true);
  2427. } else {
  2428. maintenanceMutation.mutate(false);
  2429. }
  2430. };
  2431. // Query for printable objects (for skip functionality)
  2432. // Fetch when printing with 2+ objects OR when modal is open
  2433. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2434. const { data: objectsData } = useQuery({
  2435. queryKey: ['printableObjects', printer.id],
  2436. queryFn: () => api.getPrintableObjects(printer.id),
  2437. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2438. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2439. });
  2440. // State for tracking which AMS slot is being refreshed
  2441. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2442. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2443. const seenBusyStateRef = useRef<boolean>(false);
  2444. // Fallback timeout ref
  2445. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2446. // Minimum display time passed
  2447. const minTimePassedRef = useRef<boolean>(false);
  2448. // AMS slot refresh mutation
  2449. const refreshAmsSlotMutation = useMutation({
  2450. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2451. api.refreshAmsSlot(printer.id, amsId, slotId),
  2452. onMutate: ({ amsId, slotId }) => {
  2453. // Clear any existing timeout
  2454. if (refreshTimeoutRef.current) {
  2455. clearTimeout(refreshTimeoutRef.current);
  2456. }
  2457. // Reset state
  2458. seenBusyStateRef.current = false;
  2459. minTimePassedRef.current = false;
  2460. setRefreshingSlot({ amsId, slotId });
  2461. // Minimum display time (2 seconds)
  2462. setTimeout(() => {
  2463. minTimePassedRef.current = true;
  2464. }, 2000);
  2465. // Fallback timeout (30 seconds max)
  2466. refreshTimeoutRef.current = setTimeout(() => {
  2467. setRefreshingSlot(null);
  2468. }, 30000);
  2469. },
  2470. onSuccess: (data) => {
  2471. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2472. },
  2473. onError: (error: Error) => {
  2474. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2475. if (refreshTimeoutRef.current) {
  2476. clearTimeout(refreshTimeoutRef.current);
  2477. }
  2478. setRefreshingSlot(null);
  2479. },
  2480. });
  2481. // AMS load/unload mutations (#891)
  2482. const loadAmsTrayMutation = useMutation({
  2483. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2484. onSuccess: (data) => {
  2485. showToast(data.message || t('printers.toast.loadInitiated'));
  2486. },
  2487. onError: (error: Error) => {
  2488. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2489. },
  2490. });
  2491. const unloadAmsMutation = useMutation({
  2492. mutationFn: () => api.unloadAms(printer.id),
  2493. onSuccess: (data) => {
  2494. showToast(data.message || t('printers.toast.unloadInitiated'));
  2495. },
  2496. onError: (error: Error) => {
  2497. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2498. },
  2499. });
  2500. // Plate references state
  2501. const [plateReferences, setPlateReferences] = useState<{
  2502. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2503. max_references: number;
  2504. } | null>(null);
  2505. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2506. // Fetch plate references
  2507. const fetchPlateReferences = async () => {
  2508. try {
  2509. const data = await api.getPlateReferences(printer.id);
  2510. setPlateReferences(data);
  2511. } catch {
  2512. // Ignore errors - references will show as empty
  2513. }
  2514. };
  2515. // Toggle plate detection enabled/disabled
  2516. const handleTogglePlateDetection = () => {
  2517. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2518. };
  2519. // Open plate detection management modal (for calibration/references)
  2520. const handleOpenPlateManagement = async () => {
  2521. setIsCheckingPlate(true);
  2522. setPlateCheckResult(null);
  2523. // Auto-turn on light if it's off
  2524. const lightWasOff = status?.chamber_light === false;
  2525. setPlateCheckLightWasOff(lightWasOff);
  2526. if (lightWasOff) {
  2527. await api.setChamberLight(printer.id, true);
  2528. // Wait for light to physically turn on and camera to adjust exposure
  2529. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2530. await new Promise(resolve => setTimeout(resolve, 2500));
  2531. }
  2532. try {
  2533. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2534. setPlateCheckResult(result);
  2535. fetchPlateReferences();
  2536. } catch (error) {
  2537. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2538. // Restore light if check failed
  2539. if (lightWasOff) {
  2540. await api.setChamberLight(printer.id, false);
  2541. setPlateCheckLightWasOff(false);
  2542. }
  2543. } finally {
  2544. setIsCheckingPlate(false);
  2545. }
  2546. };
  2547. // Close plate check modal and restore light state
  2548. const closePlateCheckModal = useCallback(async () => {
  2549. setPlateCheckResult(null);
  2550. // Restore light to original state if we turned it on
  2551. if (plateCheckLightWasOff) {
  2552. await api.setChamberLight(printer.id, false);
  2553. setPlateCheckLightWasOff(false);
  2554. }
  2555. }, [plateCheckLightWasOff, printer.id]);
  2556. // Calibrate plate detection handler
  2557. const handleCalibratePlate = async (label?: string) => {
  2558. setIsCalibrating(true);
  2559. try {
  2560. const result = await api.calibratePlateDetection(printer.id, { label });
  2561. if (result.success) {
  2562. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2563. // Refresh references and re-check
  2564. fetchPlateReferences();
  2565. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2566. setPlateCheckResult(checkResult);
  2567. } else {
  2568. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2569. }
  2570. } catch (error) {
  2571. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2572. } finally {
  2573. setIsCalibrating(false);
  2574. }
  2575. };
  2576. // Update reference label
  2577. const handleUpdateRefLabel = async (index: number, label: string) => {
  2578. try {
  2579. await api.updatePlateReferenceLabel(printer.id, index, label);
  2580. setEditingRefLabel(null);
  2581. fetchPlateReferences();
  2582. } catch (error) {
  2583. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  2584. }
  2585. };
  2586. // Delete reference
  2587. const handleDeleteRef = async (index: number) => {
  2588. try {
  2589. await api.deletePlateReference(printer.id, index);
  2590. showToast(t('printers.toast.referenceDeleted'), 'success');
  2591. fetchPlateReferences();
  2592. // Re-check to update counts
  2593. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2594. setPlateCheckResult(checkResult);
  2595. } catch (error) {
  2596. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  2597. }
  2598. };
  2599. // Save ROI settings
  2600. const handleSaveRoi = async () => {
  2601. if (!editingRoi) return;
  2602. setIsSavingRoi(true);
  2603. try {
  2604. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  2605. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  2606. setEditingRoi(null);
  2607. // Re-check to see new ROI in action
  2608. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2609. setPlateCheckResult(checkResult);
  2610. } catch (error) {
  2611. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  2612. } finally {
  2613. setIsSavingRoi(false);
  2614. }
  2615. };
  2616. // Close plate check modal on Escape key
  2617. useEffect(() => {
  2618. const handleEscape = (e: KeyboardEvent) => {
  2619. if (e.key === 'Escape' && plateCheckResult) {
  2620. closePlateCheckModal();
  2621. }
  2622. };
  2623. window.addEventListener('keydown', handleEscape);
  2624. return () => window.removeEventListener('keydown', handleEscape);
  2625. }, [plateCheckResult, closePlateCheckModal]);
  2626. // Watch ams_status_main to detect when RFID read completes
  2627. // ams_status_main: 0=idle, 2=rfid_identifying
  2628. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2629. useEffect(() => {
  2630. if (!refreshingSlot) return;
  2631. const amsStatus = status?.ams_status_main ?? 0;
  2632. // Track when we see non-idle state (printer is working)
  2633. if (amsStatus !== 0) {
  2634. seenBusyStateRef.current = true;
  2635. // Cancel any deferred clear since we're back to busy
  2636. if (deferredClearRef.current) {
  2637. clearTimeout(deferredClearRef.current);
  2638. deferredClearRef.current = null;
  2639. }
  2640. }
  2641. // When we've seen busy and now idle, clear (with min time check)
  2642. if (seenBusyStateRef.current && amsStatus === 0) {
  2643. if (minTimePassedRef.current) {
  2644. // Min time passed - clear now
  2645. if (refreshTimeoutRef.current) {
  2646. clearTimeout(refreshTimeoutRef.current);
  2647. }
  2648. setRefreshingSlot(null);
  2649. } else {
  2650. // Schedule clear after min time (2 seconds from start)
  2651. if (!deferredClearRef.current) {
  2652. deferredClearRef.current = setTimeout(() => {
  2653. if (refreshTimeoutRef.current) {
  2654. clearTimeout(refreshTimeoutRef.current);
  2655. }
  2656. setRefreshingSlot(null);
  2657. }, 2000);
  2658. }
  2659. }
  2660. }
  2661. return () => {
  2662. if (deferredClearRef.current) {
  2663. clearTimeout(deferredClearRef.current);
  2664. }
  2665. };
  2666. }, [status?.ams_status_main, refreshingSlot]);
  2667. useEffect(() => {
  2668. if (!showMenu) return;
  2669. const handleClickOutside = (event: MouseEvent) => {
  2670. const target = event.target as Node;
  2671. if (!printerActionsMenuRef.current?.contains(target)) {
  2672. setShowMenu(false);
  2673. }
  2674. };
  2675. document.addEventListener('mousedown', handleClickOutside);
  2676. return () => document.removeEventListener('mousedown', handleClickOutside);
  2677. }, [showMenu]);
  2678. if (shouldHide) {
  2679. return null;
  2680. }
  2681. // Size-based styling helpers
  2682. const getImageSize = () => {
  2683. switch (cardSize) {
  2684. case 1: return 'w-10 h-10';
  2685. case 2: return 'w-14 h-14';
  2686. case 3: return 'w-16 h-16';
  2687. case 4: return 'w-20 h-20';
  2688. default: return 'w-14 h-14';
  2689. }
  2690. };
  2691. const getTitleSize = () => {
  2692. switch (cardSize) {
  2693. case 1: return 'text-base truncate';
  2694. case 2: return 'text-lg';
  2695. case 3: return 'text-xl';
  2696. case 4: return 'text-2xl';
  2697. default: return 'text-lg';
  2698. }
  2699. };
  2700. const getSpacing = () => {
  2701. switch (cardSize) {
  2702. case 1: return 'mb-2';
  2703. case 2: return 'mb-4';
  2704. case 3: return 'mb-5';
  2705. case 4: return 'mb-6';
  2706. default: return 'mb-4';
  2707. }
  2708. };
  2709. const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
  2710. const handleCardDragEnter = (e: React.DragEvent) => {
  2711. e.preventDefault();
  2712. dragCounterRef.current++;
  2713. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  2714. };
  2715. const handleCardDragOver = (e: React.DragEvent) => {
  2716. e.preventDefault();
  2717. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  2718. };
  2719. const handleCardDragLeave = (e: React.DragEvent) => {
  2720. e.preventDefault();
  2721. dragCounterRef.current--;
  2722. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  2723. };
  2724. const handleCardDrop = async (e: React.DragEvent) => {
  2725. e.preventDefault();
  2726. dragCounterRef.current = 0;
  2727. setIsDraggingFile(false);
  2728. if (!canDrop) return;
  2729. const droppedFiles = Array.from(e.dataTransfer.files);
  2730. const file = droppedFiles[0];
  2731. if (!file) return;
  2732. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  2733. const lower = file.name.toLowerCase();
  2734. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  2735. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  2736. return;
  2737. }
  2738. setIsDropUploading(true);
  2739. try {
  2740. const result = await api.uploadLibraryFile(file, null);
  2741. // Check printer compatibility if sliced_for_model is available in metadata
  2742. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  2743. const printerModel = mapModelCode(printer.model);
  2744. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  2745. await api.deleteLibraryFile(result.id).catch(() => {});
  2746. showToast(
  2747. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  2748. 'error'
  2749. );
  2750. return;
  2751. }
  2752. setPrintAfterUpload({ id: result.id, filename: result.filename });
  2753. } catch {
  2754. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  2755. } finally {
  2756. setIsDropUploading(false);
  2757. }
  2758. };
  2759. const handleCardClick = (e: React.MouseEvent) => {
  2760. if (viewMode !== 'compact' || selectionMode) return;
  2761. const target = e.target as HTMLElement;
  2762. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  2763. onOpenCompactCard?.(printer.id);
  2764. };
  2765. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  2766. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  2767. const renderAmsSlotActions = ({
  2768. amsId,
  2769. slotId,
  2770. loadTrayId,
  2771. isRefreshing,
  2772. includeRfid = true,
  2773. }: {
  2774. amsId: number;
  2775. slotId: number;
  2776. loadTrayId: number;
  2777. isRefreshing?: boolean;
  2778. includeRfid?: boolean;
  2779. }) => {
  2780. const printerBusy = status?.state === 'RUNNING';
  2781. return (
  2782. <>
  2783. {includeRfid && (
  2784. <button
  2785. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2786. hasPermission('printers:ams_rfid')
  2787. ? 'text-white hover:bg-bambu-dark-tertiary'
  2788. : 'text-bambu-gray/50 cursor-not-allowed'
  2789. }`}
  2790. onClick={(e) => {
  2791. e.stopPropagation();
  2792. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  2793. refreshAmsSlotMutation.mutate({ amsId, slotId });
  2794. }}
  2795. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  2796. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  2797. >
  2798. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  2799. {t('printers.rfid.reread')}
  2800. </button>
  2801. )}
  2802. <button
  2803. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2804. hasPermission('printers:control')
  2805. ? 'text-white hover:bg-bambu-dark-tertiary'
  2806. : 'text-bambu-gray/50 cursor-not-allowed'
  2807. }`}
  2808. onClick={(e) => {
  2809. e.stopPropagation();
  2810. if (printerBusy || !hasPermission('printers:control')) return;
  2811. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  2812. }}
  2813. disabled={printerBusy || !hasPermission('printers:control')}
  2814. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2815. >
  2816. <LogIn className="w-3 h-3" />
  2817. {t('printers.ams.load')}
  2818. </button>
  2819. <button
  2820. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2821. hasPermission('printers:control')
  2822. ? 'text-white hover:bg-bambu-dark-tertiary'
  2823. : 'text-bambu-gray/50 cursor-not-allowed'
  2824. }`}
  2825. onClick={(e) => {
  2826. e.stopPropagation();
  2827. if (printerBusy || !hasPermission('printers:control')) return;
  2828. unloadAmsMutation.mutate();
  2829. }}
  2830. disabled={printerBusy || !hasPermission('printers:control')}
  2831. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2832. >
  2833. <LogOut className="w-3 h-3" />
  2834. {t('printers.ams.unload')}
  2835. </button>
  2836. </>
  2837. );
  2838. };
  2839. const printerActionsMenu = (
  2840. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  2841. <Button
  2842. variant="secondary"
  2843. size="sm"
  2844. onClick={() => setShowMenu(!showMenu)}
  2845. title={t('common.more', 'More')}
  2846. className={footerIconButtonClass}
  2847. >
  2848. <MoreVertical className="w-4 h-4" />
  2849. </Button>
  2850. {showMenu && (
  2851. <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">
  2852. <button
  2853. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2854. hasPermission('printers:update')
  2855. ? 'hover:bg-bambu-dark-tertiary'
  2856. : 'opacity-50 cursor-not-allowed'
  2857. }`}
  2858. onClick={() => {
  2859. if (!hasPermission('printers:update')) return;
  2860. setShowEditModal(true);
  2861. setShowMenu(false);
  2862. }}
  2863. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2864. >
  2865. <Pencil className="w-4 h-4" />
  2866. {t('common.edit')}
  2867. </button>
  2868. <button
  2869. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2870. onClick={() => {
  2871. setShowPrinterInfo(true);
  2872. setShowMenu(false);
  2873. }}
  2874. >
  2875. <Info className="w-4 h-4" />
  2876. {t('printers.printerInformation')}
  2877. </button>
  2878. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  2879. <button
  2880. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2881. hasPermission('printers:update')
  2882. ? 'hover:bg-bambu-dark-tertiary'
  2883. : 'opacity-50 cursor-not-allowed'
  2884. }`}
  2885. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  2886. onClick={() => {
  2887. if (!hasPermission('printers:update')) return;
  2888. setShowMenu(false);
  2889. if (printer.is_active !== false) {
  2890. handleEnterMaintenance();
  2891. } else {
  2892. maintenanceMutation.mutate(true);
  2893. }
  2894. }}
  2895. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2896. >
  2897. <Wrench className="w-4 h-4" />
  2898. {printer.is_active !== false
  2899. ? t('printers.maintenance.menuEnter')
  2900. : t('printers.maintenance.menuExit')}
  2901. </button>
  2902. <button
  2903. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2904. onClick={() => {
  2905. connectMutation.mutate();
  2906. setShowMenu(false);
  2907. }}
  2908. >
  2909. <RefreshCw className="w-4 h-4" />
  2910. {t('printers.reconnect')}
  2911. </button>
  2912. <button
  2913. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  2914. disabled={forceRefreshMutation.isPending}
  2915. onClick={() => {
  2916. forceRefreshMutation.mutate();
  2917. setShowMenu(false);
  2918. }}
  2919. >
  2920. <RotateCw className={`w-4 h-4 ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  2921. {t('printers.forceRefresh')}
  2922. </button>
  2923. <button
  2924. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2925. onClick={() => {
  2926. setShowMQTTDebug(true);
  2927. setShowMenu(false);
  2928. }}
  2929. >
  2930. <Terminal className="w-4 h-4" />
  2931. {t('printers.mqttDebug')}
  2932. </button>
  2933. <button
  2934. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2935. onClick={() => {
  2936. setShowDiagnostic(true);
  2937. setShowMenu(false);
  2938. }}
  2939. >
  2940. <Stethoscope className="w-4 h-4" />
  2941. {t('diagnostic.runButton')}
  2942. </button>
  2943. <button
  2944. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2945. hasPermission('printers:delete')
  2946. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  2947. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  2948. }`}
  2949. onClick={() => {
  2950. if (!hasPermission('printers:delete')) return;
  2951. setShowDeleteConfirm(true);
  2952. setShowMenu(false);
  2953. }}
  2954. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  2955. >
  2956. <Trash2 className="w-4 h-4" />
  2957. {t('common.delete')}
  2958. </button>
  2959. </div>
  2960. )}
  2961. </div>
  2962. );
  2963. return (
  2964. <Card
  2965. id={`printer-card-${printer.id}`}
  2966. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  2967. onClick={handleCardClick}
  2968. onDragEnter={handleCardDragEnter}
  2969. onDragOver={handleCardDragOver}
  2970. onDragLeave={handleCardDragLeave}
  2971. onDrop={handleCardDrop}
  2972. >
  2973. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  2974. {selectionMode && (
  2975. <div
  2976. className="absolute inset-0 z-20 flex items-start p-2"
  2977. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  2978. >
  2979. {isSelected ? (
  2980. <CheckSquare className="w-5 h-5 text-bambu-green" />
  2981. ) : (
  2982. <Square className="w-5 h-5 text-bambu-gray" />
  2983. )}
  2984. </div>
  2985. )}
  2986. {/* Drop zone overlay */}
  2987. {(isDraggingFile || isDropUploading) && (
  2988. <div
  2989. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  2990. isDropUploading
  2991. ? 'bg-bambu-green/10 border-bambu-green/50'
  2992. : canDrop
  2993. ? 'bg-bambu-green/10 border-bambu-green'
  2994. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  2995. }`}
  2996. >
  2997. <div className="text-center">
  2998. {isDropUploading ? (
  2999. <>
  3000. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3001. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3002. </>
  3003. ) : canDrop ? (
  3004. <>
  3005. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3006. <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
  3007. </>
  3008. ) : (
  3009. <>
  3010. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3011. <p className="text-sm font-medium text-red-700 dark:text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
  3012. </>
  3013. )}
  3014. </div>
  3015. </div>
  3016. )}
  3017. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3018. {/* Header */}
  3019. <div className={getSpacing()}>
  3020. {/* Top row: Image, Name, Menu */}
  3021. <div className="flex items-start justify-between gap-2">
  3022. <div className="flex items-center gap-3 min-w-0 flex-1">
  3023. {/* Printer Model Image */}
  3024. <img
  3025. src={getPrinterImage(printer.model)}
  3026. alt={printer.model || t('common.printer')}
  3027. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3028. />
  3029. <div className="min-w-0 flex-1">
  3030. <div className="flex items-center justify-between gap-2">
  3031. <div className="flex min-w-0 items-center gap-2">
  3032. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3033. {/* Connection indicator dot for compact mode */}
  3034. {viewMode === 'compact' && (() => {
  3035. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3036. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3037. const hasWarning = hmsErrors.length > 0;
  3038. const pipColor = !status?.connected
  3039. ? 'bg-status-error'
  3040. : hasSevere
  3041. ? 'bg-status-error'
  3042. : hasWarning
  3043. ? 'bg-status-warning'
  3044. : 'bg-status-ok';
  3045. const pipTitle = !status?.connected
  3046. ? t('printers.connection.offline')
  3047. : hasWarning
  3048. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3049. : t('printers.connection.connected');
  3050. return (
  3051. <div
  3052. className={`w-2 h-2 rounded-full flex-shrink-0 ${pipColor}`}
  3053. title={pipTitle}
  3054. />
  3055. );
  3056. })()}
  3057. </div>
  3058. {viewMode === 'compact' && showClearPlateButton && (
  3059. <button
  3060. type="button"
  3061. onClick={() => clearPlateMutation.mutate()}
  3062. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3063. aria-label={t('printers.plateStatus.markCleared')}
  3064. 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"
  3065. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3066. >
  3067. {clearPlateMutation.isPending ? (
  3068. <Loader2 className="w-3 h-3 animate-spin" />
  3069. ) : (
  3070. <PlateClearedIcon className="w-3 h-3" />
  3071. )}
  3072. </button>
  3073. )}
  3074. </div>
  3075. <p className="text-sm text-bambu-gray">
  3076. {printer.model || 'Unknown Model'}
  3077. {/* Nozzle Info - only in expanded */}
  3078. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3079. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3080. • {status.nozzles[0].nozzle_diameter}mm
  3081. </span>
  3082. )}
  3083. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3084. <span className="ml-2 text-bambu-gray">
  3085. <Clock className="w-3 h-3 inline-block mr-1" />
  3086. {Math.round(maintenanceInfo.total_print_hours)}h
  3087. </span>
  3088. )}
  3089. </p>
  3090. </div>
  3091. </div>
  3092. </div>
  3093. {/* Badges row - only in expanded mode */}
  3094. {viewMode === 'expanded' && (
  3095. <div className="mt-2">
  3096. <div className="flex flex-wrap items-center gap-2">
  3097. {/* Connection status badge (or Maintenance pill when out of service).
  3098. Defensive: only swap when is_active is EXPLICITLY false. An
  3099. undefined / missing field defaults to "active" so the regular
  3100. pill renders — matches the backend default and prevents test
  3101. fixtures (or stale clients) from accidentally tripping the
  3102. maintenance UI. */}
  3103. {printer.is_active === false ? (
  3104. <span
  3105. 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"
  3106. title={t('printers.maintenance.subtitle')}
  3107. >
  3108. <Wrench className="w-3 h-3" />
  3109. {t('printers.maintenance.pillLabel')}
  3110. </span>
  3111. ) : (
  3112. <span
  3113. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3114. status?.connected
  3115. ? 'bg-status-ok/20 text-status-ok'
  3116. : 'bg-status-error/20 text-status-error'
  3117. }`}
  3118. >
  3119. {status?.connected ? (
  3120. <Link className="w-3 h-3" />
  3121. ) : (
  3122. <Unlink className="w-3 h-3" />
  3123. )}
  3124. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3125. </span>
  3126. )}
  3127. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3128. {printer.is_active !== false && !status?.connected && (
  3129. <button
  3130. onClick={() => setShowDiagnostic(true)}
  3131. 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"
  3132. title={t('diagnostic.runButton')}
  3133. >
  3134. <Stethoscope className="w-3 h-3" />
  3135. {t('diagnostic.runButton')}
  3136. </button>
  3137. )}
  3138. {/* Network connection indicator */}
  3139. {status?.connected && status?.wired_network && (
  3140. <span
  3141. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3142. title={t('printers.connection.ethernet', 'Ethernet')}
  3143. >
  3144. <Cable className="w-3 h-3" />
  3145. {t('printers.connection.ethernet', 'Ethernet')}
  3146. </span>
  3147. )}
  3148. {/* WiFi signal indicator */}
  3149. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3150. <span
  3151. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3152. wifiSignal >= -50
  3153. ? 'bg-status-ok/20 text-status-ok'
  3154. : wifiSignal >= -60
  3155. ? 'bg-status-ok/20 text-status-ok'
  3156. : wifiSignal >= -70
  3157. ? 'bg-status-warning/20 text-status-warning'
  3158. : wifiSignal >= -80
  3159. ? 'bg-orange-500/20 text-orange-600'
  3160. : 'bg-status-error/20 text-status-error'
  3161. }`}
  3162. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3163. >
  3164. <Signal className="w-3 h-3" />
  3165. {wifiSignal}dBm
  3166. </span>
  3167. )}
  3168. {/* HMS Status Indicator */}
  3169. {status?.connected && (() => {
  3170. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3171. return (
  3172. <button
  3173. onClick={() => setShowHMSModal(true)}
  3174. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3175. knownErrors.length > 0
  3176. ? knownErrors.some(e => e.severity <= 2)
  3177. ? 'bg-status-error/20 text-status-error'
  3178. : 'bg-status-warning/20 text-status-warning'
  3179. : 'bg-status-ok/20 text-status-ok'
  3180. }`}
  3181. title={t('printers.clickToViewHmsErrors')}
  3182. >
  3183. <AlertTriangle className="w-3 h-3" />
  3184. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3185. </button>
  3186. );
  3187. })()}
  3188. {/* Maintenance Status Indicator */}
  3189. {maintenanceInfo && (
  3190. <button
  3191. onClick={() => navigate('/maintenance')}
  3192. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3193. maintenanceInfo.due_count > 0
  3194. ? 'bg-status-error/20 text-status-error'
  3195. : maintenanceInfo.warning_count > 0
  3196. ? 'bg-status-warning/20 text-status-warning'
  3197. : 'bg-status-ok/20 text-status-ok'
  3198. }`}
  3199. title={
  3200. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3201. ? `${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`
  3202. : t('printers.maintenanceUpToDate')
  3203. }
  3204. >
  3205. <Wrench className="w-3 h-3" />
  3206. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3207. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3208. : 'OK'}
  3209. </button>
  3210. )}
  3211. {/* Queue Count Badge */}
  3212. {queueCount > 0 && (
  3213. <button
  3214. onClick={() => navigate('/queue')}
  3215. 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"
  3216. title={t('printers.queue.inQueue', { count: queueCount })}
  3217. >
  3218. <Layers className="w-3 h-3" />
  3219. {queueCount}
  3220. </button>
  3221. )}
  3222. {/* Firmware Version Badge */}
  3223. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3224. <button
  3225. onClick={() => setShowFirmwareModal(true)}
  3226. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3227. firmwareInfo.update_available
  3228. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3229. : 'bg-status-ok/20 text-status-ok'
  3230. }`}
  3231. title={
  3232. firmwareInfo.update_available
  3233. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3234. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3235. }
  3236. >
  3237. {firmwareInfo.update_available ? <Download className="w-3 h-3" /> : <CheckCircle className="w-3 h-3" />}
  3238. {firmwareInfo.current_version}
  3239. </button>
  3240. ) : status?.firmware_version ? (
  3241. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3242. {status.firmware_version}
  3243. </span>
  3244. ) : null}
  3245. {/* Enclosure Door Badge — models with an actual door sensor.
  3246. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3247. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3248. <span
  3249. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3250. status.door_open
  3251. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3252. : 'bg-status-ok/20 text-status-ok'
  3253. }`}
  3254. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3255. >
  3256. {status.door_open ? <DoorOpen className="w-3 h-3" /> : <DoorClosed className="w-3 h-3" />}
  3257. </span>
  3258. )}
  3259. </div>
  3260. </div>
  3261. )}
  3262. </div>
  3263. {/* Delete Confirmation */}
  3264. {showDeleteConfirm && (
  3265. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3266. <Card className="w-full max-w-md mx-4">
  3267. <CardContent>
  3268. <div className="flex items-start gap-3 mb-4">
  3269. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3270. <AlertTriangle className="w-5 h-5 text-red-600 dark:text-red-400" />
  3271. </div>
  3272. <div>
  3273. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3274. <p className="text-sm text-bambu-gray mt-1">
  3275. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3276. </p>
  3277. </div>
  3278. </div>
  3279. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3280. <label className="flex items-start gap-3 cursor-pointer">
  3281. <input
  3282. type="checkbox"
  3283. checked={deleteArchives}
  3284. onChange={(e) => setDeleteArchives(e.target.checked)}
  3285. className="mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  3286. />
  3287. <div>
  3288. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3289. <p className="text-xs text-bambu-gray mt-0.5">
  3290. {deleteArchives
  3291. ? t('printers.confirm.deleteArchivesNote')
  3292. : t('printers.confirm.keepArchivesNote')}
  3293. </p>
  3294. </div>
  3295. </label>
  3296. </div>
  3297. <div className="flex justify-end gap-2">
  3298. <Button
  3299. variant="secondary"
  3300. onClick={() => {
  3301. setShowDeleteConfirm(false);
  3302. setDeleteArchives(true);
  3303. }}
  3304. >
  3305. {t('common.cancel')}
  3306. </Button>
  3307. <Button
  3308. variant="danger"
  3309. onClick={() => {
  3310. deleteMutation.mutate({ deleteArchives });
  3311. setShowDeleteConfirm(false);
  3312. setDeleteArchives(true);
  3313. }}
  3314. >
  3315. Delete
  3316. </Button>
  3317. </div>
  3318. </CardContent>
  3319. </Card>
  3320. </div>
  3321. )}
  3322. {/* Status — see the equivalent defensive `=== false` check on the
  3323. header pill above for why this is not `!printer.is_active`. */}
  3324. {printer.is_active === false ? (
  3325. // Maintenance mode (#1476) — replaces the cover/progress container
  3326. // so the card keeps the same height. Renders for both compact and
  3327. // expanded view modes so the printer stays visible but plainly
  3328. // out-of-service.
  3329. <>
  3330. {viewMode === 'compact' ? (
  3331. <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">
  3332. <Wrench className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  3333. <span className="text-[11px] text-amber-700 dark:text-amber-400 font-medium truncate">
  3334. {t('printers.maintenance.pillLabel')}
  3335. </span>
  3336. </div>
  3337. ) : (
  3338. <>
  3339. <div className="flex items-center gap-2 mb-2">
  3340. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3341. {t('printers.status.title', 'Status')}
  3342. </span>
  3343. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3344. </div>
  3345. <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">
  3346. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  3347. <div className="flex-1 min-w-0">
  3348. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  3349. {t('printers.maintenance.title')}
  3350. </p>
  3351. <p className="text-xs text-bambu-gray mt-0.5">
  3352. {t('printers.maintenance.subtitle')}
  3353. </p>
  3354. </div>
  3355. <Button
  3356. variant="secondary"
  3357. size="sm"
  3358. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3359. onClick={() => maintenanceMutation.mutate(true)}
  3360. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3361. >
  3362. {t('printers.maintenance.exitButton')}
  3363. </Button>
  3364. </div>
  3365. </>
  3366. )}
  3367. </>
  3368. ) : status?.connected && (
  3369. <>
  3370. {/* Compact: Simple status bar */}
  3371. {viewMode === 'compact' ? (
  3372. (() => {
  3373. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3374. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3375. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3376. ? Math.max(0, Math.min(100, status.progress || 0))
  3377. : showClearPlateButton
  3378. ? 100
  3379. : hasProblem
  3380. ? 100
  3381. : 0;
  3382. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3383. const compactProgressClass = hasProblem
  3384. ? 'bg-status-error'
  3385. : status.state === 'PAUSE'
  3386. ? 'bg-status-warning'
  3387. : 'bg-bambu-green';
  3388. return (
  3389. <div className="relative mt-2 flex items-center gap-2">
  3390. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3391. <div
  3392. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3393. style={{ width: `${compactProgress}%` }}
  3394. />
  3395. </div>
  3396. <span className={`w-9 shrink-0 text-right text-[11px] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3397. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3398. </span>
  3399. </div>
  3400. );
  3401. })()
  3402. ) : (
  3403. /* Expanded: Full status section */
  3404. <>
  3405. <div className="flex items-center gap-2 mb-2">
  3406. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3407. {t('printers.status.title', 'Status')}
  3408. </span>
  3409. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3410. </div>
  3411. {/* Current Print or Idle Placeholder */}
  3412. {(() => {
  3413. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3414. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3415. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3416. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3417. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3418. return (
  3419. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3420. <button
  3421. onClick={() => setShowSkipObjectsModal(true)}
  3422. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3423. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3424. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3425. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3426. : 'text-bambu-gray/30 cursor-not-allowed'
  3427. }`}
  3428. title={
  3429. !hasPermission('printers:control')
  3430. ? t('printers.permission.noControl')
  3431. : !isActivePrint
  3432. ? t('printers.skipObjects.onlyWhilePrinting')
  3433. : (status.printable_objects_count ?? 0) >= 2
  3434. ? t('printers.skipObjects.tooltip')
  3435. : t('printers.skipObjects.requiresMultiple')
  3436. }
  3437. >
  3438. <SkipObjectsIcon className="w-4 h-4" />
  3439. {objectsData && objectsData.skipped_count > 0 && (
  3440. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full">
  3441. {objectsData.skipped_count}
  3442. </span>
  3443. )}
  3444. </button>
  3445. <div className="flex items-stretch gap-2">
  3446. <CoverImage
  3447. url={coverUrl}
  3448. printName={printName || undefined}
  3449. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  3450. />
  3451. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  3452. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  3453. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  3454. {plateStatusPill}
  3455. </div>
  3456. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  3457. {printName || t('printers.noActiveJob', 'No active job')}
  3458. </p>
  3459. <div className="flex h-3 items-center gap-2 text-sm">
  3460. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  3461. <div
  3462. 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`}
  3463. style={{ width: `${progress}%` }}
  3464. />
  3465. </div>
  3466. <span className={`w-9 shrink-0 pr-1 text-right text-[11px] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  3467. </div>
  3468. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  3469. {isActivePrint ? (
  3470. <>
  3471. {status.remaining_time != null && status.remaining_time > 0 && (
  3472. <>
  3473. <span className="flex items-center gap-1">
  3474. <Clock className="w-3 h-3" />
  3475. {formatDuration(status.remaining_time * 60)}
  3476. </span>
  3477. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  3478. ETA {formatETA(status.remaining_time, timeFormat, t)}
  3479. </span>
  3480. </>
  3481. )}
  3482. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  3483. <span className="flex items-center gap-1">
  3484. <Layers className="w-3 h-3" />
  3485. {status.layer_num}/{status.total_layers}
  3486. </span>
  3487. )}
  3488. {currentPrintUser && (
  3489. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  3490. <User className="w-3 h-3" />
  3491. {currentPrintUser}
  3492. </span>
  3493. )}
  3494. </>
  3495. ) : lastPrint ? (
  3496. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  3497. Last: {lastPrint.print_name || lastPrint.filename}
  3498. {lastPrint.completed_at && (
  3499. <span className="ml-1 text-bambu-gray/60">
  3500. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  3501. </span>
  3502. )}
  3503. </p>
  3504. ) : (
  3505. <span>{t('printers.readyToPrint')}</span>
  3506. )}
  3507. </div>
  3508. </div>
  3509. </div>
  3510. <PrinterQueueWidget
  3511. printerId={printer.id}
  3512. printerModel={printer.model}
  3513. loadedFilamentTypes={loadedFilamentTypes}
  3514. loadedFilaments={loadedFilaments}
  3515. variant="panelExtension"
  3516. />
  3517. </div>
  3518. );
  3519. })()}
  3520. </>
  3521. )}
  3522. {/* Temperatures */}
  3523. {status.temperatures && viewMode === 'expanded' && (() => {
  3524. // Use actual heater states from MQTT stream
  3525. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  3526. const bedHeating = status.temperatures.bed_heating || false;
  3527. const chamberHeating = status.temperatures.chamber_heating || false;
  3528. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  3529. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  3530. const kinds: HeaterSensorKind[] = ['nozzle'];
  3531. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  3532. kinds.push('bed');
  3533. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  3534. return kinds;
  3535. })();
  3536. // active_extruder: 0=right, 1=left
  3537. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  3538. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  3539. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  3540. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  3541. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  3542. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  3543. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  3544. const canUseStatusControls = status.connected && hasPermission('printers:control');
  3545. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  3546. 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 ${
  3547. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3548. }`;
  3549. // Chamber fan only exists on enclosed Bambu models. Open-frame
  3550. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  3551. // the widget there is at best dead UI and at worst suggests a
  3552. // control that does nothing. Mirrors the enclosure-door badge
  3553. // gate above.
  3554. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  3555. const fanItems = [
  3556. {
  3557. key: 'part',
  3558. label: t('printers.fans.partCooling'),
  3559. value: status.cooling_fan_speed ?? 0,
  3560. Icon: Fan,
  3561. activeClass: 'text-cyan-600 dark:text-cyan-400',
  3562. },
  3563. {
  3564. key: 'aux',
  3565. label: t('printers.fans.auxiliary'),
  3566. value: status.big_fan1_speed ?? 0,
  3567. Icon: Wind,
  3568. activeClass: 'text-blue-600 dark:text-blue-400',
  3569. },
  3570. ...(hasChamberFan
  3571. ? [
  3572. {
  3573. key: 'chamber',
  3574. label: t('printers.fans.chamber'),
  3575. value: status.big_fan2_speed ?? 0,
  3576. Icon: AirVent,
  3577. activeClass: 'text-green-600 dark:text-green-400',
  3578. },
  3579. ]
  3580. : []),
  3581. ];
  3582. return (
  3583. <>
  3584. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  3585. {/* Nozzle temp - combined for dual nozzle */}
  3586. <div
  3587. className={statusControlClass}
  3588. title={statusControlTitle}
  3589. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  3590. >
  3591. <button
  3592. type="button"
  3593. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3594. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3595. onClick={(e) => {
  3596. e.stopPropagation();
  3597. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  3598. }}
  3599. >
  3600. <LineChartIcon className="w-2.5 h-2.5" />
  3601. </button>
  3602. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  3603. {status.temperatures.nozzle_2 !== undefined ? (
  3604. <>
  3605. <p className="text-[9px] text-bambu-gray">L / R</p>
  3606. <p className="text-[11px] text-white">
  3607. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  3608. </p>
  3609. </>
  3610. ) : singleNozzleSlot ? (
  3611. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  3612. <div className="cursor-default">
  3613. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3614. <p className="text-[11px] text-white">
  3615. {Math.round(status.temperatures.nozzle || 0)}°C
  3616. </p>
  3617. </div>
  3618. </NozzleSlotHoverCard>
  3619. ) : (
  3620. <>
  3621. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3622. <p className="text-[11px] text-white">
  3623. {Math.round(status.temperatures.nozzle || 0)}°C
  3624. </p>
  3625. </>
  3626. )}
  3627. {statusControlMenu === 'nozzle-temp' && (
  3628. isDualNozzle ? (
  3629. <IndicatorControlPopover
  3630. title="Set Nozzle Temperatures"
  3631. widthClass="w-[300px]"
  3632. popoverWidth={300}
  3633. popoverHeight={260}
  3634. isPending={nozzleTemperatureMutation.isPending}
  3635. onClose={() => setStatusControlMenu(null)}
  3636. >
  3637. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  3638. <NozzleTemperatureControlBox
  3639. label="Left Temp"
  3640. current={status.temperatures.nozzle}
  3641. target={status.temperatures.nozzle_target}
  3642. isActive={activeNozzle === 'L'}
  3643. isPending={nozzleTemperatureMutation.isPending}
  3644. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  3645. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3646. />
  3647. <NozzleTemperatureControlBox
  3648. label="Right Temp"
  3649. current={status.temperatures.nozzle_2}
  3650. target={status.temperatures.nozzle_2_target}
  3651. isActive={activeNozzle === 'R'}
  3652. isPending={nozzleTemperatureMutation.isPending}
  3653. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  3654. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3655. />
  3656. </div>
  3657. </IndicatorControlPopover>
  3658. ) : (
  3659. <IndicatorControlPopover
  3660. title="Set Nozzle Temperature"
  3661. unit="°C"
  3662. customMin={0}
  3663. customMax={320}
  3664. isPending={nozzleTemperatureMutation.isPending}
  3665. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3666. onClose={() => setStatusControlMenu(null)}
  3667. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  3668. />
  3669. )
  3670. )}
  3671. </div>
  3672. <div
  3673. className={statusControlClass}
  3674. title={statusControlTitle}
  3675. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  3676. >
  3677. <button
  3678. type="button"
  3679. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3680. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3681. onClick={(e) => {
  3682. e.stopPropagation();
  3683. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  3684. }}
  3685. >
  3686. <LineChartIcon className="w-2.5 h-2.5" />
  3687. </button>
  3688. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  3689. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  3690. <p className="text-[11px] text-white">
  3691. {Math.round(status.temperatures.bed || 0)}°C
  3692. </p>
  3693. {statusControlMenu === 'bed-temp' && (
  3694. <IndicatorControlPopover
  3695. title="Set Bed Temperature"
  3696. unit="°C"
  3697. customMin={0}
  3698. customMax={140}
  3699. isPending={bedTemperatureMutation.isPending}
  3700. options={buildPresetOptions(bedTempPresets, 'C')}
  3701. onClose={() => setStatusControlMenu(null)}
  3702. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  3703. />
  3704. )}
  3705. </div>
  3706. {status.temperatures.chamber !== undefined && (() => {
  3707. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  3708. // but can't act on M141, so we keep the card read-only there.
  3709. const hasChamberHeater = status.supports_chamber_heater === true;
  3710. return (
  3711. <div
  3712. className={hasChamberHeater
  3713. ? statusControlClass
  3714. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  3715. title={hasChamberHeater ? statusControlTitle : undefined}
  3716. onClick={hasChamberHeater
  3717. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  3718. : undefined}
  3719. >
  3720. <button
  3721. type="button"
  3722. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3723. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3724. onClick={(e) => {
  3725. e.stopPropagation();
  3726. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  3727. }}
  3728. >
  3729. <LineChartIcon className="w-2.5 h-2.5" />
  3730. </button>
  3731. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  3732. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  3733. <p className="text-[11px] text-white">
  3734. {Math.round(status.temperatures.chamber || 0)}°C
  3735. </p>
  3736. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  3737. <IndicatorControlPopover
  3738. title="Set Chamber Temperature"
  3739. unit="°C"
  3740. customMin={0}
  3741. customMax={60}
  3742. isPending={chamberTemperatureMutation.isPending}
  3743. options={buildPresetOptions(chamberTempPresets, 'C')}
  3744. onClose={() => setStatusControlMenu(null)}
  3745. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  3746. />
  3747. )}
  3748. </div>
  3749. );
  3750. })()}
  3751. {/* Active nozzle indicator for dual-nozzle printers */}
  3752. {isDualNozzle && (
  3753. <DualNozzleHoverCard
  3754. leftSlot={leftNozzleSlot}
  3755. rightSlot={rightNozzleSlot}
  3756. activeNozzle={activeNozzle}
  3757. filamentInfo={filamentInfo}
  3758. >
  3759. <div
  3760. 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 ${
  3761. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3762. }`}
  3763. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  3764. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  3765. >
  3766. <NozzleIcon className="w-3.5 h-3.5 mb-0.5 text-amber-600 dark:text-amber-400" />
  3767. <div className="flex items-center gap-2">
  3768. <span className={`text-[11px] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3769. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  3770. </span>
  3771. <span className="text-[9px] text-bambu-gray/40">·</span>
  3772. <span className={`text-[11px] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3773. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  3774. </span>
  3775. </div>
  3776. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3777. {statusControlMenu === 'nozzle-select' && (
  3778. <IndicatorControlPopover
  3779. title="Set Nozzle Selection"
  3780. widthClass="w-[300px]"
  3781. popoverWidth={300}
  3782. popoverHeight={140}
  3783. isPending={selectExtruderMutation.isPending}
  3784. options={[
  3785. { label: 'Left', value: 1 },
  3786. { label: 'Right', value: 0 },
  3787. ]}
  3788. onClose={() => setStatusControlMenu(null)}
  3789. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  3790. />
  3791. )}
  3792. </div>
  3793. </DualNozzleHoverCard>
  3794. )}
  3795. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  3796. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  3797. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  3798. )}
  3799. </div>
  3800. <div className="mt-2 flex items-center gap-1.5">
  3801. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  3802. const active = value > 0;
  3803. return (
  3804. <div
  3805. key={key}
  3806. 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 ${
  3807. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3808. }`}
  3809. title={canUseStatusControls ? label : statusControlTitle}
  3810. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  3811. >
  3812. <Icon className={`w-3 h-3 shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  3813. <span className={`text-[10px] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  3814. {value}%
  3815. </span>
  3816. {statusControlMenu === `fan-${key}` && (
  3817. <IndicatorControlPopover
  3818. title={`Set ${label} Speed`}
  3819. unit="%"
  3820. customMin={0}
  3821. customMax={100}
  3822. isPending={fanSpeedMutation.isPending}
  3823. options={buildPresetOptions(fanSpeedPresets, '%')}
  3824. onClose={() => setStatusControlMenu(null)}
  3825. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'chamber', speed })}
  3826. />
  3827. )}
  3828. </div>
  3829. );
  3830. })}
  3831. </div>
  3832. </>
  3833. );
  3834. })()}
  3835. {viewMode === 'expanded' && showClearPlateButton && (
  3836. <button
  3837. type="button"
  3838. onClick={() => clearPlateMutation.mutate()}
  3839. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3840. 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"
  3841. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3842. >
  3843. {clearPlateMutation.isPending ? (
  3844. <Loader2 className="w-3 h-3 animate-spin" />
  3845. ) : (
  3846. <PlateClearedIcon className="w-4 h-4" />
  3847. )}
  3848. {t('printers.plateStatus.markCleared')}
  3849. </button>
  3850. )}
  3851. {/* Controls */}
  3852. {viewMode === 'expanded' && (() => {
  3853. // Determine print state for control buttons
  3854. const isRunning = status.state === 'RUNNING';
  3855. const isPaused = status.state === 'PAUSE';
  3856. const isPrinting = isRunning || isPaused;
  3857. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  3858. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  3859. 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';
  3860. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  3861. return (
  3862. <div className="mt-3">
  3863. {/* Section Header */}
  3864. <div className="flex items-center gap-2 mb-2">
  3865. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3866. {t('printers.controls')}
  3867. </span>
  3868. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3869. </div>
  3870. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  3871. {/* Left: Secondary controls */}
  3872. <div className="flex flex-wrap items-center gap-2 min-w-0">
  3873. <button
  3874. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  3875. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  3876. className={`${iconControlClass} ${
  3877. status.chamber_light
  3878. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  3879. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  3880. }`}
  3881. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  3882. >
  3883. <ChamberLight on={status.chamber_light ?? false} className="w-4 h-4" />
  3884. </button>
  3885. {/* Airduct Mode (P2S / X2D / H2*) */}
  3886. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  3887. const isHeating = status.airduct_mode === 1;
  3888. const Icon = isHeating ? Flame : Snowflake;
  3889. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  3890. 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';
  3891. return (
  3892. <div className="relative">
  3893. <button
  3894. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  3895. disabled={!hasPermission('printers:control')}
  3896. className={`${iconControlClass} ${bg}`}
  3897. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  3898. >
  3899. <Icon className={`w-4 h-4 ${color}`} />
  3900. </button>
  3901. {showAirductMenu === printer.id && (
  3902. <>
  3903. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  3904. <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]">
  3905. {([
  3906. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  3907. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  3908. ] as const).map(({ mode, label, modeId }) => (
  3909. <button
  3910. key={mode}
  3911. onClick={() => {
  3912. airductMutation.mutate(mode);
  3913. setShowAirductMenu(null);
  3914. }}
  3915. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  3916. status.airduct_mode === modeId
  3917. ? 'text-bambu-green bg-bambu-green/10'
  3918. : 'text-white hover:bg-bambu-dark-tertiary'
  3919. }`}
  3920. >
  3921. {mode === 'heating' ? <Flame className="w-3 h-3" /> : <Snowflake className="w-3 h-3" />}
  3922. {label}
  3923. </button>
  3924. ))}
  3925. </div>
  3926. </>
  3927. )}
  3928. </div>
  3929. );
  3930. })()}
  3931. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  3932. {(() => {
  3933. const canControl = hasPermission('printers:control');
  3934. const disabled = isPrinting || !canControl;
  3935. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  3936. 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';
  3937. const requestZJog = (direction: 1 | -1) => {
  3938. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  3939. // The jog never disables the soft endstops (#2579), so it's always
  3940. // safe: the firmware clamps the move at the travel limit, or refuses
  3941. // it if the printer isn't homed. No not-homed bypass to gate.
  3942. bedJogMutation.mutate({ distance: signed });
  3943. };
  3944. const requestXyJog = (x: number, y: number) => {
  3945. xyJogMutation.mutate({ x, y });
  3946. };
  3947. const requestExtruderJog = (distance: number) => {
  3948. extruderJogMutation.mutate(distance);
  3949. };
  3950. return (
  3951. <div className="relative">
  3952. <button
  3953. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  3954. disabled={disabled}
  3955. className={`${iconControlClass} ${
  3956. disabled
  3957. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  3958. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  3959. }`}
  3960. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  3961. >
  3962. <Move className="w-4 h-4" />
  3963. </button>
  3964. {showBedJogMenu === printer.id && (
  3965. <>
  3966. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  3967. <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">
  3968. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  3969. {t('printers.bedJog.title')}
  3970. </div>
  3971. <div className="h-px bg-bambu-dark-tertiary" />
  3972. {/* #2579: Bambu firmware does not enforce soft endstops on
  3973. G-code sent over MQTT, so manual moves can drive past the
  3974. travel limits and cause a collision. Not fixable from our
  3975. side — warn prominently. */}
  3976. <div className="flex items-start gap-1.5 bg-yellow-500/10 px-3 py-2 text-[11px] leading-snug text-yellow-700 dark:text-yellow-400">
  3977. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  3978. <span>{t('printers.bedJog.limitWarning')}</span>
  3979. </div>
  3980. <div className="h-px bg-bambu-dark-tertiary" />
  3981. <div className="flex justify-center px-3 py-2.5">
  3982. <div className="flex items-center justify-center gap-3">
  3983. <div className="grid grid-cols-3 gap-1">
  3984. <div />
  3985. <button
  3986. onClick={() => requestXyJog(0, bedJogStep)}
  3987. disabled={xyJogMutation.isPending}
  3988. className={jogButtonClass}
  3989. aria-label="Move Y forward"
  3990. >
  3991. <ArrowUp className="w-4 h-4" />
  3992. </button>
  3993. <div />
  3994. <button
  3995. onClick={() => requestXyJog(-bedJogStep, 0)}
  3996. disabled={xyJogMutation.isPending}
  3997. className={jogButtonClass}
  3998. aria-label="Move X left"
  3999. >
  4000. <ArrowLeft className="w-4 h-4" />
  4001. </button>
  4002. <button
  4003. onClick={() => {
  4004. setShowBedJogMenu(null);
  4005. homeAxesMutation.mutate('all');
  4006. }}
  4007. disabled={homeAxesMutation.isPending}
  4008. className={jogButtonClass}
  4009. aria-label={t('printers.bedJog.homeZ')}
  4010. >
  4011. <Home className="w-4 h-4" />
  4012. </button>
  4013. <button
  4014. onClick={() => requestXyJog(bedJogStep, 0)}
  4015. disabled={xyJogMutation.isPending}
  4016. className={jogButtonClass}
  4017. aria-label="Move X right"
  4018. >
  4019. <ArrowRight className="w-4 h-4" />
  4020. </button>
  4021. <div />
  4022. <button
  4023. onClick={() => requestXyJog(0, -bedJogStep)}
  4024. disabled={xyJogMutation.isPending}
  4025. className={jogButtonClass}
  4026. aria-label="Move Y back"
  4027. >
  4028. <ArrowDown className="w-4 h-4" />
  4029. </button>
  4030. <div />
  4031. </div>
  4032. <div className="flex flex-col items-center gap-1">
  4033. <button
  4034. onClick={() => requestZJog(-1)}
  4035. disabled={bedJogMutation.isPending}
  4036. className={jogButtonClass}
  4037. aria-label={t('printers.bedJog.up')}
  4038. >
  4039. <ArrowUp className="w-4 h-4" />
  4040. </button>
  4041. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4042. <Layers className="w-4 h-4" />
  4043. </div>
  4044. <button
  4045. onClick={() => requestZJog(1)}
  4046. disabled={bedJogMutation.isPending}
  4047. className={jogButtonClass}
  4048. aria-label={t('printers.bedJog.down')}
  4049. >
  4050. <ArrowDown className="w-4 h-4" />
  4051. </button>
  4052. </div>
  4053. <div className="flex flex-col items-center gap-1">
  4054. <button
  4055. onClick={() => requestExtruderJog(-bedJogStep)}
  4056. disabled={extruderJogMutation.isPending}
  4057. className={jogButtonClass}
  4058. aria-label="Retract filament"
  4059. >
  4060. <ArrowUp className="w-4 h-4" />
  4061. </button>
  4062. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4063. <span className="text-sm font-semibold leading-none">E</span>
  4064. </div>
  4065. <button
  4066. onClick={() => requestExtruderJog(bedJogStep)}
  4067. disabled={extruderJogMutation.isPending}
  4068. className={jogButtonClass}
  4069. aria-label="Extrude filament"
  4070. >
  4071. <ArrowDown className="w-4 h-4" />
  4072. </button>
  4073. </div>
  4074. </div>
  4075. </div>
  4076. <div className="h-px bg-bambu-dark-tertiary" />
  4077. <div className="px-3 pt-2.5 pb-3">
  4078. <div className="mb-1 text-[9px] uppercase tracking-wider text-bambu-gray/70">
  4079. {t('printers.bedJog.step')}
  4080. </div>
  4081. <div className="flex gap-1">
  4082. {[1, 10, 50].map((step) => (
  4083. <button
  4084. key={step}
  4085. onClick={() => setBedJogStep(step)}
  4086. className={`flex-1 px-1 py-1 rounded text-[10px] transition-colors ${
  4087. bedJogStep === step
  4088. ? 'bg-bambu-green/20 text-bambu-green'
  4089. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4090. }`}
  4091. >
  4092. {step}
  4093. </button>
  4094. ))}
  4095. </div>
  4096. </div>
  4097. </div>
  4098. </>
  4099. )}
  4100. </div>
  4101. );
  4102. })()}
  4103. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4104. <button
  4105. onClick={handleTogglePlateDetection}
  4106. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4107. className={`${iconControlClass} rounded-r-none ${
  4108. printer.plate_detection_enabled
  4109. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4110. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4111. }`}
  4112. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4113. >
  4114. {plateDetectionMutation.isPending ? (
  4115. <Loader2 className="w-4 h-4 animate-spin" />
  4116. ) : (
  4117. <ScanSearch className="w-4 h-4" />
  4118. )}
  4119. </button>
  4120. <button
  4121. onClick={handleOpenPlateManagement}
  4122. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4123. 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 ${
  4124. printer.plate_detection_enabled
  4125. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4126. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4127. }`}
  4128. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4129. >
  4130. {isCheckingPlate ? (
  4131. <Loader2 className="w-4 h-4 animate-spin" />
  4132. ) : (
  4133. <ChevronDown className="w-4 h-4" />
  4134. )}
  4135. </button>
  4136. </div>
  4137. {/* Print Speed */}
  4138. {(() => (
  4139. <div className="relative">
  4140. <button
  4141. data-testid="speed-control"
  4142. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4143. disabled={!isPrinting || !hasPermission('printers:control')}
  4144. className={`${iconControlClass} ${
  4145. isPrinting
  4146. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4147. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4148. }`}
  4149. title={isPrinting ? t('printers.speed.title') : undefined}
  4150. >
  4151. <Gauge className="w-4 h-4" />
  4152. </button>
  4153. {showSpeedMenu === printer.id && (
  4154. <>
  4155. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4156. <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]">
  4157. {([
  4158. { mode: 1, label: t('printers.speed.silent') },
  4159. { mode: 2, label: t('printers.speed.standard') },
  4160. { mode: 3, label: t('printers.speed.sport') },
  4161. { mode: 4, label: t('printers.speed.ludicrous') },
  4162. ] as const).map(({ mode, label }) => (
  4163. <button
  4164. key={mode}
  4165. onClick={() => {
  4166. printSpeedMutation.mutate(mode);
  4167. setShowSpeedMenu(null);
  4168. }}
  4169. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4170. status.speed_level === mode
  4171. ? 'text-bambu-green bg-bambu-green/10'
  4172. : 'text-white hover:bg-bambu-dark-tertiary'
  4173. }`}
  4174. >
  4175. {label}
  4176. </button>
  4177. ))}
  4178. </div>
  4179. </>
  4180. )}
  4181. </div>
  4182. ))()}
  4183. </div>
  4184. {/* Right: Print Control Buttons */}
  4185. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4186. {/* Pause/Resume button */}
  4187. {(() => {
  4188. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4189. return (
  4190. <button
  4191. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4192. disabled={pauseUnavailable}
  4193. className={`
  4194. ${printControlClass}
  4195. ${pauseUnavailable
  4196. ? unavailablePrintActionClass
  4197. : isPaused
  4198. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4199. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4200. }
  4201. `}
  4202. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4203. >
  4204. {isPaused ? <Play className="w-3 h-3" /> : <Pause className="w-3 h-3" />}
  4205. {isPaused ? t('printers.resume') : t('printers.pause')}
  4206. </button>
  4207. );
  4208. })()}
  4209. {/* Stop button */}
  4210. {(() => {
  4211. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4212. return (
  4213. <button
  4214. onClick={() => setShowStopConfirm(true)}
  4215. disabled={stopUnavailable}
  4216. className={`
  4217. ${printControlClass}
  4218. ${stopUnavailable
  4219. ? unavailablePrintActionClass
  4220. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4221. }
  4222. `}
  4223. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4224. >
  4225. <Square className="w-3 h-3" />
  4226. {t('printers.stop')}
  4227. </button>
  4228. );
  4229. })()}
  4230. </div>
  4231. </div>
  4232. </div>
  4233. );
  4234. })()}
  4235. {/* AMS Units - 2-Column Grid Layout */}
  4236. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4237. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4238. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4239. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4240. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4241. const filamentSlotClass = 'min-w-14';
  4242. // #1762 (comment 2): while a print is running/paused, overlay a small
  4243. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4244. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4245. // staged to a printer with mismatched filament: the wrong-slot pill
  4246. // is visible the instant printing starts.
  4247. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4248. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4249. ? status.ams_mapping
  4250. : [];
  4251. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4252. const boundedSlotCount = Math.max(1, slotCount);
  4253. const gapCount = Math.max(0, boundedSlotCount - 1);
  4254. const minWidth = `calc(${boundedSlotCount} * 3.5rem + ${gapCount} * 0.25rem + 1rem)`;
  4255. return {
  4256. flex: `1 1 ${minWidth}`,
  4257. minWidth,
  4258. };
  4259. };
  4260. return (
  4261. <div className="mt-3">
  4262. {/* Section Header */}
  4263. <div className="flex items-center gap-2 mb-2">
  4264. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  4265. {t('printers.filaments')}
  4266. </span>
  4267. <AmsBackupBadge
  4268. state={status.ams_filament_backup}
  4269. onClick={() => setAmsBackupModalOpen(true)}
  4270. />
  4271. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4272. </div>
  4273. {/* AMS Content */}
  4274. <div className="flex flex-wrap gap-2">
  4275. {/* Regular AMS units */}
  4276. {regularAms.map((ams) => {
  4277. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4278. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4279. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4280. const isLeftNozzle = extruderId === 1;
  4281. const isRightNozzle = extruderId === 0;
  4282. return (
  4283. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4284. {/* Header: Label + Stats (no icon) */}
  4285. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4286. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4287. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4288. <AmsNameHoverCard
  4289. ams={ams}
  4290. printerId={printer.id}
  4291. label={getAmsLabel(ams.id, ams.tray.length)}
  4292. amsLabels={amsLabels}
  4293. canEdit={hasPermission('printers:update')}
  4294. onSaved={refetchAmsLabels}
  4295. >
  4296. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4297. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4298. </span>
  4299. </AmsNameHoverCard>
  4300. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4301. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4302. )}
  4303. </div>
  4304. {(ams.humidity != null || ams.temp != null) && (
  4305. <div className="flex shrink-0 items-center gap-1.5">
  4306. {ams.humidity != null && (
  4307. <HumidityIndicator
  4308. humidity={ams.humidity}
  4309. goodThreshold={amsThresholds?.humidityGood}
  4310. fairThreshold={amsThresholds?.humidityFair}
  4311. onClick={() => setAmsHistoryModal({
  4312. amsId: ams.id,
  4313. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4314. mode: 'humidity',
  4315. })}
  4316. compact
  4317. />
  4318. )}
  4319. {ams.temp != null && (
  4320. <div className="mr-1">
  4321. <TemperatureIndicator
  4322. temp={ams.temp}
  4323. goodThreshold={amsThresholds?.tempGood}
  4324. fairThreshold={amsThresholds?.tempFair}
  4325. onClick={() => setAmsHistoryModal({
  4326. amsId: ams.id,
  4327. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4328. mode: 'temperature',
  4329. })}
  4330. compact
  4331. />
  4332. </div>
  4333. )}
  4334. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  4335. Screen-only models (P1 series) keep the control but can't
  4336. be commanded: it stays disabled and says why (#2533). */}
  4337. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4338. <button
  4339. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4340. onClick={(e) => {
  4341. if (ams.dry_time > 0) {
  4342. stopDryingMutation.mutate(ams.id);
  4343. } else if (dryingPopoverAmsId === ams.id) {
  4344. setDryingPopoverAmsId(null);
  4345. } else {
  4346. const firstTray = ams.tray.find(t => t.tray_type);
  4347. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4348. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4349. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4350. setDryingFilament(filType);
  4351. setDryingTemp(preset[moduleType] || preset.n3f);
  4352. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4353. setDryingRotateTray(false);
  4354. setDryingPopoverModuleType(ams.module_type);
  4355. setDryingPopoverAmsId(ams.id);
  4356. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4357. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4358. }
  4359. }}
  4360. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4361. ams.dry_time > 0
  4362. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4363. : status.drying_screen_only || ams.dry_sf_reason?.length
  4364. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4365. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4366. }`}
  4367. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t('printers.drying.powerRequired') : t('printers.drying.start')}
  4368. >
  4369. <Flame className="w-3 h-3" />
  4370. </button>
  4371. )}
  4372. </div>
  4373. )}
  4374. </div>
  4375. {/* Drying status bar */}
  4376. {ams.dry_time > 0 && (
  4377. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[9px]">
  4378. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  4379. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  4380. {ams.dry_filament && ams.dry_target_temp != null && (
  4381. <span className="text-amber-700/80 dark:text-amber-300/70">
  4382. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  4383. </span>
  4384. )}
  4385. <span className="text-amber-700/80 dark:text-amber-300/70">
  4386. {t('printers.drying.timeRemaining', {
  4387. time: ams.dry_time >= 60
  4388. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4389. : `${ams.dry_time}m`
  4390. })}
  4391. </span>
  4392. {/* A cycle on a screen-only model was started at the printer
  4393. and can only be stopped there (#2533). */}
  4394. {!status.drying_screen_only && (
  4395. <button
  4396. onClick={() => stopDryingMutation.mutate(ams.id)}
  4397. disabled={stopDryingMutation.isPending}
  4398. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  4399. title={t('printers.drying.stop')}
  4400. >
  4401. <X className="w-3 h-3" />
  4402. </button>
  4403. )}
  4404. </div>
  4405. )}
  4406. {/* Slots grid: 4 columns - always render 4 slots */}
  4407. <div className="grid w-full grid-cols-[repeat(4,minmax(3.5rem,1fr))] gap-1">
  4408. {[0, 1, 2, 3].map((slotIdx) => {
  4409. // Find tray data for this slot (may be undefined if data incomplete)
  4410. // Use array index if available, as tray.id may not always be set
  4411. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  4412. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4413. const isEmpty = !tray?.tray_type;
  4414. const emptyKind = getEmptySlotKind(tray);
  4415. // Check if this is the currently loaded tray
  4416. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  4417. const globalTrayId = ams.id * 4 + slotIdx;
  4418. const isActive = effectiveTrayNow === globalTrayId;
  4419. // Runout guidance (#2587): the slot the paused print now
  4420. // expects filament in, and the slot that ran out.
  4421. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  4422. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  4423. // Get cloud preset info if available
  4424. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4425. // Get saved slot preset mapping (for user-configured slots)
  4426. const slotPreset = slotPresets?.[globalTrayId];
  4427. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4428. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  4429. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  4430. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  4431. // Slot-assigned-only spool fill (no tag link required)
  4432. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4433. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  4434. : undefined;
  4435. const slotSpoolForFill = slotAssignmentForFill
  4436. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  4437. : undefined;
  4438. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  4439. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  4440. : null;
  4441. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4442. const inventoryFill = (() => {
  4443. const sp = inventoryAssignment?.spool;
  4444. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4445. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4446. }
  4447. return null;
  4448. })();
  4449. // If inventory says 0% but AMS reports positive remain, prefer AMS
  4450. // (inventory weight_used may be stale or over-counted — #676)
  4451. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4452. ? null : inventoryFill;
  4453. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4454. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  4455. : resolvedInventoryFill !== null ? 'inventory' as const
  4456. : hasFillLevel ? 'ams' as const
  4457. : undefined;
  4458. // Build filament data for hover card
  4459. const filamentData = tray?.tray_type ? {
  4460. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4461. // Spoolman spool name wins over cloud lookup so a slot bound to
  4462. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  4463. // Design PLA") instead of whatever the printer's filament_id
  4464. // resolves to in the cloud catalog (often "Generic PLA" for
  4465. // P-prefix local presets). Spoolman's filament.name is just the
  4466. // material+subtype ("PLA Basic"); prepend the spool's brand so
  4467. // the hover card shows "Devil Design PLA Basic" rather than the
  4468. // vendor-less form. Strip the "@<printer>..." suffix that
  4469. // BambuStudio appends to user-preset names.
  4470. profile: slotPreset?.preset_name || (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,
  4471. colorName: getColorName(tray.tray_color || ''),
  4472. colorHex: tray.tray_color || null,
  4473. kFactor: formatKValue(tray.k),
  4474. fillLevel: effectiveFill,
  4475. trayUuid: tray.tray_uuid || null,
  4476. tagUid: tray.tag_uid || null,
  4477. fillSource,
  4478. } : null;
  4479. // Check if this specific slot is being refreshed
  4480. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  4481. refreshingSlot?.slotId === slotIdx;
  4482. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  4483. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4484. const activePrintSlotLabel = activePrintSlotIdx >= 0
  4485. ? `P${activePrintSlotIdx + 1}`
  4486. : null;
  4487. // Slot visual content (goes inside hover card)
  4488. const slotVisual = (
  4489. <div
  4490. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  4491. isExpectedSlot
  4492. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  4493. : isRanOutSlot
  4494. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  4495. : isActive
  4496. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  4497. : ''
  4498. }`}
  4499. >
  4500. {isExpectedSlot && (
  4501. <span
  4502. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  4503. title={t('printers.expectedSlot.title')}
  4504. className="absolute top-0.5 left-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  4505. >
  4506. ↓
  4507. </span>
  4508. )}
  4509. {activePrintSlotLabel && (
  4510. <span
  4511. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  4512. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  4513. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4514. >
  4515. {activePrintSlotLabel}
  4516. </span>
  4517. )}
  4518. {/* Filament color circle with 1-based slot number centered inside */}
  4519. <FilamentSlotCircle
  4520. trayColor={tray?.tray_color}
  4521. trayType={tray?.tray_type}
  4522. isEmpty={isEmpty}
  4523. emptyKind={emptyKind}
  4524. slotNumber={slotIdx + 1}
  4525. />
  4526. <div className="text-[9px] text-white font-bold truncate">
  4527. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4528. </div>
  4529. {/* Fill bar */}
  4530. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4531. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  4532. <div
  4533. className="h-full rounded-full transition-all"
  4534. style={{
  4535. width: `${effectiveFill}%`,
  4536. backgroundColor: getFillBarColor(effectiveFill),
  4537. }}
  4538. />
  4539. )}
  4540. </div>
  4541. </div>
  4542. );
  4543. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  4544. return (
  4545. <div key={slotIdx} className={`relative group w-full ${filamentSlotClass}`}>
  4546. {/* Loading overlay during RFID re-read */}
  4547. {isRefreshing && (
  4548. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4549. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4550. </div>
  4551. )}
  4552. {/* Hover card wraps only the visual content */}
  4553. {filamentData ? (
  4554. <FilamentHoverCard
  4555. data={filamentData}
  4556. actions={renderAmsSlotActions({
  4557. amsId: ams.id,
  4558. slotId: slotIdx,
  4559. loadTrayId: ams.id * 4 + slotIdx,
  4560. isRefreshing,
  4561. })}
  4562. spoolman={{
  4563. enabled: spoolmanEnabled,
  4564. // #1457: slot assignment is the user's most explicit action — it must
  4565. // outrank the tag-link, which can be stale when a non-RFID slot's
  4566. // fallback tag is still attached to a previous spool in Spoolman.
  4567. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  4568. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  4569. spoolmanUrl,
  4570. syncMode: spoolmanSyncMode,
  4571. // Suppress Link button when slot is already occupied by ANY assignment
  4572. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  4573. // suppressed for Spoolman; the maintainer screenshot shows the badge
  4574. // still appearing on slots with a local Devil Design PLA assigned.
  4575. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  4576. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  4577. setLinkSpoolModal({
  4578. tagUid: filamentData.tagUid || linkTag,
  4579. trayUuid: filamentData.trayUuid || '',
  4580. printerId: printer.id,
  4581. amsId: ams.id,
  4582. trayId: slotIdx,
  4583. });
  4584. } : undefined,
  4585. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  4586. }}
  4587. inventory={(() => {
  4588. if (spoolmanEnabled) {
  4589. if (spoolmanLoading) return undefined;
  4590. const slotAssignment = slotAssignmentForFill;
  4591. const spoolmanSpool = slotSpoolForFill;
  4592. return {
  4593. assignedSpool: spoolmanSpool ? {
  4594. id: spoolmanSpool.id,
  4595. material: spoolmanSpool.material,
  4596. brand: spoolmanSpool.brand ?? null,
  4597. color_name: spoolmanSpool.color_name ?? null,
  4598. remainingWeightGrams: spoolmanSpool.label_weight
  4599. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4600. : undefined,
  4601. } : null,
  4602. onAssignSpool: () => setAssignSpoolModal({
  4603. printerId: printer.id,
  4604. amsId: ams.id,
  4605. trayId: slotIdx,
  4606. trayInfo: {
  4607. type: tray?.tray_type || filamentData.profile,
  4608. material: tray?.tray_type ?? undefined,
  4609. profile: filamentData.profile,
  4610. color: filamentData.colorHex || '',
  4611. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4612. },
  4613. }),
  4614. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4615. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4616. };
  4617. }
  4618. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4619. return {
  4620. assignedSpool: assignment?.spool ? {
  4621. id: assignment.spool.id,
  4622. material: assignment.spool.material,
  4623. brand: assignment.spool.brand,
  4624. color_name: assignment.spool.color_name,
  4625. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4626. } : null,
  4627. onAssignSpool: () => setAssignSpoolModal({
  4628. printerId: printer.id,
  4629. amsId: ams.id,
  4630. trayId: slotIdx,
  4631. trayInfo: {
  4632. type: tray?.tray_type || filamentData.profile,
  4633. material: tray?.tray_type ?? undefined,
  4634. profile: filamentData.profile,
  4635. color: filamentData.colorHex || '',
  4636. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4637. },
  4638. }),
  4639. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  4640. isAssigned: !!assignment || isBambuLabSpool(tray),
  4641. };
  4642. })()}
  4643. configureSlot={{
  4644. enabled: hasPermission('printers:control'),
  4645. onConfigure: () => setConfigureSlotModal({
  4646. amsId: ams.id,
  4647. trayId: slotIdx,
  4648. trayCount: ams.tray.length,
  4649. trayType: tray?.tray_type || undefined,
  4650. trayColor: tray?.tray_color || undefined,
  4651. traySubBrands: tray?.tray_sub_brands || undefined,
  4652. trayInfoIdx: tray?.tray_info_idx || undefined,
  4653. extruderId: mappedExtruderId,
  4654. caliIdx: tray?.cali_idx,
  4655. savedPresetId: slotPreset?.preset_id,
  4656. }),
  4657. }}
  4658. >
  4659. {slotVisual}
  4660. </FilamentHoverCard>
  4661. ) : (
  4662. <EmptySlotHoverCard
  4663. kind={emptyKind ?? undefined}
  4664. actions={renderAmsSlotActions({
  4665. amsId: ams.id,
  4666. slotId: slotIdx,
  4667. loadTrayId: ams.id * 4 + slotIdx,
  4668. isRefreshing,
  4669. })}
  4670. configureSlot={{
  4671. enabled: hasPermission('printers:control'),
  4672. onConfigure: () => setConfigureSlotModal({
  4673. amsId: ams.id,
  4674. trayId: slotIdx,
  4675. trayCount: ams.tray.length,
  4676. extruderId: mappedExtruderId,
  4677. }),
  4678. }}
  4679. onAssignSpool={() => setAssignSpoolModal({
  4680. printerId: printer.id,
  4681. amsId: ams.id,
  4682. trayId: slotIdx,
  4683. trayInfo: {
  4684. type: '',
  4685. material: undefined,
  4686. profile: '',
  4687. color: '',
  4688. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4689. },
  4690. })}
  4691. >
  4692. {slotVisual}
  4693. </EmptySlotHoverCard>
  4694. )}
  4695. </div>
  4696. );
  4697. })}
  4698. </div>
  4699. </div>
  4700. );
  4701. })}
  4702. {/* HT AMS units */}
  4703. {htAms.map((ams) => {
  4704. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4705. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4706. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4707. const isLeftNozzle = extruderId === 1;
  4708. const isRightNozzle = extruderId === 0;
  4709. const tray = ams.tray[0];
  4710. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4711. const isEmpty = !tray?.tray_type;
  4712. const emptyKind = getEmptySlotKind(tray);
  4713. // Check if this is the currently loaded tray
  4714. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  4715. const isActive = effectiveTrayNow === globalTrayId;
  4716. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  4717. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  4718. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  4719. // Get cloud preset info if available
  4720. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4721. // Get saved slot preset mapping (for user-configured slots)
  4722. const slotPreset = slotPresets?.[globalTrayId];
  4723. const htSlotId = tray?.id ?? 0;
  4724. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4725. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  4726. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  4727. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  4728. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4729. const htInventoryFill = (() => {
  4730. const sp = htInventoryAssignment?.spool;
  4731. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4732. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4733. }
  4734. return null;
  4735. })();
  4736. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  4737. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4738. ? null : htInventoryFill;
  4739. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  4740. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4741. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  4742. : undefined;
  4743. const htSlotSpoolForFill = htSlotAssignmentForFill
  4744. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  4745. : undefined;
  4746. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  4747. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  4748. : null;
  4749. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4750. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  4751. : htResolvedInventoryFill !== null ? 'inventory' as const
  4752. : hasFillLevel ? 'ams' as const
  4753. : undefined;
  4754. // Build filament data for hover card
  4755. const filamentData = tray?.tray_type ? {
  4756. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4757. profile: slotPreset?.preset_name || (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,
  4758. colorName: getColorName(tray.tray_color || ''),
  4759. colorHex: tray.tray_color || null,
  4760. kFactor: formatKValue(tray.k),
  4761. fillLevel: htEffectiveFill,
  4762. trayUuid: tray.tray_uuid || null,
  4763. tagUid: tray.tag_uid || null,
  4764. fillSource: htFillSource,
  4765. } : null;
  4766. // Check if this specific slot is being refreshed
  4767. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  4768. refreshingSlot?.slotId === htSlotId;
  4769. // #1762 (comment 2): active print-slot index for this HT slot.
  4770. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4771. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  4772. ? `P${htActivePrintSlotIdx + 1}`
  4773. : null;
  4774. // Slot visual content (goes inside hover card)
  4775. const slotVisual = (
  4776. <div
  4777. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  4778. isExpectedSlot
  4779. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  4780. : isRanOutSlot
  4781. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  4782. : isActive
  4783. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  4784. : ''
  4785. }`}
  4786. >
  4787. {isExpectedSlot && (
  4788. <span
  4789. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  4790. title={t('printers.expectedSlot.title')}
  4791. className="absolute top-0.5 left-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  4792. >
  4793. ↓
  4794. </span>
  4795. )}
  4796. {htActivePrintSlotLabel && (
  4797. <span
  4798. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  4799. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  4800. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4801. >
  4802. {htActivePrintSlotLabel}
  4803. </span>
  4804. )}
  4805. {/* Filament color circle with 1-based slot number centered inside */}
  4806. <FilamentSlotCircle
  4807. trayColor={tray?.tray_color}
  4808. trayType={tray?.tray_type}
  4809. isEmpty={isEmpty}
  4810. emptyKind={emptyKind}
  4811. slotNumber={1}
  4812. />
  4813. <div className="text-[9px] text-white font-bold truncate">
  4814. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4815. </div>
  4816. {/* Fill bar */}
  4817. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4818. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  4819. <div
  4820. className="h-full rounded-full transition-all"
  4821. style={{
  4822. width: `${htEffectiveFill}%`,
  4823. backgroundColor: getFillBarColor(htEffectiveFill),
  4824. }}
  4825. />
  4826. )}
  4827. </div>
  4828. </div>
  4829. );
  4830. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  4831. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  4832. // Without this override, the L view squishes HT into a sliver next to the
  4833. // 4-slot AMS neighbors.
  4834. const htCardStyle: React.CSSProperties = { flex: '1 1 11rem', minWidth: '11rem' };
  4835. return (
  4836. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4837. {/* Row 1: Label + Nozzle + Drying */}
  4838. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4839. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4840. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4841. <AmsNameHoverCard
  4842. ams={ams}
  4843. printerId={printer.id}
  4844. label={getAmsLabel(ams.id, ams.tray.length)}
  4845. amsLabels={amsLabels}
  4846. canEdit={hasPermission('printers:update')}
  4847. onSaved={refetchAmsLabels}
  4848. >
  4849. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4850. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4851. </span>
  4852. </AmsNameHoverCard>
  4853. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4854. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4855. )}
  4856. </div>
  4857. {/* Drying button for HT AMS */}
  4858. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4859. <div className="relative ml-auto">
  4860. <button
  4861. disabled={status.drying_screen_only}
  4862. onClick={(e) => {
  4863. if (ams.dry_time > 0) {
  4864. stopDryingMutation.mutate(ams.id);
  4865. } else if (dryingPopoverAmsId === ams.id) {
  4866. setDryingPopoverAmsId(null);
  4867. } else {
  4868. const firstTray = ams.tray.find(t => t.tray_type);
  4869. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4870. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4871. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4872. setDryingFilament(filType);
  4873. setDryingTemp(preset[moduleType] || preset.n3f);
  4874. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4875. setDryingRotateTray(false);
  4876. setDryingPopoverModuleType(ams.module_type);
  4877. setDryingPopoverAmsId(ams.id);
  4878. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4879. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4880. }
  4881. }}
  4882. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4883. ams.dry_time > 0
  4884. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4885. : status.drying_screen_only
  4886. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4887. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4888. }`}
  4889. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  4890. >
  4891. <Flame className="w-3 h-3" />
  4892. </button>
  4893. </div>
  4894. )}
  4895. </div>
  4896. {/* HT AMS drying status bar */}
  4897. {ams.dry_time > 0 && (
  4898. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[9px]">
  4899. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  4900. {ams.dry_filament && ams.dry_target_temp != null && (
  4901. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  4902. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  4903. </span>
  4904. )}
  4905. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  4906. {ams.dry_time >= 60
  4907. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4908. : `${ams.dry_time}m`}
  4909. </span>
  4910. {!status.drying_screen_only && (
  4911. <button
  4912. onClick={() => stopDryingMutation.mutate(ams.id)}
  4913. disabled={stopDryingMutation.isPending}
  4914. 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"
  4915. title={t('printers.drying.stop')}
  4916. >
  4917. <X className="w-3 h-3" />
  4918. </button>
  4919. )}
  4920. </div>
  4921. )}
  4922. {/* Row 2: Slot (left) + Stats (right stacked) */}
  4923. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  4924. {/* Slot wrapper with loading overlay */}
  4925. <div className="relative group min-w-14 flex-1">
  4926. {/* Loading overlay during RFID re-read */}
  4927. {isHtRefreshing && (
  4928. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4929. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4930. </div>
  4931. )}
  4932. {/* Hover card wraps only the visual content */}
  4933. {filamentData ? (
  4934. <FilamentHoverCard
  4935. data={filamentData}
  4936. actions={renderAmsSlotActions({
  4937. amsId: ams.id,
  4938. slotId: htSlotId,
  4939. loadTrayId: ams.id * 4 + htSlotId,
  4940. isRefreshing: isHtRefreshing,
  4941. })}
  4942. spoolman={{
  4943. enabled: spoolmanEnabled,
  4944. // #1457: slot assignment outranks tag-link (see top-level slot block).
  4945. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  4946. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  4947. spoolmanUrl,
  4948. syncMode: spoolmanSyncMode,
  4949. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  4950. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  4951. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  4952. setLinkSpoolModal({
  4953. tagUid: filamentData.tagUid || linkTag,
  4954. trayUuid: filamentData.trayUuid || '',
  4955. printerId: printer.id,
  4956. amsId: ams.id,
  4957. trayId: htSlotId,
  4958. });
  4959. } : undefined,
  4960. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  4961. }}
  4962. inventory={(() => {
  4963. if (spoolmanEnabled) {
  4964. if (spoolmanLoading) return undefined;
  4965. const slotAssignment = htSlotAssignmentForFill;
  4966. const spoolmanSpool = htSlotSpoolForFill;
  4967. return {
  4968. assignedSpool: spoolmanSpool ? {
  4969. id: spoolmanSpool.id,
  4970. material: spoolmanSpool.material,
  4971. brand: spoolmanSpool.brand ?? null,
  4972. color_name: spoolmanSpool.color_name ?? null,
  4973. remainingWeightGrams: spoolmanSpool.label_weight
  4974. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4975. : undefined,
  4976. } : null,
  4977. onAssignSpool: () => setAssignSpoolModal({
  4978. printerId: printer.id,
  4979. amsId: ams.id,
  4980. trayId: htSlotId,
  4981. trayInfo: {
  4982. type: tray?.tray_type || filamentData.profile,
  4983. material: tray?.tray_type ?? undefined,
  4984. profile: filamentData.profile,
  4985. color: filamentData.colorHex || '',
  4986. location: getAmsLabel(ams.id, ams.tray.length),
  4987. },
  4988. }),
  4989. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4990. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4991. };
  4992. }
  4993. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4994. return {
  4995. assignedSpool: assignment?.spool ? {
  4996. id: assignment.spool.id,
  4997. material: assignment.spool.material,
  4998. brand: assignment.spool.brand,
  4999. color_name: assignment.spool.color_name,
  5000. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5001. } : null,
  5002. onAssignSpool: () => setAssignSpoolModal({
  5003. printerId: printer.id,
  5004. amsId: ams.id,
  5005. trayId: htSlotId,
  5006. trayInfo: {
  5007. type: tray?.tray_type || filamentData.profile,
  5008. material: tray?.tray_type ?? undefined,
  5009. profile: filamentData.profile,
  5010. color: filamentData.colorHex || '',
  5011. location: getAmsLabel(ams.id, ams.tray.length),
  5012. },
  5013. }),
  5014. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5015. isAssigned: !!assignment || isBambuLabSpool(tray),
  5016. };
  5017. })()}
  5018. configureSlot={{
  5019. enabled: hasPermission('printers:control'),
  5020. onConfigure: () => setConfigureSlotModal({
  5021. amsId: ams.id,
  5022. trayId: htSlotId,
  5023. trayCount: ams.tray.length,
  5024. trayType: tray?.tray_type || undefined,
  5025. trayColor: tray?.tray_color || undefined,
  5026. traySubBrands: tray?.tray_sub_brands || undefined,
  5027. trayInfoIdx: tray?.tray_info_idx || undefined,
  5028. extruderId: mappedExtruderId,
  5029. caliIdx: tray?.cali_idx,
  5030. savedPresetId: slotPreset?.preset_id,
  5031. }),
  5032. }}
  5033. >
  5034. {slotVisual}
  5035. </FilamentHoverCard>
  5036. ) : (
  5037. <EmptySlotHoverCard
  5038. kind={emptyKind ?? undefined}
  5039. actions={renderAmsSlotActions({
  5040. amsId: ams.id,
  5041. slotId: htSlotId,
  5042. loadTrayId: ams.id * 4 + htSlotId,
  5043. isRefreshing: isHtRefreshing,
  5044. })}
  5045. configureSlot={{
  5046. enabled: hasPermission('printers:control'),
  5047. onConfigure: () => setConfigureSlotModal({
  5048. amsId: ams.id,
  5049. trayId: htSlotId,
  5050. trayCount: ams.tray.length,
  5051. extruderId: mappedExtruderId,
  5052. }),
  5053. }}
  5054. onAssignSpool={() => setAssignSpoolModal({
  5055. printerId: printer.id,
  5056. amsId: ams.id,
  5057. trayId: htSlotId,
  5058. trayInfo: {
  5059. type: '',
  5060. material: undefined,
  5061. profile: '',
  5062. color: '',
  5063. location: getAmsLabel(ams.id, ams.tray.length),
  5064. },
  5065. })}
  5066. >
  5067. {slotVisual}
  5068. </EmptySlotHoverCard>
  5069. )}
  5070. </div>
  5071. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5072. {(ams.humidity != null || ams.temp != null) && (
  5073. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5074. {ams.temp != null && (
  5075. <TemperatureIndicator
  5076. temp={ams.temp}
  5077. goodThreshold={amsThresholds?.tempGood}
  5078. fairThreshold={amsThresholds?.tempFair}
  5079. onClick={() => setAmsHistoryModal({
  5080. amsId: ams.id,
  5081. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5082. mode: 'temperature',
  5083. })}
  5084. compact
  5085. />
  5086. )}
  5087. {ams.humidity != null && (
  5088. <HumidityIndicator
  5089. humidity={ams.humidity}
  5090. goodThreshold={amsThresholds?.humidityGood}
  5091. fairThreshold={amsThresholds?.humidityFair}
  5092. onClick={() => setAmsHistoryModal({
  5093. amsId: ams.id,
  5094. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5095. mode: 'humidity',
  5096. })}
  5097. compact
  5098. />
  5099. )}
  5100. </div>
  5101. )}
  5102. </div>
  5103. </div>
  5104. );
  5105. })}
  5106. {/* External spool(s) - grouped in one card like regular AMS */}
  5107. {status.vt_tray.length > 0 && (
  5108. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5109. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5110. <span className="block min-w-0 flex-1 truncate text-[10px] text-white font-medium">{t('printers.external')}</span>
  5111. </div>
  5112. <div className={`grid w-full ${status.vt_tray.length > 1 ? 'grid-cols-[repeat(2,minmax(3.5rem,1fr))]' : 'grid-cols-[minmax(3.5rem,1fr)]'} gap-1`}>
  5113. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5114. const extTrayId = extTray.id ?? 254;
  5115. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5116. // generically — use active_extruder to determine L vs R:
  5117. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5118. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5119. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5120. (extTrayId === 255 && status.active_extruder === 0)
  5121. : effectiveTrayNow === extTrayId;
  5122. const slotTrayId = extTrayId - 254; // 0 or 1
  5123. const extLabel = isDualNozzle
  5124. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  5125. : '';
  5126. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5127. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5128. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5129. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5130. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5131. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5132. const extInventoryFill = (() => {
  5133. const sp = extInventoryAssignment?.spool;
  5134. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5135. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5136. }
  5137. return null;
  5138. })();
  5139. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5140. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5141. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5142. ? null : extInventoryFill;
  5143. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5144. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5145. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5146. : undefined;
  5147. const extSlotSpoolForFill = extSlotAssignmentForFill
  5148. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5149. : undefined;
  5150. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5151. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5152. : null;
  5153. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5154. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5155. : extResolvedInventoryFill !== null ? 'inventory' as const
  5156. : extHasFillLevel ? 'ams' as const
  5157. : undefined;
  5158. const extFilamentData = {
  5159. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5160. profile: extSlotPreset?.preset_name || (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',
  5161. colorName: getColorName(extTray.tray_color || ''),
  5162. colorHex: extTray.tray_color || null,
  5163. kFactor: formatKValue(extTray.k),
  5164. fillLevel: extEffectiveFill,
  5165. trayUuid: extTray.tray_uuid || null,
  5166. tagUid: extTray.tag_uid || null,
  5167. fillSource: extFillSource,
  5168. };
  5169. const isEmpty = !extTray.tray_type;
  5170. const emptyKind = getEmptySlotKind(extTray);
  5171. const extSlotContent = (
  5172. <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' : ''}`}>
  5173. {/* Color circle: L/R inside on dual-nozzle external (replaces
  5174. the separate Ext-L/Ext-R caption that made the row taller than
  5175. regular AMS slots), 1-based slot number on single-nozzle. */}
  5176. <FilamentSlotCircle
  5177. trayColor={extTray.tray_color}
  5178. trayType={extTray.tray_type}
  5179. isEmpty={isEmpty}
  5180. emptyKind={emptyKind}
  5181. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  5182. />
  5183. <div className={`text-[9px] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5184. {extTray.tray_type || t('ams.slotEmpty')}
  5185. </div>
  5186. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5187. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5188. <div
  5189. className="h-full rounded-full transition-all"
  5190. style={{
  5191. width: `${extEffectiveFill}%`,
  5192. backgroundColor: getFillBarColor(extEffectiveFill),
  5193. }}
  5194. />
  5195. )}
  5196. </div>
  5197. </div>
  5198. );
  5199. return (
  5200. <div key={extTrayId} className={`relative group w-full ${filamentSlotClass}`}>
  5201. {!isEmpty ? (
  5202. <FilamentHoverCard
  5203. data={extFilamentData}
  5204. actions={renderAmsSlotActions({
  5205. amsId: 255,
  5206. slotId: slotTrayId,
  5207. loadTrayId: extTrayId,
  5208. includeRfid: false,
  5209. })}
  5210. spoolman={{
  5211. enabled: spoolmanEnabled,
  5212. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5213. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5214. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5215. spoolmanUrl,
  5216. syncMode: spoolmanSyncMode,
  5217. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5218. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5219. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5220. setLinkSpoolModal({
  5221. tagUid: extFilamentData.tagUid || linkTag,
  5222. trayUuid: extFilamentData.trayUuid || '',
  5223. printerId: printer.id,
  5224. amsId: 255,
  5225. trayId: slotTrayId,
  5226. });
  5227. } : undefined,
  5228. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5229. }}
  5230. inventory={(() => {
  5231. if (spoolmanEnabled) {
  5232. if (spoolmanLoading) return undefined;
  5233. const slotAssignment = extSlotAssignmentForFill;
  5234. const spoolmanSpool = extSlotSpoolForFill;
  5235. return {
  5236. assignedSpool: spoolmanSpool ? {
  5237. id: spoolmanSpool.id,
  5238. material: spoolmanSpool.material,
  5239. brand: spoolmanSpool.brand ?? null,
  5240. color_name: spoolmanSpool.color_name ?? null,
  5241. remainingWeightGrams: spoolmanSpool.label_weight
  5242. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5243. : undefined,
  5244. } : null,
  5245. onAssignSpool: () => setAssignSpoolModal({
  5246. printerId: printer.id,
  5247. amsId: 255,
  5248. trayId: slotTrayId,
  5249. trayInfo: {
  5250. type: extTray.tray_type || extFilamentData.profile,
  5251. material: extTray.tray_type ?? undefined,
  5252. profile: extFilamentData.profile,
  5253. color: extFilamentData.colorHex || '',
  5254. location: extLabel || t('printers.external'),
  5255. },
  5256. }),
  5257. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5258. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5259. };
  5260. }
  5261. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5262. return {
  5263. assignedSpool: assignment?.spool ? {
  5264. id: assignment.spool.id,
  5265. material: assignment.spool.material,
  5266. brand: assignment.spool.brand,
  5267. color_name: assignment.spool.color_name,
  5268. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5269. } : null,
  5270. onAssignSpool: () => setAssignSpoolModal({
  5271. printerId: printer.id,
  5272. amsId: 255,
  5273. trayId: slotTrayId,
  5274. trayInfo: {
  5275. type: extTray.tray_type || extFilamentData.profile,
  5276. material: extTray.tray_type ?? undefined,
  5277. profile: extFilamentData.profile,
  5278. color: extFilamentData.colorHex || '',
  5279. location: extLabel || t('printers.external'),
  5280. },
  5281. }),
  5282. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5283. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5284. };
  5285. })()}
  5286. configureSlot={{
  5287. enabled: hasPermission('printers:control'),
  5288. onConfigure: () => setConfigureSlotModal({
  5289. amsId: 255,
  5290. trayId: slotTrayId,
  5291. trayCount: 1,
  5292. trayType: extTray.tray_type || undefined,
  5293. trayColor: extTray.tray_color || undefined,
  5294. traySubBrands: extTray.tray_sub_brands || undefined,
  5295. trayInfoIdx: extTray.tray_info_idx || undefined,
  5296. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5297. caliIdx: extTray.cali_idx,
  5298. savedPresetId: extSlotPreset?.preset_id,
  5299. }),
  5300. }}
  5301. >
  5302. {extSlotContent}
  5303. </FilamentHoverCard>
  5304. ) : (
  5305. <EmptySlotHoverCard
  5306. kind={emptyKind ?? undefined}
  5307. actions={renderAmsSlotActions({
  5308. amsId: 255,
  5309. slotId: slotTrayId,
  5310. loadTrayId: extTrayId,
  5311. includeRfid: false,
  5312. })}
  5313. configureSlot={{
  5314. enabled: hasPermission('printers:control'),
  5315. onConfigure: () => setConfigureSlotModal({
  5316. amsId: 255,
  5317. trayId: slotTrayId,
  5318. trayCount: 1,
  5319. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5320. }),
  5321. }}
  5322. onAssignSpool={() => setAssignSpoolModal({
  5323. printerId: printer.id,
  5324. amsId: 255,
  5325. trayId: slotTrayId,
  5326. trayInfo: {
  5327. type: '',
  5328. material: undefined,
  5329. profile: '',
  5330. color: '',
  5331. location: `External Slot ${slotTrayId + 1}`,
  5332. },
  5333. })}
  5334. >
  5335. {extSlotContent}
  5336. </EmptySlotHoverCard>
  5337. )}
  5338. </div>
  5339. );
  5340. })}
  5341. </div>
  5342. </div>
  5343. )}
  5344. </div>
  5345. </div>
  5346. );
  5347. })()}
  5348. </>
  5349. )}
  5350. {/* Bottom block (power row + action bar). Wrapped together so the
  5351. power row hugs the action bar at the card bottom instead of
  5352. floating up when there's less filament content above. */}
  5353. {viewMode === 'expanded' && (
  5354. <div className="mt-auto">
  5355. {smartPlug && (
  5356. <div className="pt-3">
  5357. <div className="flex items-center gap-2 mb-2">
  5358. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  5359. {t('printers.power', 'Power')}
  5360. </span>
  5361. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5362. </div>
  5363. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  5364. {/* Plug name + current power */}
  5365. <div className="flex items-center gap-2 min-w-0 pl-1">
  5366. <Zap className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  5367. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  5368. <span
  5369. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[10px] font-medium flex-shrink-0"
  5370. title={t('smartPlugs.power')}
  5371. >
  5372. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  5373. </span>
  5374. </div>
  5375. {/* Spacer */}
  5376. <div className="flex-1" />
  5377. <div className="flex items-center gap-2">
  5378. {/* Auto-off */}
  5379. <button
  5380. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  5381. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  5382. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  5383. 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 ${
  5384. !hasPermission('smart_plugs:control')
  5385. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5386. : smartPlug.auto_off || smartPlug.auto_off_executed
  5387. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5388. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5389. }`}
  5390. >
  5391. <Clock className="w-4 h-4" />
  5392. </button>
  5393. <button
  5394. onClick={() => {
  5395. if (plugStatus?.state === 'ON') {
  5396. setShowPowerOffConfirm(true);
  5397. } else {
  5398. setShowPowerOnConfirm(true);
  5399. }
  5400. }}
  5401. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  5402. 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 ${
  5403. !hasPermission('smart_plugs:control')
  5404. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5405. : plugStatus?.state === 'ON'
  5406. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5407. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5408. }`}
  5409. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  5410. >
  5411. <Zap className="w-4 h-4" />
  5412. </button>
  5413. </div>
  5414. </div>
  5415. {/* HA entity buttons row */}
  5416. {scriptPlugs && scriptPlugs.length > 0 && (
  5417. <div className="flex items-center gap-2 mt-2">
  5418. <Home className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
  5419. <span className="text-xs text-bambu-gray">HA:</span>
  5420. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  5421. <div className="flex flex-wrap gap-1">
  5422. {scriptPlugs.map(script => {
  5423. const isScript = script.ha_entity_id?.startsWith('script.');
  5424. return (
  5425. <button
  5426. key={script.id}
  5427. onClick={() => {
  5428. if (isScript) {
  5429. runScriptMutation.mutate({ id: script.id, action: 'on' });
  5430. } else {
  5431. setHaToggleConfirm(script);
  5432. }
  5433. }}
  5434. disabled={runScriptMutation.isPending}
  5435. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  5436. 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"
  5437. >
  5438. <Play className="w-2.5 h-2.5" />
  5439. {script.name}
  5440. </button>
  5441. );
  5442. })}
  5443. </div>
  5444. </div>
  5445. )}
  5446. </div>
  5447. )}
  5448. {/* Connection Info & Actions */}
  5449. <div className="pt-4">
  5450. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  5451. <div className="flex items-center justify-between gap-2">
  5452. {printerActionsMenu}
  5453. <div className="flex items-center justify-end gap-2 flex-wrap">
  5454. {/* Camera Button */}
  5455. <Button
  5456. variant="secondary"
  5457. size="sm"
  5458. onClick={() => {
  5459. if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
  5460. onOpenEmbeddedCamera(printer.id, printer.name);
  5461. } else {
  5462. // Use saved window state or defaults
  5463. const saved = localStorage.getItem('cameraWindowState');
  5464. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  5465. const features = [
  5466. `width=${state.width}`,
  5467. `height=${state.height}`,
  5468. state.left !== undefined ? `left=${state.left}` : '',
  5469. state.top !== undefined ? `top=${state.top}` : '',
  5470. // No `noopener`: same-origin popup needs opener so the browser
  5471. // copies sessionStorage (auth token) into the new window.
  5472. 'menubar=no,toolbar=no,location=no,status=no',
  5473. ].filter(Boolean).join(',');
  5474. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  5475. }
  5476. }}
  5477. disabled={!status?.connected || !hasPermission('camera:view')}
  5478. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  5479. className={footerIconButtonClass}
  5480. >
  5481. <Video className="w-4 h-4" />
  5482. </Button>
  5483. <Button
  5484. variant="secondary"
  5485. size="sm"
  5486. onClick={() => setShowFileManager(true)}
  5487. disabled={!isConnected || !hasPermission('printers:files')}
  5488. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  5489. className={footerIconButtonClass}
  5490. >
  5491. <HardDrive className="w-4 h-4" />
  5492. </Button>
  5493. {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
  5494. <Button
  5495. size="sm"
  5496. onClick={() => setShowUploadForPrint(true)}
  5497. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  5498. title={
  5499. !hasPermission('library:upload')
  5500. ? t('fileManager.noPermissionUpload')
  5501. : !hasPermission('queue:create')
  5502. ? t('fileManager.noPermissionAddToQueue')
  5503. : t('common.print')
  5504. }
  5505. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  5506. >
  5507. <PrinterIcon className="w-4 h-4" />
  5508. {t('common.print')}
  5509. </Button>
  5510. )}
  5511. </div>
  5512. </div>
  5513. </div>
  5514. </div>
  5515. )}
  5516. </CardContent>
  5517. {/* File Manager Modal */}
  5518. {showFileManager && (
  5519. <FileManagerModal
  5520. printerId={printer.id}
  5521. printerName={printer.name}
  5522. onClose={() => setShowFileManager(false)}
  5523. />
  5524. )}
  5525. {/* Upload for Print Modal */}
  5526. {showUploadForPrint && (
  5527. <FileUploadModal
  5528. folderId={null}
  5529. onClose={() => setShowUploadForPrint(false)}
  5530. onUploadComplete={() => {}}
  5531. autoUpload
  5532. accept=".gcode,.3mf"
  5533. validateFile={(file) => {
  5534. const lower = file.name.toLowerCase();
  5535. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  5536. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  5537. }
  5538. }}
  5539. onFileUploaded={(uploadedFile) => {
  5540. // Check printer compatibility if sliced_for_model is available in metadata
  5541. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  5542. const printerModel = mapModelCode(printer.model);
  5543. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  5544. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  5545. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  5546. }
  5547. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  5548. }}
  5549. />
  5550. )}
  5551. {/* Print Modal (after upload) */}
  5552. {printAfterUpload && (
  5553. <PrintModal
  5554. mode="create"
  5555. libraryFileId={printAfterUpload.id}
  5556. archiveName={printAfterUpload.filename}
  5557. initialSelectedPrinterIds={[printer.id]}
  5558. onClose={() => setPrintAfterUpload(null)}
  5559. onSuccess={() => setPrintAfterUpload(null)}
  5560. cleanupLibraryAfterDispatch
  5561. />
  5562. )}
  5563. {/* MQTT Debug Modal */}
  5564. {showMQTTDebug && (
  5565. <MQTTDebugModal
  5566. printerId={printer.id}
  5567. printerName={printer.name}
  5568. onClose={() => setShowMQTTDebug(false)}
  5569. />
  5570. )}
  5571. {showDiagnostic && (
  5572. <ConnectionDiagnosticModal
  5573. printerId={printer.id}
  5574. printerName={printer.name}
  5575. onClose={() => setShowDiagnostic(false)}
  5576. />
  5577. )}
  5578. {showPrinterInfo && (
  5579. <PrinterInfoModal
  5580. printer={printer}
  5581. status={status}
  5582. totalPrintHours={maintenanceInfo?.total_print_hours}
  5583. onClose={closePrinterInfo}
  5584. />
  5585. )}
  5586. {/* Plate Check Result Modal */}
  5587. {plateCheckResult && (
  5588. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  5589. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  5590. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  5591. <div className="flex items-center gap-2">
  5592. {plateCheckResult.needs_calibration ? (
  5593. <ScanSearch className="w-5 h-5 text-blue-500" />
  5594. ) : plateCheckResult.is_empty ? (
  5595. <CheckCircle className="w-5 h-5 text-green-500" />
  5596. ) : (
  5597. <XCircle className="w-5 h-5 text-yellow-500" />
  5598. )}
  5599. <h2 className="text-lg font-semibold text-white">
  5600. Build Plate Check
  5601. </h2>
  5602. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  5603. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  5604. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  5605. </span>
  5606. )}
  5607. </div>
  5608. <button
  5609. onClick={() => closePlateCheckModal()}
  5610. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  5611. >
  5612. <X className="w-5 h-5" />
  5613. </button>
  5614. </div>
  5615. <div className="p-4 space-y-4">
  5616. {plateCheckResult.needs_calibration ? (
  5617. <>
  5618. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  5619. <p className="font-medium text-blue-700 dark:text-blue-400">
  5620. {t('printers.plateDetection.calibrationRequired')}
  5621. </p>
  5622. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  5623. </div>
  5624. <div className="text-sm text-bambu-gray space-y-2">
  5625. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  5626. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  5627. </div>
  5628. </>
  5629. ) : (
  5630. <>
  5631. <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'}`}>
  5632. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  5633. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  5634. </p>
  5635. <p className="text-sm text-bambu-gray mt-1">
  5636. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  5637. </p>
  5638. </div>
  5639. {plateCheckResult.debug_image_url && (
  5640. <div>
  5641. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  5642. <img
  5643. src={plateCheckResult.debug_image_url}
  5644. alt={t('printers.plateDetection.analysisPreview')}
  5645. className="w-full rounded-lg border border-bambu-dark-tertiary"
  5646. />
  5647. <p className="text-xs text-bambu-gray mt-2">
  5648. {t('printers.plateDetection.analysisLegend')}
  5649. </p>
  5650. </div>
  5651. )}
  5652. <p className="text-xs text-bambu-gray">
  5653. {plateCheckResult.message}
  5654. </p>
  5655. </>
  5656. )}
  5657. {/* Saved References Grid */}
  5658. {plateReferences && plateReferences.references.length > 0 && (
  5659. <div className="mt-4">
  5660. <div className="flex items-center gap-2 mb-2">
  5661. <p className="text-sm font-medium text-white shrink-0">
  5662. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  5663. </p>
  5664. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5665. </div>
  5666. <div className="grid grid-cols-5 gap-2">
  5667. {plateReferences.references.map((ref) => (
  5668. <div key={ref.index} className="relative group">
  5669. <img
  5670. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  5671. alt={ref.label || `Reference ${ref.index + 1}`}
  5672. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  5673. />
  5674. {/* Delete button */}
  5675. <button
  5676. onClick={() => handleDeleteRef(ref.index)}
  5677. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  5678. title={t('printers.plateDetection.deleteReference')}
  5679. >
  5680. <X className="w-3 h-3 text-white" />
  5681. </button>
  5682. {/* Label */}
  5683. {editingRefLabel?.index === ref.index ? (
  5684. <input
  5685. type="text"
  5686. value={editingRefLabel.label}
  5687. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  5688. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  5689. onKeyDown={(e) => {
  5690. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  5691. if (e.key === 'Escape') setEditingRefLabel(null);
  5692. }}
  5693. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  5694. autoFocus
  5695. placeholder={t('printers.plateDetection.labelPlaceholder')}
  5696. />
  5697. ) : (
  5698. <p
  5699. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  5700. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  5701. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  5702. >
  5703. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  5704. </p>
  5705. )}
  5706. {/* Timestamp */}
  5707. <p className="text-[10px] text-bambu-gray/60">
  5708. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  5709. </p>
  5710. </div>
  5711. ))}
  5712. </div>
  5713. </div>
  5714. )}
  5715. {/* ROI Editor */}
  5716. {!plateCheckResult.needs_calibration && (
  5717. <div className="mt-4">
  5718. <div className="flex items-center justify-between mb-2">
  5719. <div className="flex min-w-0 flex-1 items-center gap-2">
  5720. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  5721. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5722. </div>
  5723. {!editingRoi ? (
  5724. <Button
  5725. variant="ghost"
  5726. size="sm"
  5727. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  5728. >
  5729. <Pencil className="w-3 h-3 mr-1" />
  5730. {t('common.edit')}
  5731. </Button>
  5732. ) : (
  5733. <div className="flex gap-1">
  5734. <Button
  5735. variant="ghost"
  5736. size="sm"
  5737. onClick={() => setEditingRoi(null)}
  5738. disabled={isSavingRoi}
  5739. >
  5740. {t('common.cancel')}
  5741. </Button>
  5742. <Button
  5743. size="sm"
  5744. onClick={handleSaveRoi}
  5745. disabled={isSavingRoi}
  5746. >
  5747. {isSavingRoi ? <Loader2 className="w-3 h-3 animate-spin" /> : t('common.save')}
  5748. </Button>
  5749. </div>
  5750. )}
  5751. </div>
  5752. {editingRoi ? (
  5753. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  5754. <div className="grid grid-cols-2 gap-3">
  5755. <div>
  5756. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  5757. <input
  5758. type="range"
  5759. min="0"
  5760. max="0.9"
  5761. step="0.01"
  5762. value={editingRoi.x}
  5763. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  5764. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5765. />
  5766. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  5767. </div>
  5768. <div>
  5769. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  5770. <input
  5771. type="range"
  5772. min="0"
  5773. max="0.9"
  5774. step="0.01"
  5775. value={editingRoi.y}
  5776. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  5777. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5778. />
  5779. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  5780. </div>
  5781. <div>
  5782. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  5783. <input
  5784. type="range"
  5785. min="0.1"
  5786. max="1"
  5787. step="0.01"
  5788. value={editingRoi.w}
  5789. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  5790. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5791. />
  5792. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  5793. </div>
  5794. <div>
  5795. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  5796. <input
  5797. type="range"
  5798. min="0.1"
  5799. max="1"
  5800. step="0.01"
  5801. value={editingRoi.h}
  5802. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  5803. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5804. />
  5805. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  5806. </div>
  5807. </div>
  5808. <p className="text-xs text-bambu-gray">
  5809. {t('printers.roi.instruction')}
  5810. </p>
  5811. </div>
  5812. ) : (
  5813. <p className="text-xs text-bambu-gray">
  5814. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  5815. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  5816. </p>
  5817. )}
  5818. </div>
  5819. )}
  5820. </div>
  5821. <div className="flex justify-end gap-2 p-4">
  5822. {plateCheckResult.needs_calibration ? (
  5823. <>
  5824. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  5825. {t('common.cancel')}
  5826. </Button>
  5827. <Button
  5828. onClick={() => handleCalibratePlate()}
  5829. disabled={isCalibrating}
  5830. >
  5831. {isCalibrating ? (
  5832. <>
  5833. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  5834. Calibrating...
  5835. </>
  5836. ) : (
  5837. 'Calibrate Empty Plate'
  5838. )}
  5839. </Button>
  5840. </>
  5841. ) : (
  5842. <>
  5843. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  5844. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  5845. </Button>
  5846. <Button onClick={() => closePlateCheckModal()}>
  5847. Close
  5848. </Button>
  5849. </>
  5850. )}
  5851. </div>
  5852. </div>
  5853. </div>
  5854. )}
  5855. {/* Power On Confirmation */}
  5856. {showPowerOnConfirm && smartPlug && (
  5857. <ConfirmModal
  5858. title={t('printers.confirm.powerOnTitle')}
  5859. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  5860. confirmText={t('printers.confirm.powerOnButton')}
  5861. variant="default"
  5862. onConfirm={() => {
  5863. powerControlMutation.mutate('on');
  5864. setShowPowerOnConfirm(false);
  5865. }}
  5866. onCancel={() => setShowPowerOnConfirm(false)}
  5867. />
  5868. )}
  5869. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  5870. disconnects MQTT, which stops progress tracking + completion
  5871. notifications for the in-flight job. Idle / FINISH / FAILED states
  5872. skip this dialog and toggle directly. */}
  5873. {confirmMaintenanceEnter && (
  5874. <ConfirmModal
  5875. title={t('printers.maintenance.confirmMidPrintTitle')}
  5876. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  5877. confirmText={t('printers.maintenance.menuEnter')}
  5878. variant="danger"
  5879. onConfirm={() => {
  5880. maintenanceMutation.mutate(false);
  5881. setConfirmMaintenanceEnter(false);
  5882. }}
  5883. onCancel={() => setConfirmMaintenanceEnter(false)}
  5884. />
  5885. )}
  5886. {/* Power Off Confirmation */}
  5887. {showPowerOffConfirm && smartPlug && (
  5888. <ConfirmModal
  5889. title={t('printers.confirm.powerOffTitle')}
  5890. message={
  5891. status?.state === 'RUNNING'
  5892. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  5893. : t('printers.confirm.powerOffMessage', { name: printer.name })
  5894. }
  5895. confirmText={t('printers.confirm.powerOffButton')}
  5896. variant="danger"
  5897. onConfirm={() => {
  5898. powerControlMutation.mutate('off');
  5899. setShowPowerOffConfirm(false);
  5900. }}
  5901. onCancel={() => setShowPowerOffConfirm(false)}
  5902. />
  5903. )}
  5904. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  5905. {haToggleConfirm && (
  5906. <ConfirmModal
  5907. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  5908. message={
  5909. status?.state === 'RUNNING'
  5910. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5911. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5912. }
  5913. confirmText={t('printers.confirm.haToggleButton')}
  5914. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  5915. onConfirm={() => {
  5916. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  5917. setHaToggleConfirm(null);
  5918. }}
  5919. onCancel={() => setHaToggleConfirm(null)}
  5920. />
  5921. )}
  5922. {/* Stop Print Confirmation */}
  5923. {showStopConfirm && (
  5924. <ConfirmModal
  5925. title={t('printers.confirm.stopTitle')}
  5926. message={t('printers.confirm.stopMessage', { name: printer.name })}
  5927. confirmText={t('printers.confirm.stopButton')}
  5928. variant="danger"
  5929. onConfirm={() => {
  5930. stopPrintMutation.mutate();
  5931. setShowStopConfirm(false);
  5932. }}
  5933. onCancel={() => setShowStopConfirm(false)}
  5934. />
  5935. )}
  5936. {/* Pause Print Confirmation */}
  5937. {showPauseConfirm && (
  5938. <ConfirmModal
  5939. title={t('printers.confirm.pauseTitle')}
  5940. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  5941. confirmText={t('printers.confirm.pauseButton')}
  5942. variant="default"
  5943. onConfirm={() => {
  5944. pausePrintMutation.mutate();
  5945. setShowPauseConfirm(false);
  5946. }}
  5947. onCancel={() => setShowPauseConfirm(false)}
  5948. />
  5949. )}
  5950. {/* Resume Print Confirmation */}
  5951. {showResumeConfirm && (
  5952. <ConfirmModal
  5953. title={t('printers.confirm.resumeTitle')}
  5954. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  5955. confirmText={t('printers.confirm.resumeButton')}
  5956. variant="default"
  5957. onConfirm={() => {
  5958. resumePrintMutation.mutate();
  5959. setShowResumeConfirm(false);
  5960. }}
  5961. onCancel={() => setShowResumeConfirm(false)}
  5962. />
  5963. )}
  5964. {/* Skip Objects Modal */}
  5965. <SkipObjectsModal
  5966. printerId={printer.id}
  5967. isOpen={showSkipObjectsModal}
  5968. onClose={() => setShowSkipObjectsModal(false)}
  5969. />
  5970. {/* HMS Error Modal */}
  5971. {showHMSModal && (
  5972. <HMSErrorModal
  5973. printerName={printer.name}
  5974. errors={status?.hms_errors || []}
  5975. onClose={() => setShowHMSModal(false)}
  5976. printerId={printer.id}
  5977. hasPermission={hasPermission}
  5978. runoutGuidance={runoutGuidance}
  5979. />
  5980. )}
  5981. {/* AMS Filament Backup status / control modal (#1762) */}
  5982. {amsBackupModalOpen && status && (
  5983. <AmsBackupModal
  5984. isOpen={amsBackupModalOpen}
  5985. state={status.ams_filament_backup}
  5986. amsUnits={status.ams}
  5987. amsExtruderMap={status.ams_extruder_map}
  5988. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  5989. canToggle={hasPermission('printers:control')}
  5990. pending={setAmsBackupMutation.isPending}
  5991. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  5992. onClose={() => setAmsBackupModalOpen(false)}
  5993. />
  5994. )}
  5995. {/* AMS History Modal */}
  5996. {amsHistoryModal && (
  5997. <AMSHistoryModal
  5998. isOpen={!!amsHistoryModal}
  5999. onClose={() => setAmsHistoryModal(null)}
  6000. printerId={printer.id}
  6001. printerName={printer.name}
  6002. amsId={amsHistoryModal.amsId}
  6003. amsLabel={amsHistoryModal.amsLabel}
  6004. initialMode={amsHistoryModal.mode}
  6005. thresholds={amsThresholds}
  6006. />
  6007. )}
  6008. {/* Heater History Modal (nozzle / bed / chamber) */}
  6009. {heaterHistoryModal && (
  6010. <HeaterHistoryModal
  6011. isOpen={!!heaterHistoryModal}
  6012. onClose={() => setHeaterHistoryModal(null)}
  6013. printerId={printer.id}
  6014. printerName={printer.name}
  6015. initialKind={heaterHistoryModal.initialKind}
  6016. availableKinds={heaterHistoryModal.availableKinds}
  6017. />
  6018. )}
  6019. {/* Link Spool Modal */}
  6020. {linkSpoolModal && (
  6021. <LinkSpoolModal
  6022. isOpen={!!linkSpoolModal}
  6023. onClose={() => setLinkSpoolModal(null)}
  6024. tagUid={linkSpoolModal.tagUid}
  6025. trayUuid={linkSpoolModal.trayUuid}
  6026. printerId={linkSpoolModal.printerId}
  6027. amsId={linkSpoolModal.amsId}
  6028. trayId={linkSpoolModal.trayId}
  6029. />
  6030. )}
  6031. {/* Assign Spool Modal */}
  6032. {assignSpoolModal && (
  6033. <AssignSpoolModal
  6034. isOpen={!!assignSpoolModal}
  6035. onClose={() => setAssignSpoolModal(null)}
  6036. printerId={assignSpoolModal.printerId}
  6037. amsId={assignSpoolModal.amsId}
  6038. trayId={assignSpoolModal.trayId}
  6039. trayInfo={assignSpoolModal.trayInfo}
  6040. spoolmanEnabled={!!spoolmanEnabled}
  6041. />
  6042. )}
  6043. {/* Configure AMS Slot Modal */}
  6044. {configureSlotModal && (
  6045. <ConfigureAmsSlotModal
  6046. isOpen={!!configureSlotModal}
  6047. onClose={() => setConfigureSlotModal(null)}
  6048. printerId={printer.id}
  6049. slotInfo={configureSlotModal}
  6050. printerModel={mapModelCode(printer.model) || undefined}
  6051. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6052. onSuccess={() => {
  6053. // Refresh slot presets to show updated profile name
  6054. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  6055. // Printer status will update automatically via WebSocket when AMS data changes
  6056. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6057. }}
  6058. />
  6059. )}
  6060. {/* Edit Printer Modal */}
  6061. {showEditModal && (
  6062. <EditPrinterModal
  6063. printer={printer}
  6064. onClose={() => setShowEditModal(false)}
  6065. />
  6066. )}
  6067. {/* Firmware Update Modal */}
  6068. {showFirmwareModal && firmwareInfo && (
  6069. <FirmwareUpdateModal
  6070. printer={printer}
  6071. firmwareInfo={firmwareInfo}
  6072. onClose={() => setShowFirmwareModal(false)}
  6073. />
  6074. )}
  6075. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  6076. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  6077. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  6078. const sliderMin = 35;
  6079. const sliderMax = maxTemp + 10;
  6080. return (
  6081. <>
  6082. {/* Backdrop */}
  6083. <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
  6084. {/* Popover */}
  6085. <div
  6086. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  6087. style={{
  6088. top: dryingPopoverPos.top,
  6089. left: dryingPopoverPos.left,
  6090. // Cap to the space between the popover's top and the bottom
  6091. // viewport margin (8px, matching computePopoverPosition's
  6092. // margin). When the popover is taller than that space — short
  6093. // viewport, landscape phone, zoomed-in — the body scrolls and
  6094. // the footer stays pinned, so the Start button is always
  6095. // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
  6096. // Safari's bottom toolbar overlay doesn't clip the footer
  6097. // (#1669, iPhone 17 Safari).
  6098. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6099. }}
  6100. onClick={e => e.stopPropagation()}
  6101. >
  6102. {/* Header */}
  6103. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6104. <Flame className="w-3.5 h-3.5 text-bambu-green" />
  6105. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6106. </div>
  6107. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6108. {/* Body */}
  6109. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6110. {/* Filament type select */}
  6111. <div>
  6112. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6113. <ToolbarDropdown
  6114. value={dryingFilament}
  6115. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6116. onChange={fil => {
  6117. setDryingFilament(fil);
  6118. const preset = dryingPresets[fil];
  6119. if (preset) {
  6120. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6121. setDryingTemp(preset[key]);
  6122. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6123. }
  6124. }}
  6125. fullWidth
  6126. />
  6127. </div>
  6128. {/* Temperature */}
  6129. <div>
  6130. <div className="flex items-center justify-between mb-1">
  6131. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6132. <div className="flex items-center gap-1">
  6133. <input
  6134. type="number"
  6135. min={45}
  6136. max={maxTemp}
  6137. value={dryingTemp}
  6138. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6139. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6140. />
  6141. <span className="text-[10px] text-bambu-gray">°C</span>
  6142. </div>
  6143. </div>
  6144. <input
  6145. type="range"
  6146. min={sliderMin}
  6147. max={sliderMax}
  6148. value={dryingTemp}
  6149. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6150. className="w-full h-1 accent-bambu-green cursor-pointer"
  6151. />
  6152. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6153. <span>45°C</span>
  6154. <span>{maxTemp}°C</span>
  6155. </div>
  6156. </div>
  6157. {/* Duration */}
  6158. <div>
  6159. <div className="flex items-center justify-between mb-1">
  6160. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6161. <div className="flex items-center gap-1">
  6162. <input
  6163. type="number"
  6164. min={1}
  6165. max={24}
  6166. value={dryingDuration}
  6167. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6168. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6169. />
  6170. <span className="text-[10px] text-bambu-gray">{t('printers.drying.hours')}</span>
  6171. </div>
  6172. </div>
  6173. <input
  6174. type="range"
  6175. min={1}
  6176. max={24}
  6177. value={dryingDuration}
  6178. onChange={e => setDryingDuration(Number(e.target.value))}
  6179. className="w-full h-1 accent-bambu-green cursor-pointer"
  6180. />
  6181. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6182. <span>1h</span>
  6183. <span>24h</span>
  6184. </div>
  6185. </div>
  6186. {/* Rotate tray — disabled when any tray in THIS AMS has its
  6187. filament threaded out into the feed tube. The whole AMS
  6188. rotates as one mechanism (all 4 spools turn together), so a
  6189. single loaded slot locks the entire unit. Bambu per-tray
  6190. `state`: 9 = empty, 10 = spool present but not loaded
  6191. (rotation possible), 11 = loaded into tube (rotation impossible).
  6192. Catches both mid-print (active feed) AND idle-with-threaded-
  6193. filament — the H2D's post-print state leaves filament in the
  6194. tube but tray_now resets to 255, which a tray_now-only check
  6195. would silently miss. */}
  6196. {(() => {
  6197. const targetAms = dryingPopoverAmsId !== null
  6198. ? amsData.find(a => a.id === dryingPopoverAmsId)
  6199. : undefined;
  6200. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6201. tray => tray.state === 11,
  6202. );
  6203. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  6204. return (
  6205. <button
  6206. type="button"
  6207. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6208. aria-pressed={rotateChecked}
  6209. disabled={trayLoadedInThisAms}
  6210. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  6211. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  6212. rotateChecked
  6213. ? 'bg-bambu-green border-bambu-green text-white'
  6214. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  6215. }`}
  6216. >
  6217. {t('printers.drying.rotateTray')}
  6218. </button>
  6219. );
  6220. })()}
  6221. </div>
  6222. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6223. {/* Footer */}
  6224. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6225. <button
  6226. onClick={() => {
  6227. if (dryingPopoverAmsId !== null) {
  6228. // Clamp rotateTray off when any tray in this AMS is loaded into
  6229. // the tube — the rotate UI is disabled there, but the state may
  6230. // linger as `true` from a previous AMS, or a print may have
  6231. // started while the popover was open. Without this clamp the
  6232. // Start payload would carry rotate_tray=true and firmware would
  6233. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  6234. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  6235. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6236. tray => tray.state === 11,
  6237. );
  6238. startDryingMutation.mutate({
  6239. amsId: dryingPopoverAmsId,
  6240. temp: dryingTemp,
  6241. duration: dryingDuration,
  6242. filament: dryingFilament,
  6243. rotateTray: dryingRotateTray && !trayLoadedInThisAms,
  6244. });
  6245. }
  6246. }}
  6247. disabled={startDryingMutation.isPending}
  6248. data-testid="drying-start-confirm"
  6249. 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"
  6250. >
  6251. {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
  6252. </button>
  6253. </div>
  6254. </div>
  6255. </>
  6256. );
  6257. })()}
  6258. </Card>
  6259. );
  6260. }
  6261. export function AddPrinterModal({
  6262. onClose,
  6263. onAdd,
  6264. existingSerials,
  6265. }: {
  6266. onClose: () => void;
  6267. onAdd: (data: PrinterCreate) => void;
  6268. existingSerials: string[];
  6269. }) {
  6270. const { t } = useTranslation();
  6271. const [form, setForm] = useState<PrinterCreate>({
  6272. name: '',
  6273. serial_number: '',
  6274. ip_address: '',
  6275. access_code: '',
  6276. model: '',
  6277. location: '',
  6278. auto_archive: true,
  6279. });
  6280. // Discovery state
  6281. const [discovering, setDiscovering] = useState(false);
  6282. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  6283. const [discoveryError, setDiscoveryError] = useState('');
  6284. const [hasScanned, setHasScanned] = useState(false);
  6285. const [isDocker, setIsDocker] = useState(false);
  6286. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  6287. const [subnet, setSubnet] = useState('');
  6288. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  6289. // text input so users can scan a subnet Bambuddy isn't directly on
  6290. // (printer behind a router on a different L3 segment — SSDP multicast
  6291. // won't cross that boundary, only an active unicast scan will). #1564
  6292. const [customSubnet, setCustomSubnet] = useState('');
  6293. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  6294. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  6295. const [showDiagnostic, setShowDiagnostic] = useState(false);
  6296. // Setup-time pre-flight: run the connection diagnostic on save and warn
  6297. // (not block) when checks fail, so the user doesn't add a printer that
  6298. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  6299. // failed result awaiting an explicit "save anyway".
  6300. const [checkingSave, setCheckingSave] = useState(false);
  6301. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6302. // Fetch discovery info on mount + restore the last custom CIDR the user
  6303. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  6304. // time they open this modal).
  6305. useEffect(() => {
  6306. discoveryApi.getInfo().then(info => {
  6307. setIsDocker(info.is_docker);
  6308. if (info.subnets.length > 0) {
  6309. setDetectedSubnets(info.subnets);
  6310. setSubnet(info.subnets[0]);
  6311. }
  6312. }).catch(() => {
  6313. // Ignore errors, assume not Docker
  6314. });
  6315. try {
  6316. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  6317. if (saved) setCustomSubnet(saved);
  6318. } catch {
  6319. // localStorage unavailable (private mode, quota); recall is opportunistic
  6320. }
  6321. }, []);
  6322. // Filter out already-added printers
  6323. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  6324. const handleAddSubmit = async (e: React.FormEvent) => {
  6325. e.preventDefault();
  6326. setCheckingSave(true);
  6327. try {
  6328. const result = await api.diagnoseConnection({
  6329. ip_address: form.ip_address.trim(),
  6330. serial_number: form.serial_number.trim() || undefined,
  6331. access_code: form.access_code || undefined,
  6332. });
  6333. if (result.checks.some((c) => c.status === 'fail')) {
  6334. setSaveWarning(result);
  6335. return;
  6336. }
  6337. } catch {
  6338. // Diagnostic infrastructure failed — never block the save on it.
  6339. } finally {
  6340. setCheckingSave(false);
  6341. }
  6342. onAdd(form);
  6343. };
  6344. const startDiscovery = async () => {
  6345. setDiscoveryError('');
  6346. setDiscovered([]);
  6347. setDiscovering(true);
  6348. setHasScanned(false);
  6349. setScanProgress({ scanned: 0, total: 0 });
  6350. // Native installs fall back to subnet scanning when the user picks
  6351. // "Custom" — SSDP can't reach a printer on a different L3 segment
  6352. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  6353. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  6354. const wantsSubnetScan = isDocker || useCustomSubnet;
  6355. if (wantsSubnetScan && useCustomSubnet) {
  6356. try {
  6357. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  6358. } catch {
  6359. // localStorage write best-effort; user just retypes next time
  6360. }
  6361. }
  6362. try {
  6363. if (wantsSubnetScan) {
  6364. await discoveryApi.startSubnetScan(scanCidr);
  6365. // Poll for scan status and results
  6366. const pollInterval = setInterval(async () => {
  6367. try {
  6368. const status = await discoveryApi.getScanStatus();
  6369. setScanProgress({ scanned: status.scanned, total: status.total });
  6370. const printers = await discoveryApi.getDiscoveredPrinters();
  6371. setDiscovered(printers);
  6372. if (!status.running) {
  6373. clearInterval(pollInterval);
  6374. setDiscovering(false);
  6375. setHasScanned(true);
  6376. }
  6377. } catch (e) {
  6378. console.error('Failed to get scan status:', e);
  6379. }
  6380. }, 500);
  6381. } else {
  6382. // Use SSDP discovery for native installs
  6383. await discoveryApi.startDiscovery(10);
  6384. // Poll for discovered printers every second
  6385. const pollInterval = setInterval(async () => {
  6386. try {
  6387. const printers = await discoveryApi.getDiscoveredPrinters();
  6388. setDiscovered(printers);
  6389. } catch (e) {
  6390. console.error('Failed to get discovered printers:', e);
  6391. }
  6392. }, 1000);
  6393. // Stop after 10 seconds
  6394. setTimeout(async () => {
  6395. clearInterval(pollInterval);
  6396. try {
  6397. await discoveryApi.stopDiscovery();
  6398. } catch {
  6399. // Ignore stop errors
  6400. }
  6401. setDiscovering(false);
  6402. setHasScanned(true);
  6403. // Final fetch
  6404. try {
  6405. const printers = await discoveryApi.getDiscoveredPrinters();
  6406. setDiscovered(printers);
  6407. } catch (e) {
  6408. console.error('Failed to get final discovered printers:', e);
  6409. }
  6410. }, 10000);
  6411. }
  6412. } catch (e) {
  6413. console.error('Failed to start discovery:', e);
  6414. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  6415. setDiscovering(false);
  6416. setHasScanned(true);
  6417. }
  6418. };
  6419. // Reuse module-level mapModelCode
  6420. const selectPrinter = (printer: DiscoveredPrinter) => {
  6421. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  6422. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  6423. setForm({
  6424. ...form,
  6425. name: printer.name || '',
  6426. serial_number: serialNumber,
  6427. ip_address: printer.ip_address,
  6428. model: mapModelCode(printer.model),
  6429. });
  6430. // Clear discovery results after selection
  6431. setDiscovered([]);
  6432. };
  6433. // Cleanup discovery on unmount
  6434. useEffect(() => {
  6435. return () => {
  6436. discoveryApi.stopDiscovery().catch(() => {});
  6437. discoveryApi.stopSubnetScan().catch(() => {});
  6438. };
  6439. }, []);
  6440. // Close on Escape key
  6441. useEffect(() => {
  6442. const handleKeyDown = (e: KeyboardEvent) => {
  6443. if (e.key === 'Escape') onClose();
  6444. };
  6445. window.addEventListener('keydown', handleKeyDown);
  6446. return () => window.removeEventListener('keydown', handleKeyDown);
  6447. }, [onClose]);
  6448. return (
  6449. <>
  6450. <div
  6451. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6452. onClick={onClose}
  6453. >
  6454. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6455. <CardContent>
  6456. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  6457. {/* Discovery Section */}
  6458. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  6459. {/* Subnet picker — always visible. The dropdown lists detected
  6460. interface subnets and a "Custom..." sentinel that reveals
  6461. a CIDR text input for printers on a different L3 segment
  6462. (router, VLAN, etc.). #1564 */}
  6463. <div className="mb-3">
  6464. <label className="block text-sm text-bambu-gray mb-1">
  6465. {t('printers.discovery.subnetToScan')}
  6466. </label>
  6467. {detectedSubnets.length > 0 ? (
  6468. <select
  6469. 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"
  6470. value={useCustomSubnet ? '__custom__' : subnet}
  6471. onChange={(e) => {
  6472. if (e.target.value === '__custom__') {
  6473. setUseCustomSubnet(true);
  6474. } else {
  6475. setUseCustomSubnet(false);
  6476. setSubnet(e.target.value);
  6477. }
  6478. }}
  6479. disabled={discovering}
  6480. >
  6481. {detectedSubnets.map(s => (
  6482. <option key={s} value={s}>{s}</option>
  6483. ))}
  6484. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  6485. </select>
  6486. ) : (
  6487. <input
  6488. type="text"
  6489. 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"
  6490. value={subnet}
  6491. onChange={(e) => setSubnet(e.target.value)}
  6492. placeholder="192.168.1.0/24"
  6493. disabled={discovering}
  6494. />
  6495. )}
  6496. {useCustomSubnet && (
  6497. <input
  6498. type="text"
  6499. aria-label={t('printers.discovery.customSubnetLabel')}
  6500. 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"
  6501. value={customSubnet}
  6502. onChange={(e) => setCustomSubnet(e.target.value)}
  6503. placeholder="10.1.1.0/24"
  6504. disabled={discovering}
  6505. />
  6506. )}
  6507. <p className="mt-1 text-xs text-bambu-gray">
  6508. {isDocker
  6509. ? t('printers.discovery.dockerNote')
  6510. : t('printers.discovery.customSubnetNote')}
  6511. </p>
  6512. </div>
  6513. <Button
  6514. type="button"
  6515. variant="secondary"
  6516. onClick={startDiscovery}
  6517. disabled={discovering}
  6518. className="w-full"
  6519. >
  6520. {discovering ? (
  6521. <>
  6522. <Loader2 className="w-4 h-4 animate-spin" />
  6523. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  6524. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  6525. : t('printers.discovery.scanning')}
  6526. </>
  6527. ) : (
  6528. <>
  6529. <Search className="w-4 h-4" />
  6530. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  6531. </>
  6532. )}
  6533. </Button>
  6534. {discoveryError && (
  6535. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  6536. )}
  6537. {newPrinters.length > 0 && (
  6538. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  6539. {newPrinters.map((printer) => (
  6540. <div
  6541. key={printer.serial}
  6542. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  6543. onClick={() => selectPrinter(printer)}
  6544. >
  6545. <div className="min-w-0 flex-1">
  6546. <p className="font-medium text-white text-sm truncate">
  6547. {printer.name || printer.serial}
  6548. </p>
  6549. <p className="text-xs text-bambu-gray truncate">
  6550. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  6551. {printer.serial.startsWith('unknown-') && (
  6552. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  6553. )}
  6554. </p>
  6555. </div>
  6556. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  6557. </div>
  6558. ))}
  6559. </div>
  6560. )}
  6561. {discovering && (
  6562. <p className="mt-2 text-sm text-bambu-gray text-center">
  6563. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  6564. </p>
  6565. )}
  6566. {hasScanned && !discovering && discovered.length === 0 && (
  6567. <p className="mt-2 text-sm text-bambu-gray text-center">
  6568. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  6569. </p>
  6570. )}
  6571. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  6572. <p className="mt-2 text-sm text-bambu-gray text-center">
  6573. {t('printers.discovery.allConfigured')}
  6574. </p>
  6575. )}
  6576. </div>
  6577. <form onSubmit={handleAddSubmit} className="space-y-4">
  6578. <div>
  6579. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6580. <input
  6581. type="text"
  6582. required
  6583. 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"
  6584. value={form.name}
  6585. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6586. placeholder={t('printers.modal.myPrinter')}
  6587. />
  6588. </div>
  6589. <div>
  6590. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6591. <input
  6592. type="text"
  6593. required
  6594. 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])?)*)"
  6595. 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"
  6596. value={form.ip_address}
  6597. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6598. placeholder="192.168.1.100 or printer.local"
  6599. />
  6600. </div>
  6601. <div>
  6602. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6603. <input
  6604. type="text"
  6605. required
  6606. 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"
  6607. value={form.serial_number}
  6608. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  6609. placeholder="01P00A000000000"
  6610. />
  6611. </div>
  6612. <div>
  6613. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6614. <input
  6615. type="password"
  6616. required
  6617. 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"
  6618. value={form.access_code}
  6619. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6620. placeholder={t('printers.modal.fromPrinterSettings')}
  6621. />
  6622. </div>
  6623. <div>
  6624. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  6625. <select
  6626. 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"
  6627. value={form.model || ''}
  6628. onChange={(e) => setForm({ ...form, model: e.target.value })}
  6629. >
  6630. <option value="">{t('printers.modal.selectModel')}</option>
  6631. <optgroup label="A1 Series">
  6632. <option value="A1">A1</option>
  6633. <option value="A1 Mini">A1 Mini</option>
  6634. </optgroup>
  6635. <optgroup label="A2 Series">
  6636. <option value="A2L">A2L</option>
  6637. </optgroup>
  6638. <optgroup label="H2 Series">
  6639. <option value="H2C">H2C</option>
  6640. <option value="H2D">H2D</option>
  6641. <option value="H2D Pro">H2D Pro</option>
  6642. <option value="H2S">H2S</option>
  6643. </optgroup>
  6644. <optgroup label="P Series">
  6645. <option value="P1P">P1P</option>
  6646. <option value="P1S">P1S</option>
  6647. <option value="P2S">P2S</option>
  6648. </optgroup>
  6649. <optgroup label="X1 Series">
  6650. <option value="X1">X1</option>
  6651. <option value="X1C">X1 Carbon</option>
  6652. <option value="X1E">X1E</option>
  6653. </optgroup>
  6654. <optgroup label="X2 Series">
  6655. <option value="X2D">X2D</option>
  6656. </optgroup>
  6657. </select>
  6658. </div>
  6659. <div>
  6660. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  6661. <input
  6662. type="text"
  6663. 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"
  6664. value={form.location || ''}
  6665. onChange={(e) => setForm({ ...form, location: e.target.value })}
  6666. placeholder={t('printers.modal.locationPlaceholder')}
  6667. />
  6668. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  6669. </div>
  6670. <div className="flex items-center gap-2">
  6671. <input
  6672. type="checkbox"
  6673. id="auto_archive"
  6674. checked={form.auto_archive}
  6675. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  6676. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  6677. />
  6678. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  6679. {t('printers.modal.autoArchiveLabel')}
  6680. </label>
  6681. </div>
  6682. <button
  6683. type="button"
  6684. onClick={() => setShowDiagnostic(true)}
  6685. disabled={!form.ip_address.trim()}
  6686. 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"
  6687. >
  6688. <Stethoscope className="w-4 h-4" />
  6689. {t('diagnostic.runButton')}
  6690. </button>
  6691. {saveWarning ? (
  6692. <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">
  6693. <div className="flex items-start gap-2">
  6694. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  6695. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  6696. </div>
  6697. <DiagnosticChecklist result={saveWarning} />
  6698. <div className="flex gap-3">
  6699. <Button
  6700. type="button"
  6701. variant="secondary"
  6702. onClick={() => setSaveWarning(null)}
  6703. className="flex-1"
  6704. >
  6705. {t('printers.addPreflight.back')}
  6706. </Button>
  6707. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  6708. {t('printers.addPreflight.saveAnyway')}
  6709. </Button>
  6710. </div>
  6711. </div>
  6712. ) : (
  6713. <div className="flex gap-3 pt-2">
  6714. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  6715. {t('common.cancel')}
  6716. </Button>
  6717. <Button type="submit" disabled={checkingSave} className="flex-1">
  6718. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  6719. </Button>
  6720. </div>
  6721. )}
  6722. </form>
  6723. </CardContent>
  6724. </Card>
  6725. </div>
  6726. {showDiagnostic && (
  6727. <ConnectionDiagnosticModal
  6728. connection={{
  6729. ip_address: form.ip_address.trim(),
  6730. serial_number: form.serial_number.trim() || undefined,
  6731. access_code: form.access_code || undefined,
  6732. }}
  6733. printerName={form.name || null}
  6734. onClose={() => setShowDiagnostic(false)}
  6735. />
  6736. )}
  6737. </>
  6738. );
  6739. }
  6740. function FirmwareUpdateModal({
  6741. printer,
  6742. firmwareInfo,
  6743. onClose,
  6744. }: {
  6745. printer: Printer;
  6746. firmwareInfo: FirmwareUpdateInfo;
  6747. onClose: () => void;
  6748. }) {
  6749. const { t } = useTranslation();
  6750. const queryClient = useQueryClient();
  6751. const { showToast } = useToast();
  6752. const { hasPermission } = useAuth();
  6753. const canUpdate = hasPermission('firmware:update');
  6754. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  6755. const [isUploading, setIsUploading] = useState(false);
  6756. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  6757. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  6758. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  6759. );
  6760. // Prepare check query — runs when a version is selected and user can update
  6761. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  6762. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  6763. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  6764. staleTime: 30000,
  6765. enabled: !!selectedVersion && canUpdate && !isUploading,
  6766. });
  6767. // Start upload mutation
  6768. const uploadMutation = useMutation({
  6769. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  6770. onSuccess: () => {
  6771. setIsUploading(true);
  6772. // Start polling for status
  6773. const interval = setInterval(async () => {
  6774. try {
  6775. const status = await firmwareApi.getUploadStatus(printer.id);
  6776. setUploadStatus(status);
  6777. if (status.status === 'complete' || status.status === 'error') {
  6778. clearInterval(interval);
  6779. setPollInterval(null);
  6780. setIsUploading(false);
  6781. if (status.status === 'complete') {
  6782. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  6783. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  6784. }
  6785. }
  6786. } catch {
  6787. // Ignore errors during polling
  6788. }
  6789. }, 2000);
  6790. setPollInterval(interval);
  6791. },
  6792. onError: (error: Error) => {
  6793. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  6794. setIsUploading(false);
  6795. },
  6796. });
  6797. // Cleanup on unmount
  6798. useEffect(() => {
  6799. return () => {
  6800. if (pollInterval) clearInterval(pollInterval);
  6801. };
  6802. }, [pollInterval]);
  6803. const handleStartUpload = () => {
  6804. setUploadStatus(null);
  6805. uploadMutation.mutate();
  6806. };
  6807. return (
  6808. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  6809. <Card className="w-full max-w-md mx-4">
  6810. <CardContent>
  6811. <div className="flex items-start gap-3 mb-4">
  6812. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  6813. {firmwareInfo.update_available
  6814. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  6815. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  6816. </div>
  6817. <div className="flex-1">
  6818. <h3 className="text-lg font-semibold text-white">
  6819. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  6820. </h3>
  6821. <p className="text-sm text-bambu-gray mt-1">
  6822. {printer.name}
  6823. </p>
  6824. </div>
  6825. </div>
  6826. {/* Version Info */}
  6827. {(() => {
  6828. const selectedEntry = selectedVersion
  6829. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  6830. : null;
  6831. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  6832. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  6833. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  6834. return (
  6835. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  6836. <div className="flex justify-between items-center text-sm">
  6837. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  6838. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  6839. {firmwareInfo.current_version || t('common.unknown')}
  6840. </span>
  6841. </div>
  6842. {showSecondLine && (
  6843. <div className="flex justify-between items-center text-sm mt-1">
  6844. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  6845. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  6846. </div>
  6847. )}
  6848. {displayNotes && (
  6849. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  6850. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  6851. {t('printers.firmwareModal.releaseNotes')}
  6852. </summary>
  6853. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  6854. {displayNotes}
  6855. </div>
  6856. </details>
  6857. )}
  6858. </div>
  6859. );
  6860. })()}
  6861. {/* Available versions list */}
  6862. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  6863. <div className="mb-4">
  6864. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  6865. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  6866. {firmwareInfo.available_versions.map((v) => {
  6867. const isCurrent = firmwareInfo.current_version === v.version;
  6868. const isSelected = selectedVersion === v.version;
  6869. const cmp = firmwareInfo.current_version
  6870. ? compareFwVersions(v.version, firmwareInfo.current_version)
  6871. : 0;
  6872. const relLabel = isCurrent
  6873. ? t('printers.firmwareModal.currentBadge')
  6874. : cmp > 0
  6875. ? t('printers.firmwareModal.newerBadge')
  6876. : t('printers.firmwareModal.olderBadge');
  6877. const relClass = isCurrent
  6878. ? 'text-bambu-gray'
  6879. : cmp > 0
  6880. ? 'text-orange-700 dark:text-orange-400'
  6881. : 'text-blue-700 dark:text-blue-400';
  6882. return (
  6883. <button
  6884. key={v.version}
  6885. type="button"
  6886. disabled={!v.file_available || !canUpdate || isCurrent}
  6887. onClick={() => setSelectedVersion(v.version)}
  6888. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  6889. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  6890. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  6891. >
  6892. <div className="flex items-center gap-2 min-w-0">
  6893. <span className="font-mono text-white">{v.version}</span>
  6894. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  6895. </div>
  6896. <span className={`text-xs px-2 py-0.5 rounded-full ${
  6897. isCurrent
  6898. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  6899. : v.file_available
  6900. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  6901. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  6902. }`}>
  6903. {isCurrent
  6904. ? t('printers.firmwareModal.installed')
  6905. : v.file_available
  6906. ? t('printers.firmwareModal.usable')
  6907. : t('printers.firmwareModal.unavailable')}
  6908. </span>
  6909. </button>
  6910. );
  6911. })}
  6912. </div>
  6913. </div>
  6914. )}
  6915. {/* Status / Progress (only when a version is selected) */}
  6916. {!selectedVersion ? null : isPreparing ? (
  6917. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  6918. <Loader2 className="w-4 h-4 animate-spin" />
  6919. {t('printers.firmwareModal.checkingPrereqs')}
  6920. </div>
  6921. ) : prepareInfo && !isUploading && !uploadStatus ? (
  6922. <div className="mb-4">
  6923. {prepareInfo.can_proceed ? (
  6924. <div className="flex items-center gap-2 text-bambu-green text-sm">
  6925. <Box className="w-4 h-4" />
  6926. {t('printers.firmwareModal.sdCardReady')}
  6927. </div>
  6928. ) : (
  6929. <div className="space-y-1">
  6930. {prepareInfo.errors.map((error, i) => (
  6931. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  6932. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  6933. {error}
  6934. </div>
  6935. ))}
  6936. </div>
  6937. )}
  6938. </div>
  6939. ) : null}
  6940. {/* Upload Progress */}
  6941. {(isUploading || uploadStatus) && uploadStatus && (
  6942. <div className="mb-4">
  6943. <div className="flex items-center justify-between text-sm mb-1">
  6944. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  6945. <span className="text-white">{uploadStatus.progress}%</span>
  6946. </div>
  6947. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  6948. <div
  6949. className={`h-2 rounded-full transition-all ${
  6950. uploadStatus.status === 'error' ? 'bg-status-error' :
  6951. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  6952. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  6953. style={{ width: `${uploadStatus.progress}%` }}
  6954. />
  6955. </div>
  6956. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  6957. {uploadStatus.error && (
  6958. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  6959. )}
  6960. </div>
  6961. )}
  6962. {/* Success Message */}
  6963. {uploadStatus?.status === 'complete' && (
  6964. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  6965. <p className="text-sm text-bambu-green font-medium mb-2">
  6966. {t('printers.firmwareModal.uploadedSuccess')}
  6967. </p>
  6968. <p className="text-xs text-bambu-gray">
  6969. {t('printers.firmwareModal.applyInstructions')}
  6970. </p>
  6971. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  6972. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  6973. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  6974. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  6975. <li>{t('printers.firmwareModal.step4')}</li>
  6976. </ol>
  6977. </div>
  6978. )}
  6979. {/* Buttons */}
  6980. <div className="flex gap-2 justify-end">
  6981. <Button variant="secondary" onClick={onClose}>
  6982. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  6983. </Button>
  6984. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  6985. <Button
  6986. onClick={handleStartUpload}
  6987. disabled={uploadMutation.isPending}
  6988. >
  6989. {uploadMutation.isPending ? (
  6990. <>
  6991. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  6992. {t('printers.firmwareModal.starting')}
  6993. </>
  6994. ) : (
  6995. <>
  6996. <Download className="w-4 h-4 mr-2" />
  6997. {t('printers.firmwareModal.uploadFirmware')}
  6998. </>
  6999. )}
  7000. </Button>
  7001. )}
  7002. </div>
  7003. </CardContent>
  7004. </Card>
  7005. </div>
  7006. );
  7007. }
  7008. function EditPrinterModal({
  7009. printer,
  7010. onClose,
  7011. }: {
  7012. printer: Printer;
  7013. onClose: () => void;
  7014. }) {
  7015. const { t } = useTranslation();
  7016. const queryClient = useQueryClient();
  7017. const { showToast } = useToast();
  7018. const [form, setForm] = useState({
  7019. name: printer.name,
  7020. ip_address: printer.ip_address,
  7021. access_code: '',
  7022. model: printer.model || '',
  7023. location: printer.location || '',
  7024. auto_archive: printer.auto_archive,
  7025. is_active: printer.is_active,
  7026. });
  7027. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  7028. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  7029. const [checkingSave, setCheckingSave] = useState(false);
  7030. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7031. const updateMutation = useMutation({
  7032. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  7033. onSuccess: () => {
  7034. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7035. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7036. onClose();
  7037. },
  7038. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  7039. });
  7040. // Close on Escape key
  7041. useEffect(() => {
  7042. const handleKeyDown = (e: KeyboardEvent) => {
  7043. if (e.key === 'Escape') onClose();
  7044. };
  7045. window.addEventListener('keydown', handleKeyDown);
  7046. return () => window.removeEventListener('keydown', handleKeyDown);
  7047. }, [onClose]);
  7048. const doSave = () => {
  7049. const data: Partial<PrinterCreate> = {
  7050. name: form.name,
  7051. ip_address: form.ip_address,
  7052. model: form.model || undefined,
  7053. location: form.location || undefined,
  7054. auto_archive: form.auto_archive,
  7055. is_active: form.is_active,
  7056. };
  7057. // Only include access_code if it was changed
  7058. if (form.access_code) {
  7059. data.access_code = form.access_code;
  7060. }
  7061. updateMutation.mutate(data);
  7062. };
  7063. const handleSubmit = async (e: React.FormEvent) => {
  7064. e.preventDefault();
  7065. setCheckingSave(true);
  7066. try {
  7067. const result = await api.diagnoseConnection({
  7068. ip_address: form.ip_address.trim(),
  7069. serial_number: printer.serial_number,
  7070. access_code: form.access_code || undefined,
  7071. });
  7072. if (result.checks.some((c) => c.status === 'fail')) {
  7073. setSaveWarning(result);
  7074. return;
  7075. }
  7076. } catch {
  7077. // Diagnostic infrastructure failed — never block the save on it.
  7078. } finally {
  7079. setCheckingSave(false);
  7080. }
  7081. doSave();
  7082. };
  7083. return (
  7084. <div
  7085. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7086. onClick={onClose}
  7087. >
  7088. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7089. <CardContent>
  7090. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  7091. <form onSubmit={handleSubmit} className="space-y-4">
  7092. <div>
  7093. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7094. <input
  7095. type="text"
  7096. required
  7097. 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"
  7098. value={form.name}
  7099. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7100. placeholder={t('printers.modal.myPrinter')}
  7101. />
  7102. </div>
  7103. <div>
  7104. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7105. <input
  7106. type="text"
  7107. required
  7108. 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])?)*)"
  7109. 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"
  7110. value={form.ip_address}
  7111. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7112. placeholder="192.168.1.100 or printer.local"
  7113. />
  7114. </div>
  7115. <div>
  7116. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7117. <input
  7118. type="text"
  7119. disabled
  7120. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  7121. value={printer.serial_number}
  7122. />
  7123. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  7124. </div>
  7125. <div>
  7126. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7127. <input
  7128. type="password"
  7129. 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"
  7130. value={form.access_code}
  7131. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7132. placeholder={t('printers.accessCodePlaceholder')}
  7133. />
  7134. </div>
  7135. <div>
  7136. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7137. <select
  7138. 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"
  7139. value={form.model}
  7140. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7141. >
  7142. <option value="">{t('printers.modal.selectModel')}</option>
  7143. <optgroup label="A1 Series">
  7144. <option value="A1">A1</option>
  7145. <option value="A1 Mini">A1 Mini</option>
  7146. </optgroup>
  7147. <optgroup label="A2 Series">
  7148. <option value="A2L">A2L</option>
  7149. </optgroup>
  7150. <optgroup label="H2 Series">
  7151. <option value="H2C">H2C</option>
  7152. <option value="H2D">H2D</option>
  7153. <option value="H2D Pro">H2D Pro</option>
  7154. <option value="H2S">H2S</option>
  7155. </optgroup>
  7156. <optgroup label="P Series">
  7157. <option value="P1P">P1P</option>
  7158. <option value="P1S">P1S</option>
  7159. <option value="P2S">P2S</option>
  7160. </optgroup>
  7161. <optgroup label="X1 Series">
  7162. <option value="X1">X1</option>
  7163. <option value="X1C">X1 Carbon</option>
  7164. <option value="X1E">X1E</option>
  7165. </optgroup>
  7166. <optgroup label="X2 Series">
  7167. <option value="X2D">X2D</option>
  7168. </optgroup>
  7169. </select>
  7170. </div>
  7171. <div>
  7172. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7173. <input
  7174. type="text"
  7175. 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"
  7176. value={form.location}
  7177. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7178. placeholder={t('printers.modal.locationPlaceholder')}
  7179. />
  7180. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7181. </div>
  7182. <div className="flex items-center gap-2">
  7183. <input
  7184. type="checkbox"
  7185. id="edit_auto_archive"
  7186. checked={form.auto_archive}
  7187. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7188. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7189. />
  7190. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7191. {t('printers.modal.autoArchiveLabel')}
  7192. </label>
  7193. </div>
  7194. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7195. is_active because the user-facing concept is "is this printer
  7196. in maintenance" not "is it active". */}
  7197. <div>
  7198. <div className="flex items-center gap-2">
  7199. <input
  7200. type="checkbox"
  7201. id="edit_maintenance_mode"
  7202. checked={!form.is_active}
  7203. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  7204. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  7205. />
  7206. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  7207. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  7208. {t('printers.maintenance.editFieldLabel')}
  7209. </label>
  7210. </div>
  7211. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  7212. {t('printers.maintenance.editFieldHelp')}
  7213. </p>
  7214. </div>
  7215. {saveWarning ? (
  7216. <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">
  7217. <div className="flex items-start gap-2">
  7218. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7219. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7220. </div>
  7221. <DiagnosticChecklist result={saveWarning} />
  7222. <div className="flex gap-3">
  7223. <Button
  7224. type="button"
  7225. variant="secondary"
  7226. onClick={() => setSaveWarning(null)}
  7227. className="flex-1"
  7228. >
  7229. {t('printers.addPreflight.back')}
  7230. </Button>
  7231. <Button
  7232. type="button"
  7233. onClick={doSave}
  7234. className="flex-1"
  7235. disabled={updateMutation.isPending}
  7236. >
  7237. {t('printers.addPreflight.saveAnyway')}
  7238. </Button>
  7239. </div>
  7240. </div>
  7241. ) : (
  7242. <div className="flex gap-3 pt-4">
  7243. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7244. {t('common.cancel')}
  7245. </Button>
  7246. <Button
  7247. type="submit"
  7248. className="flex-1"
  7249. disabled={updateMutation.isPending || checkingSave}
  7250. >
  7251. {checkingSave
  7252. ? t('printers.addPreflight.checking')
  7253. : updateMutation.isPending
  7254. ? t('common.saving')
  7255. : t('printers.modal.saveChanges')}
  7256. </Button>
  7257. </div>
  7258. )}
  7259. </form>
  7260. </CardContent>
  7261. </Card>
  7262. </div>
  7263. );
  7264. }
  7265. // Component to check if a printer is offline (for power dropdown)
  7266. function usePrinterOfflineStatus(printerId: number) {
  7267. const { data: status } = useQuery({
  7268. queryKey: ['printerStatus', printerId],
  7269. queryFn: () => api.getPrinterStatus(printerId),
  7270. refetchInterval: 30000,
  7271. });
  7272. return !status?.connected;
  7273. }
  7274. // Power dropdown item for an offline printer
  7275. function PowerDropdownItem({
  7276. printer,
  7277. plug,
  7278. onPowerOn,
  7279. isPowering,
  7280. }: {
  7281. printer: Printer;
  7282. plug: { id: number; name: string };
  7283. onPowerOn: (plugId: number) => void;
  7284. isPowering: boolean;
  7285. }) {
  7286. const isOffline = usePrinterOfflineStatus(printer.id);
  7287. // Fetch plug status
  7288. const { data: plugStatus } = useQuery({
  7289. queryKey: ['smartPlugStatus', plug.id],
  7290. queryFn: () => api.getSmartPlugStatus(plug.id),
  7291. refetchInterval: 10000,
  7292. });
  7293. // Only show if printer is offline
  7294. if (!isOffline) {
  7295. return null;
  7296. }
  7297. return (
  7298. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  7299. <div className="flex items-center gap-2 min-w-0">
  7300. <span className="text-sm text-white truncate">{printer.name}</span>
  7301. {plugStatus && (
  7302. <span
  7303. className={`text-xs px-1.5 py-0.5 rounded ${
  7304. plugStatus.state === 'ON'
  7305. ? 'bg-bambu-green/20 text-bambu-green'
  7306. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  7307. }`}
  7308. >
  7309. {plugStatus.state || '?'}
  7310. </span>
  7311. )}
  7312. </div>
  7313. <button
  7314. onClick={() => onPowerOn(plug.id)}
  7315. disabled={isPowering || plugStatus?.state === 'ON'}
  7316. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  7317. plugStatus?.state === 'ON'
  7318. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  7319. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  7320. }`}
  7321. >
  7322. <Power className="w-3 h-3" />
  7323. {isPowering ? '...' : 'On'}
  7324. </button>
  7325. </div>
  7326. );
  7327. }
  7328. export function PrintersPage() {
  7329. const { t } = useTranslation();
  7330. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  7331. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  7332. const accentButtonClass = {
  7333. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  7334. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  7335. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  7336. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  7337. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  7338. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  7339. }[activeAccent];
  7340. const [showAddModal, setShowAddModal] = useState(false);
  7341. const [hideDisconnected, setHideDisconnected] = useState(() => {
  7342. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  7343. });
  7344. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  7345. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  7346. const [sortBy, setSortBy] = useState<SortOption>(() => {
  7347. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  7348. });
  7349. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  7350. return localStorage.getItem('printerSortAsc') !== 'false';
  7351. });
  7352. // Card size: 1=small, 2=medium, 3=large, 4=xl
  7353. const [cardSize, setCardSize] = useState<number>(() => {
  7354. const saved = localStorage.getItem('printerCardSize');
  7355. return saved ? parseInt(saved, 10) : 2; // Default to medium
  7356. });
  7357. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  7358. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  7359. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  7360. });
  7361. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  7362. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  7363. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  7364. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  7365. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  7366. });
  7367. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  7368. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  7369. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  7370. });
  7371. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  7372. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  7373. // Defaulting to 'full' because the cards already show this info — users who
  7374. // pick cam-wall view still want to glance the same details without flipping.
  7375. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  7376. const saved = localStorage.getItem('camWallStatusMode');
  7377. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  7378. });
  7379. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  7380. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  7381. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  7382. const scrollPrinterIntoView = useCallback((printerId: number) => {
  7383. requestAnimationFrame(() => {
  7384. requestAnimationFrame(() => {
  7385. const card = document.getElementById(`printer-card-${printerId}`);
  7386. if (!card) return;
  7387. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  7388. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  7389. window.scrollTo({
  7390. top: Math.max(0, top),
  7391. behavior: 'smooth',
  7392. });
  7393. });
  7394. });
  7395. }, []);
  7396. const openCompactCard = useCallback((printerId: number) => {
  7397. setCompactDrilldownPrinterId(printerId);
  7398. setCardSize(2);
  7399. localStorage.setItem('printerCardSize', '2');
  7400. scrollPrinterIntoView(printerId);
  7401. }, [scrollPrinterIntoView]);
  7402. const returnToCompactCards = useCallback(() => {
  7403. const printerId = compactDrilldownPrinterId;
  7404. setCompactDrilldownPrinterId(null);
  7405. setCardSize(1);
  7406. localStorage.setItem('printerCardSize', '1');
  7407. if (printerId != null) {
  7408. scrollPrinterIntoView(printerId);
  7409. }
  7410. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  7411. const [search, setSearch] = useState('');
  7412. const [statusFilter, setStatusFilter] = useState<string>('all');
  7413. const [locationFilter, setLocationFilter] = useState<string>('all');
  7414. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  7415. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  7416. try {
  7417. const saved = localStorage.getItem('printerCollapsedSections');
  7418. return saved ? JSON.parse(saved) : {};
  7419. } catch { return {}; }
  7420. });
  7421. const queryClient = useQueryClient();
  7422. const { showToast } = useToast();
  7423. const { hasPermission } = useAuth();
  7424. // Embedded camera viewer state - supports multiple simultaneous viewers
  7425. // Persisted to localStorage so cameras reopen after navigation
  7426. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  7427. // Initialize from localStorage if camera_view_mode is embedded
  7428. const saved = localStorage.getItem('openEmbeddedCameras');
  7429. if (saved) {
  7430. try {
  7431. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  7432. return new Map(cameras.map(c => [c.id, c]));
  7433. } catch {
  7434. return new Map();
  7435. }
  7436. }
  7437. return new Map();
  7438. });
  7439. // Persist open cameras to localStorage when they change
  7440. useEffect(() => {
  7441. const cameras = Array.from(embeddedCameraPrinters.values());
  7442. if (cameras.length > 0) {
  7443. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  7444. } else {
  7445. localStorage.removeItem('openEmbeddedCameras');
  7446. }
  7447. }, [embeddedCameraPrinters]);
  7448. const { data: printers, isLoading } = useQuery({
  7449. queryKey: ['printers'],
  7450. queryFn: api.getPrinters,
  7451. });
  7452. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  7453. // so users with printers:read but no settings:read still get the values needed
  7454. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  7455. const { data: settings } = useQuery({
  7456. queryKey: ['ui-preferences'],
  7457. queryFn: api.getUiPreferences,
  7458. });
  7459. // Parse user-configured temperature/fan presets once, with defensive fallback
  7460. // to built-in defaults on parse failure (validators on the backend already
  7461. // reject malformed writes, so this is just forward-compat).
  7462. const effectiveNozzleTempPresets = useMemo(
  7463. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  7464. [settings?.nozzle_temp_presets],
  7465. );
  7466. const effectiveBedTempPresets = useMemo(
  7467. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  7468. [settings?.bed_temp_presets],
  7469. );
  7470. const effectiveChamberTempPresets = useMemo(
  7471. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, 60),
  7472. [settings?.chamber_temp_presets],
  7473. );
  7474. const effectiveFanSpeedPresets = useMemo(
  7475. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  7476. [settings?.fan_speed_presets],
  7477. );
  7478. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  7479. const effectiveDryingPresets = useMemo(() => {
  7480. if (settings?.drying_presets) {
  7481. try {
  7482. const userPresets = JSON.parse(settings.drying_presets);
  7483. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  7484. return { ...DRYING_PRESETS, ...userPresets };
  7485. }
  7486. } catch { /* ignore parse errors, use defaults */ }
  7487. }
  7488. return DRYING_PRESETS;
  7489. }, [settings?.drying_presets]);
  7490. // Close embedded cameras if mode changes to 'window'
  7491. useEffect(() => {
  7492. if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
  7493. setEmbeddedCameraPrinters(new Map());
  7494. }
  7495. }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
  7496. // Fetch all smart plugs to know which printers have them
  7497. const { data: smartPlugs } = useQuery({
  7498. queryKey: ['smart-plugs'],
  7499. queryFn: api.getSmartPlugs,
  7500. });
  7501. // Fetch maintenance overview for all printers to show badges
  7502. const { data: maintenanceOverview } = useQuery({
  7503. queryKey: ['maintenanceOverview'],
  7504. queryFn: api.getMaintenanceOverview,
  7505. staleTime: 60 * 1000, // 1 minute
  7506. });
  7507. // Fetch Spoolman status to enable link spool feature
  7508. const { data: spoolmanStatus } = useQuery({
  7509. queryKey: ['spoolman-status'],
  7510. queryFn: api.getSpoolmanStatus,
  7511. staleTime: 60 * 1000, // 1 minute
  7512. });
  7513. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  7514. // Fetch Spoolman settings to get sync mode
  7515. const { data: spoolmanSettings } = useQuery({
  7516. queryKey: ['spoolman-settings'],
  7517. queryFn: api.getSpoolmanSettings,
  7518. enabled: !!spoolmanEnabled,
  7519. staleTime: 60 * 1000, // 1 minute
  7520. });
  7521. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  7522. // Fetch unlinked spools to know if link button should be enabled
  7523. const { data: unlinkedSpools } = useQuery({
  7524. queryKey: ['unlinked-spools'],
  7525. queryFn: api.getUnlinkedSpools,
  7526. enabled: !!spoolmanEnabled,
  7527. staleTime: 30 * 1000, // 30 seconds
  7528. });
  7529. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  7530. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  7531. const { data: linkedSpoolsData } = useQuery({
  7532. queryKey: ['linked-spools'],
  7533. queryFn: api.getLinkedSpools,
  7534. enabled: !!spoolmanEnabled,
  7535. staleTime: 30 * 1000, // 30 seconds
  7536. });
  7537. const linkedSpools = linkedSpoolsData?.linked;
  7538. // Fetch spool assignments for inventory feature
  7539. const { data: spoolAssignments } = useQuery({
  7540. queryKey: ['spool-assignments'],
  7541. queryFn: () => api.getAssignments(),
  7542. enabled: hasPermission('inventory:view_assignments'),
  7543. staleTime: 30 * 1000,
  7544. });
  7545. const unassignMutation = useMutation({
  7546. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  7547. api.unassignSpool(printerId, amsId, trayId),
  7548. onSuccess: () => {
  7549. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  7550. },
  7551. });
  7552. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  7553. queryKey: ['spoolman-inventory-spools'],
  7554. queryFn: () => api.getSpoolmanInventorySpools(false),
  7555. enabled: !!spoolmanEnabled,
  7556. staleTime: 30 * 1000,
  7557. });
  7558. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  7559. queryKey: ['spoolman-slot-assignments'],
  7560. queryFn: () => api.getSpoolmanSlotAssignments(),
  7561. enabled: !!spoolmanEnabled,
  7562. staleTime: 30 * 1000,
  7563. });
  7564. const unassignSpoolmanMutation = useMutation({
  7565. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  7566. onSuccess: () => {
  7567. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  7568. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  7569. },
  7570. });
  7571. // Helper to find assignment for a specific slot
  7572. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  7573. return spoolAssignments?.find(
  7574. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  7575. );
  7576. };
  7577. // Create a map of printer_id -> maintenance info for quick lookup
  7578. const maintenanceByPrinter = maintenanceOverview?.reduce(
  7579. (acc, overview) => {
  7580. acc[overview.printer_id] = {
  7581. due_count: overview.due_count,
  7582. warning_count: overview.warning_count,
  7583. total_print_hours: overview.total_print_hours,
  7584. };
  7585. return acc;
  7586. },
  7587. {} as Record<number, PrinterMaintenanceInfo>
  7588. ) || {};
  7589. // Create a map of printer_id -> smart plug
  7590. const smartPlugByPrinter = smartPlugs?.reduce(
  7591. (acc, plug) => {
  7592. if (plug.printer_id) {
  7593. acc[plug.printer_id] = plug;
  7594. }
  7595. return acc;
  7596. },
  7597. {} as Record<number, typeof smartPlugs[0]>
  7598. ) || {};
  7599. const addMutation = useMutation({
  7600. mutationFn: api.createPrinter,
  7601. onSuccess: () => {
  7602. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7603. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  7604. setShowAddModal(false);
  7605. },
  7606. onError: (error: Error) => {
  7607. // Localized message when the backend returns a stable error code;
  7608. // the raw message is an English fallback for non-UI clients.
  7609. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  7610. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  7611. return;
  7612. }
  7613. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  7614. },
  7615. });
  7616. const powerOnMutation = useMutation({
  7617. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  7618. onSuccess: () => {
  7619. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  7620. setPoweringOn(null);
  7621. },
  7622. onError: () => {
  7623. setPoweringOn(null);
  7624. },
  7625. });
  7626. // Bulk selection state
  7627. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  7628. const [isSelectionMode, setIsSelectionMode] = useState(false);
  7629. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  7630. const [bulkActionPending, setBulkActionPending] = useState(false);
  7631. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  7632. const toggleSelect = useCallback((id: number) => {
  7633. setSelectedPrinterIds(prev => {
  7634. const next = new Set(prev);
  7635. if (next.has(id)) next.delete(id);
  7636. else next.add(id);
  7637. return next;
  7638. });
  7639. }, []);
  7640. const clearSelection = useCallback(() => {
  7641. setSelectedPrinterIds(new Set());
  7642. setIsSelectionMode(false);
  7643. }, []);
  7644. // Escape key exits selection mode
  7645. useEffect(() => {
  7646. const handleKeyDown = (e: KeyboardEvent) => {
  7647. if (e.key === 'Escape' && selectionMode) {
  7648. clearSelection();
  7649. }
  7650. };
  7651. window.addEventListener('keydown', handleKeyDown);
  7652. return () => window.removeEventListener('keydown', handleKeyDown);
  7653. }, [selectionMode, clearSelection]);
  7654. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7655. setBulkActionPending(true);
  7656. const ids = Array.from(selectedPrinterIds);
  7657. // Filter to only applicable printers based on cached state
  7658. const applicableIds = ids.filter(id => {
  7659. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  7660. if (!status?.connected) return false;
  7661. switch (action) {
  7662. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  7663. case 'pause': return status.state === 'RUNNING';
  7664. case 'resume': return status.state === 'PAUSE';
  7665. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  7666. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  7667. default: return false;
  7668. }
  7669. });
  7670. if (applicableIds.length === 0) {
  7671. showToast(t('printers.bulk.noneApplicable'), 'error');
  7672. setBulkActionPending(false);
  7673. setBulkConfirmAction(null);
  7674. return;
  7675. }
  7676. const apiCall = {
  7677. stop: api.stopPrint,
  7678. pause: api.pausePrint,
  7679. resume: api.resumePrint,
  7680. clearPlate: api.clearPlate,
  7681. clearHMS: api.clearHMSErrors,
  7682. }[action];
  7683. const results = await Promise.allSettled(
  7684. applicableIds.map(id => apiCall(id))
  7685. );
  7686. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  7687. const failed = results.filter(r => r.status === 'rejected').length;
  7688. if (failed === 0) {
  7689. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  7690. } else {
  7691. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  7692. }
  7693. // Invalidate status queries for affected printers
  7694. applicableIds.forEach(id => {
  7695. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  7696. });
  7697. setBulkActionPending(false);
  7698. setBulkConfirmAction(null);
  7699. }, [selectedPrinterIds, queryClient, showToast, t]);
  7700. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7701. // Actions that need confirmation
  7702. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  7703. setBulkConfirmAction(action);
  7704. } else {
  7705. executeBulkAction(action);
  7706. }
  7707. }, [executeBulkAction]);
  7708. const toggleHideDisconnected = () => {
  7709. const newValue = !hideDisconnected;
  7710. setHideDisconnected(newValue);
  7711. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  7712. };
  7713. const handleSortChange = (newSort: SortOption) => {
  7714. setSortBy(newSort);
  7715. localStorage.setItem('printerSortBy', newSort);
  7716. };
  7717. const toggleSortDirection = () => {
  7718. const newAsc = !sortAsc;
  7719. setSortAsc(newAsc);
  7720. localStorage.setItem('printerSortAsc', String(newAsc));
  7721. };
  7722. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  7723. const getGridClasses = () => {
  7724. switch (cardSize) {
  7725. 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
  7726. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  7727. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  7728. case 4: return 'grid-cols-1'; // XL: single column, full width
  7729. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  7730. }
  7731. };
  7732. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  7733. // Increment version counter whenever a printer status cache entry is updated so
  7734. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  7735. useEffect(() => {
  7736. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  7737. if (
  7738. event.type === 'updated' &&
  7739. Array.isArray(event.query.queryKey) &&
  7740. event.query.queryKey[0] === 'printerStatus'
  7741. ) {
  7742. setStatusCacheVersion(v => v + 1);
  7743. }
  7744. });
  7745. return unsubscribe;
  7746. }, [queryClient]);
  7747. // Filter printers by search term, status, and location
  7748. const filteredPrinters = useMemo(() => {
  7749. if (!printers) return [];
  7750. let result = printers;
  7751. // Text search
  7752. if (search.trim()) {
  7753. const q = search.trim().toLowerCase();
  7754. result = result.filter(p =>
  7755. p.name.toLowerCase().includes(q) ||
  7756. (p.model || '').toLowerCase().includes(q) ||
  7757. (p.location || '').toLowerCase().includes(q) ||
  7758. (p.serial_number || '').toLowerCase().includes(q)
  7759. );
  7760. }
  7761. // Location filter
  7762. if (locationFilter !== 'all') {
  7763. result = result.filter(p => (p.location || '') === locationFilter);
  7764. }
  7765. // Status filter
  7766. if (statusFilter !== 'all') {
  7767. result = result.filter(p => {
  7768. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7769. if (!status?.connected) return statusFilter === 'offline';
  7770. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  7771. switch (statusFilter) {
  7772. case 'printing': return status.state === 'RUNNING';
  7773. case 'paused': return status.state === 'PAUSE';
  7774. case 'finished': return status.state === 'FINISH';
  7775. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  7776. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  7777. case 'offline': return false; // Connected printers are never offline
  7778. default: return true;
  7779. }
  7780. });
  7781. }
  7782. return result;
  7783. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  7784. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  7785. // Derive unique locations for the location filter dropdown
  7786. const availableLocations = useMemo(() => {
  7787. if (!printers) return [];
  7788. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  7789. }, [printers]);
  7790. // Sort printers based on selected option
  7791. const sortedPrinters = useMemo(() => {
  7792. const sorted = [...filteredPrinters];
  7793. switch (sortBy) {
  7794. case 'name':
  7795. sorted.sort((a, b) => a.name.localeCompare(b.name));
  7796. break;
  7797. case 'model':
  7798. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  7799. break;
  7800. case 'location':
  7801. // Sort by location, with ungrouped printers last
  7802. sorted.sort((a, b) => {
  7803. const locA = a.location || '';
  7804. const locB = b.location || '';
  7805. if (!locA && locB) return 1;
  7806. if (locA && !locB) return -1;
  7807. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  7808. });
  7809. break;
  7810. case 'status':
  7811. // Sort by status: HMS errors > printing > idle > offline
  7812. sorted.sort((a, b) => {
  7813. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  7814. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  7815. const getPriority = (s: typeof statusA) => {
  7816. if (!s?.connected) return 3; // offline
  7817. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  7818. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  7819. if (s.state === 'RUNNING') return 1; // printing
  7820. return 2; // idle
  7821. };
  7822. return getPriority(statusA) - getPriority(statusB);
  7823. });
  7824. break;
  7825. case 'eta':
  7826. sorted.sort((a, b) => {
  7827. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  7828. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  7829. const tier = (s: typeof statusA) => {
  7830. if (!s?.connected) return 3; // offline last
  7831. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  7832. if (s.state === 'RUNNING') return 1; // printing without ETA
  7833. return 2; // idle
  7834. };
  7835. const ta = tier(statusA);
  7836. const tb = tier(statusB);
  7837. if (ta !== tb) return ta - tb;
  7838. if (ta === 0) {
  7839. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  7840. if (diff !== 0) return diff;
  7841. }
  7842. return a.name.localeCompare(b.name);
  7843. });
  7844. break;
  7845. }
  7846. // Apply ascending/descending
  7847. if (!sortAsc) {
  7848. sorted.reverse();
  7849. }
  7850. return sorted;
  7851. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  7852. const selectAll = useCallback(() => {
  7853. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  7854. setIsSelectionMode(true);
  7855. }, [sortedPrinters]);
  7856. const selectByState = useCallback((state: PrinterState) => {
  7857. setSelectedPrinterIds(prev => {
  7858. const next = new Set(prev);
  7859. sortedPrinters.forEach(p => {
  7860. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7861. if (classifyPrinterStatus(status) === state) next.add(p.id);
  7862. });
  7863. return next;
  7864. });
  7865. setIsSelectionMode(true);
  7866. }, [sortedPrinters, queryClient]);
  7867. const selectByLocation = useCallback((location: string) => {
  7868. setSelectedPrinterIds(prev => {
  7869. const next = new Set(prev);
  7870. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  7871. return next;
  7872. });
  7873. setIsSelectionMode(true);
  7874. }, [sortedPrinters]);
  7875. const selectByModel = useCallback((model: string) => {
  7876. setSelectedPrinterIds(prev => {
  7877. const next = new Set(prev);
  7878. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  7879. return next;
  7880. });
  7881. setIsSelectionMode(true);
  7882. }, [sortedPrinters]);
  7883. const toggleSectionCollapse = useCallback((key: string) => {
  7884. setCollapsedSections(prev => {
  7885. const next = { ...prev, [key]: !prev[key] };
  7886. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  7887. return next;
  7888. });
  7889. }, []);
  7890. // Group printers when sorted by location, status, or model
  7891. const groupedPrinters = useMemo(() => {
  7892. if (sortBy === 'name' || sortBy === 'eta') return null;
  7893. const groups: Record<string, typeof sortedPrinters> = {};
  7894. if (sortBy === 'location') {
  7895. sortedPrinters.forEach(printer => {
  7896. const location = printer.location || 'Ungrouped';
  7897. if (!groups[location]) groups[location] = [];
  7898. groups[location].push(printer);
  7899. });
  7900. } else if (sortBy === 'model') {
  7901. sortedPrinters.forEach(printer => {
  7902. const model = printer.model || 'Unknown';
  7903. if (!groups[model]) groups[model] = [];
  7904. groups[model].push(printer);
  7905. });
  7906. } else if (sortBy === 'status') {
  7907. sortedPrinters.forEach(printer => {
  7908. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  7909. const group = classifyPrinterStatus(status);
  7910. if (!groups[group]) groups[group] = [];
  7911. groups[group].push(printer);
  7912. });
  7913. }
  7914. return groups;
  7915. // 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
  7916. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  7917. const toolbarRef = useRef<HTMLDivElement>(null);
  7918. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  7919. const expandedToolbarWidthRef = useRef(0);
  7920. const [compactToolbar, setCompactToolbar] = useState(false);
  7921. const measureToolbar = useCallback(() => {
  7922. const toolbar = toolbarRef.current;
  7923. if (!toolbar) return;
  7924. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  7925. if (measuredControlsWidth) {
  7926. expandedToolbarWidthRef.current = measuredControlsWidth;
  7927. }
  7928. const searchMinimumWidth = 220;
  7929. const gapWidth = 8;
  7930. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  7931. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  7932. }, []);
  7933. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  7934. useLayoutEffect(() => {
  7935. measureToolbar();
  7936. const toolbar = toolbarRef.current;
  7937. if (!toolbar) return;
  7938. if (typeof ResizeObserver === 'undefined') {
  7939. window.addEventListener('resize', measureToolbar);
  7940. return () => window.removeEventListener('resize', measureToolbar);
  7941. }
  7942. const resizeObserver = new ResizeObserver(() => measureToolbar());
  7943. resizeObserver.observe(toolbar);
  7944. window.addEventListener('resize', measureToolbar);
  7945. return () => {
  7946. resizeObserver.disconnect();
  7947. window.removeEventListener('resize', measureToolbar);
  7948. };
  7949. }, [
  7950. measureToolbar,
  7951. printers?.length,
  7952. availableLocations.length,
  7953. hideDisconnected,
  7954. smartPlugCount,
  7955. ]);
  7956. const renderFilterControls = (inMenu = false) => (
  7957. <>
  7958. {/* Status filter */}
  7959. {printers && printers.length > 0 && (
  7960. <ToolbarDropdown
  7961. value={statusFilter}
  7962. onChange={setStatusFilter}
  7963. fullWidth={inMenu}
  7964. options={[
  7965. { value: 'all', label: t('printers.filter.allStatuses') },
  7966. { value: 'printing', label: t('printers.status.printing') },
  7967. { value: 'paused', label: t('printers.status.paused') },
  7968. { value: 'idle', label: t('printers.status.idle') },
  7969. { value: 'finished', label: t('printers.status.finished') },
  7970. { value: 'error', label: t('printers.status.error') },
  7971. { value: 'offline', label: t('printers.status.offline') },
  7972. ]}
  7973. />
  7974. )}
  7975. {/* Location filter — only shown when at least one printer has a location */}
  7976. {printers && printers.length > 0 && availableLocations.length > 0 && (
  7977. <ToolbarDropdown
  7978. value={locationFilter}
  7979. onChange={setLocationFilter}
  7980. fullWidth={inMenu}
  7981. options={[
  7982. { value: 'all', label: t('printers.filter.allLocations') },
  7983. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  7984. ]}
  7985. />
  7986. )}
  7987. <button
  7988. type="button"
  7989. onClick={toggleHideDisconnected}
  7990. aria-pressed={hideDisconnected}
  7991. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  7992. hideDisconnected
  7993. ? 'bg-bambu-green border-bambu-green text-white'
  7994. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7995. }`}
  7996. >
  7997. {t('printers.hideOffline')}
  7998. </button>
  7999. </>
  8000. );
  8001. const renderViewControls = (inMenu = false) => (
  8002. <>
  8003. {/* Sort dropdown */}
  8004. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  8005. <ToolbarDropdown<SortOption>
  8006. value={sortBy}
  8007. onChange={handleSortChange}
  8008. fullWidth={inMenu}
  8009. options={[
  8010. { value: 'name', label: t('printers.sort.name') },
  8011. { value: 'status', label: t('printers.sort.status') },
  8012. { value: 'model', label: t('printers.sort.model') },
  8013. { value: 'location', label: t('printers.sort.location') },
  8014. { value: 'eta', label: t('printers.sort.eta') },
  8015. ]}
  8016. />
  8017. <button
  8018. onClick={toggleSortDirection}
  8019. 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"
  8020. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  8021. >
  8022. {sortAsc ? (
  8023. <ArrowUp className="w-4 h-4 text-white" />
  8024. ) : (
  8025. <ArrowDown className="w-4 h-4 text-white" />
  8026. )}
  8027. </button>
  8028. </div>
  8029. {/* Page view toggle: Cards / Cam Wall */}
  8030. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  8031. <button
  8032. type="button"
  8033. onClick={() => {
  8034. setPageView('cards');
  8035. localStorage.setItem('printerPageView', 'cards');
  8036. }}
  8037. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8038. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8039. }`}
  8040. title={t('printers.pageView.cards')}
  8041. aria-pressed={pageView === 'cards'}
  8042. >
  8043. <LayoutGrid className="w-3.5 h-3.5" />
  8044. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  8045. </button>
  8046. <button
  8047. type="button"
  8048. onClick={() => {
  8049. setPageView('camwall');
  8050. localStorage.setItem('printerPageView', 'camwall');
  8051. }}
  8052. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8053. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8054. }`}
  8055. title={t('printers.pageView.camWall')}
  8056. aria-pressed={pageView === 'camwall'}
  8057. disabled={!hasPermission('camera:view')}
  8058. >
  8059. <MonitorPlay className="w-3.5 h-3.5" />
  8060. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  8061. </button>
  8062. </div>
  8063. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  8064. view, and the page a kiosk token points at. Only offered once the wall
  8065. is the active view, so it doesn't compete with the toggle above. */}
  8066. {pageView === 'camwall' && hasPermission('camera:view') && (
  8067. <RouterLink
  8068. to="/camwall"
  8069. 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' : ''}`}
  8070. title={t('printers.pageView.openCamWallPage')}
  8071. >
  8072. <ExternalLink className="w-3.5 h-3.5" />
  8073. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  8074. </RouterLink>
  8075. )}
  8076. {/* Card size selector */}
  8077. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${pageView === 'camwall' ? 'opacity-40 pointer-events-none' : ''} ${inMenu ? 'w-full' : ''}`}>
  8078. {cardSizeLabels.map((label, index) => {
  8079. const size = index + 1;
  8080. const isSelected = cardSize === size;
  8081. return (
  8082. <button
  8083. key={label}
  8084. onClick={() => {
  8085. setCompactDrilldownPrinterId(null);
  8086. setCardSize(size);
  8087. localStorage.setItem('printerCardSize', String(size));
  8088. }}
  8089. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  8090. index === 0 ? 'rounded-l-lg' : ''
  8091. } ${
  8092. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  8093. } ${
  8094. isSelected
  8095. ? 'bg-bambu-green text-white'
  8096. : 'text-white hover:bg-bambu-dark-tertiary'
  8097. }`}
  8098. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  8099. >
  8100. {label}
  8101. </button>
  8102. );
  8103. })}
  8104. </div>
  8105. </>
  8106. );
  8107. const renderActionControls = (inMenu = false) => (
  8108. <>
  8109. {/* Bulk select toggle */}
  8110. <button
  8111. onClick={() => {
  8112. if (selectionMode) clearSelection();
  8113. else setIsSelectionMode(true);
  8114. }}
  8115. 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' : ''} ${
  8116. selectionMode
  8117. ? 'bg-bambu-green border-bambu-green text-white'
  8118. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8119. }`}
  8120. title={t('printers.bulk.select')}
  8121. disabled={!hasPermission('printers:control')}
  8122. >
  8123. <CheckSquare className="w-4 h-4" />
  8124. {inMenu && <span>{t('printers.bulk.select')}</span>}
  8125. </button>
  8126. {/* Power dropdown for offline printers with smart plugs */}
  8127. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  8128. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  8129. <button
  8130. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  8131. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  8132. inMenu
  8133. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  8134. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8135. }`}
  8136. >
  8137. <span className="flex items-center gap-1.5">
  8138. <Power className="w-4 h-4" />
  8139. {t('printers.powerOn')}
  8140. </span>
  8141. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  8142. </button>
  8143. {showPowerDropdown && (
  8144. <>
  8145. {/* Backdrop to close dropdown */}
  8146. <div
  8147. className="fixed inset-0 z-10"
  8148. onClick={() => setShowPowerDropdown(false)}
  8149. />
  8150. <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">
  8151. <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">
  8152. {t('printers.offlinePrintersWithPlugs')}
  8153. </div>
  8154. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  8155. <PowerDropdownItem
  8156. key={printer.id}
  8157. printer={printer}
  8158. plug={smartPlugByPrinter[printer.id]}
  8159. onPowerOn={(plugId) => {
  8160. setPoweringOn(plugId);
  8161. powerOnMutation.mutate(plugId);
  8162. }}
  8163. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  8164. />
  8165. ))}
  8166. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  8167. <div className="px-3 py-2 text-sm text-bambu-gray">
  8168. No printers with smart plugs
  8169. </div>
  8170. )}
  8171. </div>
  8172. </>
  8173. )}
  8174. </div>
  8175. )}
  8176. <Button
  8177. onClick={() => setShowAddModal(true)}
  8178. disabled={!hasPermission('printers:create')}
  8179. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8180. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  8181. >
  8182. <Plus className="w-4 h-4" />
  8183. {t('printers.addPrinter')}
  8184. </Button>
  8185. </>
  8186. );
  8187. return (
  8188. <div className="p-4 md:p-8">
  8189. <div className="space-y-3 mb-6">
  8190. <div>
  8191. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  8192. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  8193. {t('printers.title')}
  8194. </h1>
  8195. <StatusSummaryBar printers={printers} />
  8196. </div>
  8197. <div ref={toolbarRef} className="relative flex items-center gap-2">
  8198. {/* Only show search bar when printers exist */}
  8199. {printers && printers.length > 0 && (
  8200. <div className="relative min-w-0 flex-1">
  8201. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  8202. <input
  8203. type="search"
  8204. name="printer-search"
  8205. autoComplete="off"
  8206. data-1p-ignore
  8207. data-lpignore="true"
  8208. value={search}
  8209. onChange={(e) => setSearch(e.target.value)}
  8210. placeholder={t('printers.search')}
  8211. aria-label={t('printers.search')}
  8212. 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"
  8213. />
  8214. {search && (
  8215. <button
  8216. type="button"
  8217. aria-label={t('common.clear')}
  8218. onClick={() => setSearch('')}
  8219. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  8220. >
  8221. <X className="w-4 h-4" />
  8222. </button>
  8223. )}
  8224. </div>
  8225. )}
  8226. <div
  8227. ref={expandedToolbarControlsRef}
  8228. aria-hidden={compactToolbar}
  8229. inert={compactToolbar}
  8230. 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`}
  8231. >
  8232. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8233. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  8234. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8235. <div className="flex items-center gap-2">{renderViewControls()}</div>
  8236. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8237. <div className="flex items-center gap-2">{renderActionControls()}</div>
  8238. </div>
  8239. {compactToolbar && (
  8240. <div className="ml-auto flex items-center justify-end gap-1">
  8241. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  8242. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  8243. </ToolbarMenu>
  8244. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  8245. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  8246. </ToolbarMenu>
  8247. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  8248. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  8249. </ToolbarMenu>
  8250. </div>
  8251. )}
  8252. </div>
  8253. </div>
  8254. {isLoading ? (
  8255. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  8256. ) : printers?.length === 0 ? (
  8257. <Card>
  8258. <CardContent className="text-center py-12">
  8259. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  8260. <Button
  8261. onClick={() => setShowAddModal(true)}
  8262. disabled={!hasPermission('printers:create')}
  8263. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8264. >
  8265. <Plus className="w-4 h-4" />
  8266. {t('printers.addPrinter')}
  8267. </Button>
  8268. </CardContent>
  8269. </Card>
  8270. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  8271. <Card>
  8272. <CardContent className="text-center py-12">
  8273. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  8274. </CardContent>
  8275. </Card>
  8276. ) : pageView === 'camwall' ? (
  8277. <CameraWall
  8278. printers={sortedPrinters}
  8279. maxLive={camWallMaxLive}
  8280. snapshotIntervalSec={camWallSnapshotSec}
  8281. onTileClick={(id, name) => {
  8282. const cameraMode = settings?.camera_view_mode || 'window';
  8283. if (cameraMode === 'embedded') {
  8284. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  8285. } else {
  8286. const saved = localStorage.getItem('cameraWindowState');
  8287. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  8288. const features = [
  8289. `width=${state.width}`,
  8290. `height=${state.height}`,
  8291. state.left !== undefined ? `left=${state.left}` : '',
  8292. state.top !== undefined ? `top=${state.top}` : '',
  8293. 'menubar=no,toolbar=no,location=no,status=no',
  8294. ].filter(Boolean).join(',');
  8295. window.open(`/camera/${id}`, `camera-${id}`, features);
  8296. }
  8297. }}
  8298. statusMode={camWallStatusMode}
  8299. onChangeMaxLive={(next) => {
  8300. setCamWallMaxLive(next);
  8301. localStorage.setItem('camWallMaxLive', String(next));
  8302. }}
  8303. onChangeSnapshotIntervalSec={(next) => {
  8304. setCamWallSnapshotSec(next);
  8305. localStorage.setItem('camWallSnapshotSec', String(next));
  8306. }}
  8307. onChangeStatusMode={(next) => {
  8308. setCamWallStatusMode(next);
  8309. localStorage.setItem('camWallStatusMode', next);
  8310. }}
  8311. />
  8312. ) : groupedPrinters ? (
  8313. /* Grouped view (location, status, or model) */
  8314. <div className="space-y-6">
  8315. {(() => {
  8316. const keys = sortBy === 'status'
  8317. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  8318. : Object.keys(groupedPrinters);
  8319. // For status grouping, asc/desc flips the fixed priority order
  8320. // (asc = error→offline, desc = offline→error). This matches the
  8321. // sort-toggle behaviour for other groupings.
  8322. return (sortAsc ? keys : [...keys].reverse());
  8323. })().map((groupKey) => {
  8324. const groupPrinters = groupedPrinters[groupKey];
  8325. const collapseKey = `${sortBy}:${groupKey}`;
  8326. const isOpen = !collapsedSections[collapseKey];
  8327. const dot = sortBy === 'status'
  8328. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  8329. : 'bg-bambu-green';
  8330. const label = sortBy === 'status'
  8331. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  8332. : groupKey;
  8333. return (
  8334. <Collapsible
  8335. key={groupKey}
  8336. open={isOpen}
  8337. onToggle={() => toggleSectionCollapse(collapseKey)}
  8338. summaryClassName="py-1"
  8339. summary={
  8340. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  8341. <span className={`w-2 h-2 rounded-full ${dot}`} />
  8342. {label}
  8343. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  8344. {selectionMode && (
  8345. <button
  8346. onClick={(e) => {
  8347. e.stopPropagation();
  8348. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  8349. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  8350. else if (sortBy === 'model') selectByModel(groupKey);
  8351. }}
  8352. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  8353. >
  8354. {t('printers.bulk.selectAll')}
  8355. </button>
  8356. )}
  8357. </h2>
  8358. }
  8359. >
  8360. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8361. {groupPrinters.map((printer) => (
  8362. <PrinterCard
  8363. key={printer.id}
  8364. printer={printer}
  8365. hideIfDisconnected={hideDisconnected}
  8366. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8367. viewMode={viewMode}
  8368. cardSize={cardSize}
  8369. amsThresholds={settings ? {
  8370. humidityGood: Number(settings.ams_humidity_good) || 40,
  8371. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8372. tempGood: Number(settings.ams_temp_good) || 28,
  8373. tempFair: Number(settings.ams_temp_fair) || 35,
  8374. } : undefined}
  8375. spoolmanEnabled={spoolmanEnabled}
  8376. hasUnlinkedSpools={hasUnlinkedSpools}
  8377. linkedSpools={linkedSpools}
  8378. spoolmanUrl={spoolmanStatus?.url}
  8379. spoolmanSyncMode={spoolmanSyncMode}
  8380. onGetAssignment={getAssignment}
  8381. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8382. spoolmanSpools={spoolmanSpools}
  8383. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8384. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8385. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8386. timeFormat={settings?.time_format || 'system'}
  8387. cameraViewMode={settings?.camera_view_mode || 'window'}
  8388. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8389. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8390. dryingPresets={effectiveDryingPresets}
  8391. nozzleTempPresets={effectiveNozzleTempPresets}
  8392. bedTempPresets={effectiveBedTempPresets}
  8393. chamberTempPresets={effectiveChamberTempPresets}
  8394. fanSpeedPresets={effectiveFanSpeedPresets}
  8395. requirePlateClear={settings?.require_plate_clear === true}
  8396. selectionMode={selectionMode}
  8397. isSelected={selectedPrinterIds.has(printer.id)}
  8398. onToggleSelect={toggleSelect}
  8399. onOpenCompactCard={openCompactCard}
  8400. />
  8401. ))}
  8402. </div>
  8403. </Collapsible>
  8404. );
  8405. })}
  8406. </div>
  8407. ) : (
  8408. /* Regular grid view */
  8409. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8410. {sortedPrinters.map((printer) => (
  8411. <PrinterCard
  8412. key={printer.id}
  8413. printer={printer}
  8414. hideIfDisconnected={hideDisconnected}
  8415. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8416. viewMode={viewMode}
  8417. cardSize={cardSize}
  8418. spoolmanEnabled={spoolmanEnabled}
  8419. hasUnlinkedSpools={hasUnlinkedSpools}
  8420. linkedSpools={linkedSpools}
  8421. spoolmanUrl={spoolmanStatus?.url}
  8422. spoolmanSyncMode={spoolmanSyncMode}
  8423. onGetAssignment={getAssignment}
  8424. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8425. spoolmanSpools={spoolmanSpools}
  8426. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8427. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8428. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8429. amsThresholds={settings ? {
  8430. humidityGood: Number(settings.ams_humidity_good) || 40,
  8431. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8432. tempGood: Number(settings.ams_temp_good) || 28,
  8433. tempFair: Number(settings.ams_temp_fair) || 35,
  8434. } : undefined}
  8435. timeFormat={settings?.time_format || 'system'}
  8436. cameraViewMode={settings?.camera_view_mode || 'window'}
  8437. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8438. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8439. dryingPresets={effectiveDryingPresets}
  8440. nozzleTempPresets={effectiveNozzleTempPresets}
  8441. bedTempPresets={effectiveBedTempPresets}
  8442. chamberTempPresets={effectiveChamberTempPresets}
  8443. fanSpeedPresets={effectiveFanSpeedPresets}
  8444. requirePlateClear={settings?.require_plate_clear === true}
  8445. selectionMode={selectionMode}
  8446. isSelected={selectedPrinterIds.has(printer.id)}
  8447. onToggleSelect={toggleSelect}
  8448. onOpenCompactCard={openCompactCard}
  8449. />
  8450. ))}
  8451. </div>
  8452. )}
  8453. {cardSize === 2 && compactDrilldownPrinterId != null && (
  8454. <button
  8455. type="button"
  8456. onClick={returnToCompactCards}
  8457. 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}`}
  8458. title={t('common.back', 'Back')}
  8459. >
  8460. <ArrowLeft className="w-4 h-4" />
  8461. {t('common.back', 'Back')}
  8462. </button>
  8463. )}
  8464. {showAddModal && (
  8465. <AddPrinterModal
  8466. onClose={() => setShowAddModal(false)}
  8467. onAdd={(data) => addMutation.mutate(data)}
  8468. existingSerials={printers?.map(p => p.serial_number) || []}
  8469. />
  8470. )}
  8471. {/* Bulk selection toolbar */}
  8472. {selectionMode && printers && (
  8473. <BulkPrinterToolbar
  8474. selectedIds={selectedPrinterIds}
  8475. printers={printers}
  8476. onClose={clearSelection}
  8477. onSelectAll={selectAll}
  8478. onSelectByLocation={selectByLocation}
  8479. onSelectByState={selectByState}
  8480. onAction={handleBulkAction}
  8481. actionPending={bulkActionPending}
  8482. />
  8483. )}
  8484. {/* Bulk action confirmation modals */}
  8485. {bulkConfirmAction === 'stop' && (
  8486. <ConfirmModal
  8487. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  8488. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  8489. confirmText={t('printers.bulk.confirm.stopButton')}
  8490. variant="danger"
  8491. isLoading={bulkActionPending}
  8492. onConfirm={() => executeBulkAction('stop')}
  8493. onCancel={() => setBulkConfirmAction(null)}
  8494. />
  8495. )}
  8496. {bulkConfirmAction === 'pause' && (
  8497. <ConfirmModal
  8498. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  8499. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  8500. confirmText={t('printers.bulk.confirm.pauseButton')}
  8501. isLoading={bulkActionPending}
  8502. onConfirm={() => executeBulkAction('pause')}
  8503. onCancel={() => setBulkConfirmAction(null)}
  8504. />
  8505. )}
  8506. {bulkConfirmAction === 'clearPlate' && (
  8507. <ConfirmModal
  8508. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  8509. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  8510. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  8511. isLoading={bulkActionPending}
  8512. onConfirm={() => executeBulkAction('clearPlate')}
  8513. onCancel={() => setBulkConfirmAction(null)}
  8514. />
  8515. )}
  8516. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  8517. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  8518. <EmbeddedCameraViewer
  8519. key={camera.id}
  8520. printerId={camera.id}
  8521. printerName={camera.name}
  8522. viewerIndex={index}
  8523. onClose={() => setEmbeddedCameraPrinters(prev => {
  8524. const next = new Map(prev);
  8525. next.delete(camera.id);
  8526. return next;
  8527. })}
  8528. />
  8529. ))}
  8530. </div>
  8531. );
  8532. }