PrintersPage.tsx 409 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720
  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. } from 'lucide-react';
  85. import { useNavigate } from 'react-router-dom';
  86. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  87. import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
  88. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  89. import { Card, CardContent } from '../components/Card';
  90. import { Button } from '../components/Button';
  91. import { ConfirmModal } from '../components/ConfirmModal';
  92. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  93. import { FileManagerModal } from '../components/FileManagerModal';
  94. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  95. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  96. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  97. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  98. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  99. import { AmsBackupModal } from '../components/AmsBackupModal';
  100. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  101. import type { HeaterSensorKind } from '../api/client';
  102. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  103. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  104. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  105. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  106. import { useToast } from '../contexts/ToastContext';
  107. import { ChamberLight } from '../components/icons/ChamberLight';
  108. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  109. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  110. import { FileUploadModal } from '../components/FileUploadModal';
  111. import { PrintModal } from '../components/PrintModal';
  112. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  113. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool } from '../utils/amsHelpers';
  114. import { getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
  115. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  116. import { Collapsible } from '../components/Collapsible';
  117. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  118. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  119. export interface SpoolmanSlotAssignmentRow {
  120. printer_id: number;
  121. ams_id: number;
  122. tray_id: number;
  123. spoolman_spool_id: number;
  124. }
  125. // Color names resolve via getColorName() which reads the backend color_catalog
  126. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  127. // Format K value with 3 decimal places, default to 0.020 if null
  128. function formatKValue(k: number | null | undefined): string {
  129. const value = k ?? 0.020;
  130. return value.toFixed(3);
  131. }
  132. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  133. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  134. const { mode } = useTheme();
  135. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  136. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  137. return (
  138. <span
  139. className="inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded"
  140. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  141. >
  142. {side}
  143. </span>
  144. );
  145. }
  146. // Expand nozzle type codes to material names
  147. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  148. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  149. function nozzleTypeName(type: string, t: (key: string) => string): string {
  150. if (!type) return '';
  151. // Full text names (from main nozzle info)
  152. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  153. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  154. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  155. // 4-char codes (e.g. "HS01"): last 2 digits = material
  156. if (type.length >= 4) {
  157. const material = type.slice(2, 4);
  158. if (material === '00') return t('printers.nozzleStainlessSteel');
  159. if (material === '01') return t('printers.nozzleHardenedSteel');
  160. if (material === '05') return t('printers.nozzleTungstenCarbide');
  161. }
  162. // 2-digit numeric codes
  163. if (type === '00') return t('printers.nozzleStainlessSteel');
  164. if (type === '01') return t('printers.nozzleHardenedSteel');
  165. if (type === '05') return t('printers.nozzleTungstenCarbide');
  166. // 2-char alpha codes: H prefix = hardened steel
  167. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  168. return type;
  169. }
  170. // Parse flow type from nozzle type code
  171. // HH = high flow, HS = standard/normal
  172. function nozzleFlowName(type: string, t: (key: string) => string): string {
  173. if (!type) return '';
  174. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  175. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  176. return '';
  177. }
  178. // Per-slot hover card for nozzle rack
  179. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  180. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  181. slot: import('../api/client').NozzleRackSlot;
  182. index: number;
  183. activeStatus?: boolean;
  184. filamentName?: string;
  185. children: React.ReactNode;
  186. }) {
  187. const { t } = useTranslation();
  188. const [isVisible, setIsVisible] = useState(false);
  189. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  190. const triggerRef = useRef<HTMLDivElement>(null);
  191. const cardRef = useRef<HTMLDivElement>(null);
  192. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  193. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  194. const isMounted = slot.stat === 1;
  195. useEffect(() => {
  196. if (isVisible && triggerRef.current && cardRef.current) {
  197. const triggerRect = triggerRef.current.getBoundingClientRect();
  198. const cardHeight = cardRef.current.offsetHeight;
  199. const headerHeight = 56;
  200. const spaceAbove = triggerRect.top - headerHeight;
  201. const spaceBelow = window.innerHeight - triggerRect.bottom;
  202. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  203. setPosition('bottom');
  204. } else {
  205. setPosition('top');
  206. }
  207. }
  208. }, [isVisible]);
  209. const handleMouseEnter = () => {
  210. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  211. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  212. };
  213. const handleMouseLeave = () => {
  214. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  215. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  216. };
  217. useEffect(() => {
  218. return () => {
  219. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  220. };
  221. }, []);
  222. const filamentCss = parseFilamentColor(slot.filament_color);
  223. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  224. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  225. return (
  226. <div
  227. ref={triggerRef}
  228. className="relative"
  229. onMouseEnter={handleMouseEnter}
  230. onMouseLeave={handleMouseLeave}
  231. >
  232. {children}
  233. {isVisible && (
  234. <div
  235. ref={cardRef}
  236. className={`
  237. absolute left-1/2 -translate-x-1/2 z-50
  238. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  239. animate-in fade-in-0 zoom-in-95 duration-150
  240. `}
  241. style={{ maxWidth: 'calc(100vw - 24px)' }}
  242. >
  243. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  244. {isEmpty ? (
  245. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  246. Slot {index + 1} — Empty
  247. </div>
  248. ) : (
  249. <div className="p-2.5 space-y-1.5">
  250. {/* Diameter */}
  251. <div className="flex items-center justify-between">
  252. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  253. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  254. </div>
  255. {/* Type */}
  256. {typeFull && (
  257. <div className="flex items-center justify-between">
  258. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  259. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  260. </div>
  261. )}
  262. {/* Flow (hide if empty) */}
  263. {flowFull && (
  264. <div className="flex items-center justify-between">
  265. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  266. <span className="text-xs text-white font-semibold">{flowFull}</span>
  267. </div>
  268. )}
  269. {/* Status badge */}
  270. <div className="flex items-center justify-between">
  271. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  272. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  273. activeStatus || isMounted
  274. ? 'bg-green-900/50 text-green-400'
  275. : 'bg-bambu-dark-tertiary text-bambu-gray'
  276. }`}>
  277. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  278. </span>
  279. </div>
  280. {/* Wear (hide if null) */}
  281. {slot.wear != null && (
  282. <div className="flex items-center justify-between">
  283. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  284. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  285. </div>
  286. )}
  287. {/* Max Temp (hide if 0) */}
  288. {slot.max_temp > 0 && (
  289. <div className="flex items-center justify-between">
  290. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  291. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  292. </div>
  293. )}
  294. {/* Serial (hide if empty) */}
  295. {slot.serial_number && (
  296. <div className="flex items-center justify-between">
  297. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  298. <span className="text-[10px] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  299. </div>
  300. )}
  301. {/* Filament: material type + color swatch (hide if no color) */}
  302. {(filamentCss || slot.filament_type) && (
  303. <div className="flex items-center justify-between">
  304. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  305. <div className="flex items-center gap-1">
  306. {filamentCss && (
  307. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  308. )}
  309. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  310. </div>
  311. </div>
  312. )}
  313. </div>
  314. )}
  315. </div>
  316. {/* Arrow pointer */}
  317. <div
  318. className={`
  319. absolute left-1/2 -translate-x-1/2 w-0 h-0
  320. border-l-[6px] border-l-transparent
  321. border-r-[6px] border-r-transparent
  322. ${position === 'top'
  323. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  324. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  325. `}
  326. />
  327. </div>
  328. )}
  329. </div>
  330. );
  331. }
  332. // Dual-nozzle hover card showing L and R nozzle details side by side
  333. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  334. leftSlot?: import('../api/client').NozzleRackSlot;
  335. rightSlot?: import('../api/client').NozzleRackSlot;
  336. activeNozzle: 'L' | 'R';
  337. filamentInfo?: Record<string, { name: string; k: number | null }>;
  338. children: React.ReactNode;
  339. }) {
  340. const { t } = useTranslation();
  341. const [isVisible, setIsVisible] = useState(false);
  342. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  343. const triggerRef = useRef<HTMLDivElement>(null);
  344. const cardRef = useRef<HTMLDivElement>(null);
  345. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  346. useEffect(() => {
  347. if (isVisible && triggerRef.current && cardRef.current) {
  348. const triggerRect = triggerRef.current.getBoundingClientRect();
  349. const cardHeight = cardRef.current.offsetHeight;
  350. const headerHeight = 56;
  351. const spaceAbove = triggerRect.top - headerHeight;
  352. const spaceBelow = window.innerHeight - triggerRect.bottom;
  353. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  354. setPosition('bottom');
  355. } else {
  356. setPosition('top');
  357. }
  358. }
  359. }, [isVisible]);
  360. const handleMouseEnter = () => {
  361. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  362. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  363. };
  364. const handleMouseLeave = () => {
  365. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  366. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  367. };
  368. useEffect(() => {
  369. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  370. }, []);
  371. if (!leftSlot && !rightSlot) return <>{children}</>;
  372. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  373. const isActive = activeNozzle === side;
  374. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  375. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  376. const filamentCss = parseFilamentColor(slot.filament_color);
  377. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  378. return (
  379. <div className="flex-1 space-y-1.5">
  380. <div className={`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-400' : 'text-bambu-gray'}`}>
  381. {side === 'L' ? t('common.left') : t('common.right')}
  382. </div>
  383. {slot.nozzle_diameter && (
  384. <div className="flex items-center justify-between">
  385. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  386. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  387. </div>
  388. )}
  389. {typeFull && (
  390. <div className="flex items-center justify-between">
  391. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleType')}</span>
  392. <span className="text-[10px] text-white font-semibold">{typeFull}</span>
  393. </div>
  394. )}
  395. {flowFull && (
  396. <div className="flex items-center justify-between">
  397. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  398. <span className="text-[10px] text-white font-semibold">{flowFull}</span>
  399. </div>
  400. )}
  401. <div className="flex items-center justify-between">
  402. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  403. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  404. isActive
  405. ? 'bg-green-900/50 text-green-400'
  406. : 'bg-bambu-dark-tertiary text-bambu-gray'
  407. }`}>
  408. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  409. </span>
  410. </div>
  411. {slot.wear != null && (
  412. <div className="flex items-center justify-between">
  413. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleWear')}</span>
  414. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  415. </div>
  416. )}
  417. {/* Serial and max temp only available on the right (removable) nozzle */}
  418. {side === 'R' && slot.max_temp > 0 && (
  419. <div className="flex items-center justify-between">
  420. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  421. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  422. </div>
  423. )}
  424. {side === 'R' && slot.serial_number && (
  425. <div className="flex items-center justify-between">
  426. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  427. <span className="text-[10px] text-white font-mono">{slot.serial_number}</span>
  428. </div>
  429. )}
  430. {(filamentCss || slot.filament_type || slot.filament_id) && (
  431. <div className="flex items-center justify-between">
  432. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  433. <div className="flex items-center gap-1">
  434. {filamentCss && (
  435. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  436. )}
  437. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">
  438. {filamentName || slot.filament_type || slot.filament_id || ''}
  439. </span>
  440. </div>
  441. </div>
  442. )}
  443. </div>
  444. );
  445. };
  446. return (
  447. <div
  448. ref={triggerRef}
  449. className="relative flex-1"
  450. onMouseEnter={handleMouseEnter}
  451. onMouseLeave={handleMouseLeave}
  452. >
  453. {children}
  454. {isVisible && (
  455. <div
  456. ref={cardRef}
  457. className={`
  458. absolute left-1/2 -translate-x-1/2 z-50
  459. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  460. animate-in fade-in-0 zoom-in-95 duration-150
  461. `}
  462. style={{ maxWidth: 'calc(100vw - 24px)' }}
  463. >
  464. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  465. <div className="p-2.5 flex gap-3">
  466. {leftSlot && renderColumn(leftSlot, 'L')}
  467. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  468. {rightSlot && renderColumn(rightSlot, 'R')}
  469. </div>
  470. </div>
  471. {/* Arrow pointer */}
  472. <div
  473. className={`
  474. absolute left-1/2 -translate-x-1/2 w-0 h-0
  475. border-l-[6px] border-l-transparent
  476. border-r-[6px] border-r-transparent
  477. ${position === 'top'
  478. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  479. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  480. `}
  481. />
  482. </div>
  483. )}
  484. </div>
  485. );
  486. }
  487. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  488. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  489. const { t } = useTranslation();
  490. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  491. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  492. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  493. // base — computing it from min(present IDs) shifts everything left when slot 16
  494. // is the one currently mounted (#943).
  495. const rackNozzles = slots.filter(s => s.id >= 2);
  496. const RACK_SIZE = 6;
  497. const RACK_BASE_ID = 16;
  498. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  499. { length: RACK_SIZE },
  500. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  501. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  502. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  503. },
  504. );
  505. return (
  506. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center">
  507. <p className="text-[9px] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  508. <div className="flex gap-[3px] justify-center">
  509. {rackSlots.map((slot, i) => {
  510. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  511. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  512. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  513. return (
  514. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  515. <div
  516. className={`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  517. isEmpty
  518. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  519. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  520. }`}
  521. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  522. >
  523. <span className={`text-[10px] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  524. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  525. >
  526. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  527. </span>
  528. </div>
  529. </NozzleSlotHoverCard>
  530. );
  531. })}
  532. </div>
  533. </div>
  534. );
  535. }
  536. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  537. function WaterDropEmpty({ className }: { className?: string }) {
  538. return (
  539. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  540. <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"/>
  541. </svg>
  542. );
  543. }
  544. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  545. function WaterDropHalf({ className }: { className?: string }) {
  546. return (
  547. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  548. <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"/>
  549. <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"/>
  550. </svg>
  551. );
  552. }
  553. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  554. function WaterDropFull({ className }: { className?: string }) {
  555. return (
  556. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  557. <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"/>
  558. <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"/>
  559. </svg>
  560. );
  561. }
  562. // Thermometer SVG - empty outline
  563. function ThermometerEmpty({ className }: { className?: string }) {
  564. return (
  565. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  566. <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"/>
  567. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  568. </svg>
  569. );
  570. }
  571. // Thermometer SVG - half filled (gold - same as humidity fair)
  572. function ThermometerHalf({ className }: { className?: string }) {
  573. return (
  574. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  575. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  576. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  577. <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"/>
  578. </svg>
  579. );
  580. }
  581. // Thermometer SVG - fully filled (red - same as humidity bad)
  582. function ThermometerFull({ className }: { className?: string }) {
  583. return (
  584. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  585. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  586. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  587. <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"/>
  588. </svg>
  589. );
  590. }
  591. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  592. // Added for visual parity with the thermometer icons on the dual-nozzle card
  593. // that previously had no icon at all (#1115, design by @m4rtini2).
  594. function NozzleIcon({ className }: { className?: string }) {
  595. return (
  596. <svg
  597. className={className}
  598. viewBox="0 0 24 24"
  599. fill="none"
  600. xmlns="http://www.w3.org/2000/svg"
  601. stroke="currentColor"
  602. strokeWidth="1.5"
  603. strokeLinecap="round"
  604. strokeLinejoin="round"
  605. >
  606. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  607. <rect x="6" y="11.5" width="12.1" height="3.7" />
  608. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  609. </svg>
  610. );
  611. }
  612. // Heater thermometer icon - filled when heating, outline when off
  613. interface HeaterThermometerProps {
  614. className?: string;
  615. color: string; // The color class (e.g., "text-orange-400")
  616. isHeating: boolean;
  617. }
  618. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  619. // Extract the actual color from Tailwind class for SVG fill
  620. const colorMap: Record<string, string> = {
  621. 'text-orange-400': '#fb923c',
  622. 'text-blue-400': '#60a5fa',
  623. 'text-green-400': '#4ade80',
  624. };
  625. const fillColor = colorMap[color] || '#888';
  626. // Glow style when heating
  627. const glowStyle = isHeating ? {
  628. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  629. } : {};
  630. if (isHeating) {
  631. // Filled thermometer with glow - heater is ON
  632. return (
  633. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  634. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  635. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  636. <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"/>
  637. </svg>
  638. );
  639. }
  640. // Empty thermometer - heater is OFF
  641. return (
  642. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  643. <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"/>
  644. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  645. </svg>
  646. );
  647. }
  648. // AMS Filament Backup tri-state indicator + toggle.
  649. // state=true → ON, click to disable
  650. // state=false → OFF, click opens modal
  651. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  652. interface AmsBackupBadgeProps {
  653. state: boolean | null;
  654. onClick: () => void;
  655. }
  656. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  657. const { t } = useTranslation();
  658. const known = state !== null;
  659. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors ';
  660. let title: string;
  661. if (state === true) {
  662. className += known
  663. ? 'bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  664. : 'bg-blue-500/20 text-blue-400 cursor-default';
  665. title = t('printers.amsBackup.titleOn');
  666. } else if (state === false) {
  667. className += known
  668. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  669. : 'bg-bambu-dark text-bambu-gray cursor-default';
  670. title = t('printers.amsBackup.titleOff');
  671. } else {
  672. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  673. title = t('printers.amsBackup.titleUnknown');
  674. }
  675. return (
  676. <button
  677. type="button"
  678. disabled={!known}
  679. onClick={() => known && onClick()}
  680. className={className}
  681. title={title}
  682. aria-label={title}
  683. >
  684. {known ? <Repeat className="w-3 h-3" /> : <span>?</span>}
  685. </button>
  686. );
  687. }
  688. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  689. // Reference: https://github.com/theicedmango/bambu-humidity
  690. interface HumidityIndicatorProps {
  691. humidity: number | string;
  692. goodThreshold?: number; // <= this is green
  693. fairThreshold?: number; // <= this is orange, > is red
  694. onClick?: () => void;
  695. compact?: boolean; // Smaller version for grid layout
  696. }
  697. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  698. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  699. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  700. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  701. // Status thresholds (configurable via settings)
  702. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  703. let textColor: string;
  704. let statusText: string;
  705. if (isNaN(humidityValue)) {
  706. textColor = '#C3C2C1';
  707. statusText = 'Unknown';
  708. } else if (humidityValue <= good) {
  709. textColor = '#22a352'; // Green - Good
  710. statusText = 'Good';
  711. } else if (humidityValue <= fair) {
  712. textColor = '#d4a017'; // Gold - Fair
  713. statusText = 'Fair';
  714. } else {
  715. textColor = '#c62828'; // Red - Bad
  716. statusText = 'Bad';
  717. }
  718. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  719. let DropComponent: React.FC<{ className?: string }>;
  720. if (isNaN(humidityValue)) {
  721. DropComponent = WaterDropEmpty;
  722. } else if (humidityValue <= good) {
  723. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  724. } else if (humidityValue <= fair) {
  725. DropComponent = WaterDropHalf; // Fair - half filled
  726. } else {
  727. DropComponent = WaterDropFull; // Bad - full (too humid)
  728. }
  729. return (
  730. <button
  731. type="button"
  732. onClick={onClick}
  733. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  734. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  735. >
  736. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  737. <span className={`font-medium tabular-nums ${compact ? 'text-[10px]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  738. </button>
  739. );
  740. }
  741. // Temperature indicator with dynamic icon and coloring
  742. interface TemperatureIndicatorProps {
  743. temp: number;
  744. goodThreshold?: number; // <= this is blue
  745. fairThreshold?: number; // <= this is orange, > is red
  746. onClick?: () => void;
  747. compact?: boolean; // Smaller version for grid layout
  748. }
  749. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  750. // Ensure thresholds are numbers
  751. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  752. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  753. let textColor: string;
  754. let statusText: string;
  755. let ThermoComponent: React.FC<{ className?: string }>;
  756. if (temp <= good) {
  757. textColor = '#22a352'; // Green - good (same as humidity)
  758. statusText = 'Good';
  759. ThermoComponent = ThermometerEmpty;
  760. } else if (temp <= fair) {
  761. textColor = '#d4a017'; // Gold - fair (same as humidity)
  762. statusText = 'Fair';
  763. ThermoComponent = ThermometerHalf;
  764. } else {
  765. textColor = '#c62828'; // Red - bad (same as humidity)
  766. statusText = 'Bad';
  767. ThermoComponent = ThermometerFull;
  768. }
  769. return (
  770. <button
  771. type="button"
  772. onClick={onClick}
  773. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  774. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  775. >
  776. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  777. <span className={`tabular-nums text-right ${compact ? 'text-[10px] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  778. </button>
  779. );
  780. }
  781. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  782. *
  783. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  784. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  785. * every empty-by-bitmask slot lands here regardless of firmware payload
  786. * shape.
  787. *
  788. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  789. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  790. * the user cleared with "Reset Slot" where a physical spool may still be
  791. * loaded but unassigned.
  792. *
  793. * Returns null when the slot is loaded (tray_type is present).
  794. */
  795. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null } | null | undefined): 'physical' | 'reset' | null {
  796. if (tray?.tray_type) return null;
  797. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  798. }
  799. function CoverImage({
  800. url,
  801. printName,
  802. className = 'w-20 h-20',
  803. radiusClass = 'rounded-lg',
  804. }: {
  805. url: string | null;
  806. printName?: string;
  807. className?: string;
  808. radiusClass?: string;
  809. }) {
  810. const { t } = useTranslation();
  811. const [loaded, setLoaded] = useState(false);
  812. const [error, setError] = useState(false);
  813. const [showOverlay, setShowOverlay] = useState(false);
  814. // Cache-bust the image URL when the print name changes so the browser
  815. // fetches the new cover instead of serving the stale cached image.
  816. const cacheBustedUrl = useMemo(() => {
  817. if (!url) return null;
  818. const sep = url.includes('?') ? '&' : '?';
  819. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  820. }, [url, printName]);
  821. // Reset loaded/error state when the image URL changes
  822. useEffect(() => {
  823. setLoaded(false);
  824. setError(false);
  825. }, [cacheBustedUrl]);
  826. return (
  827. <>
  828. <div
  829. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  830. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  831. >
  832. {cacheBustedUrl && !error ? (
  833. <>
  834. <img
  835. src={cacheBustedUrl}
  836. alt={t('printers.printPreview')}
  837. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  838. onLoad={() => setLoaded(true)}
  839. onError={() => setError(true)}
  840. />
  841. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  842. </>
  843. ) : (
  844. <Box className="w-8 h-8 text-bambu-gray" />
  845. )}
  846. </div>
  847. {/* Cover Image Overlay */}
  848. {showOverlay && cacheBustedUrl && (
  849. <div
  850. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  851. onClick={() => setShowOverlay(false)}
  852. >
  853. <div className="relative max-w-2xl max-h-full">
  854. <img
  855. src={cacheBustedUrl}
  856. alt={t('printers.printPreview')}
  857. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  858. />
  859. {printName && (
  860. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  861. )}
  862. </div>
  863. </div>
  864. )}
  865. </>
  866. );
  867. }
  868. interface PrinterMaintenanceInfo {
  869. due_count: number;
  870. warning_count: number;
  871. total_print_hours: number;
  872. }
  873. // Status summary bar component - uses queryClient to read cached statuses
  874. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  875. const { t } = useTranslation();
  876. const queryClient = useQueryClient();
  877. // Subscribe to query cache changes to re-render when status updates
  878. // Throttled to prevent rapid re-renders from causing tab crashes
  879. const [cacheTick, setCacheTick] = useState(0);
  880. useEffect(() => {
  881. let pending = false;
  882. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  883. if (!pending) {
  884. pending = true;
  885. requestAnimationFrame(() => {
  886. setCacheTick(t => t + 1);
  887. pending = false;
  888. });
  889. }
  890. });
  891. return () => unsubscribe();
  892. }, [queryClient]);
  893. const { counts, nextFinish } = useMemo(() => {
  894. let printing = 0;
  895. let paused = 0;
  896. let finished = 0;
  897. let idle = 0;
  898. let offline = 0;
  899. let loading = 0;
  900. let error = 0;
  901. let nextPrinterName: string | null = null;
  902. let nextRemainingMin: number | null = null;
  903. let nextProgress: number = 0;
  904. printers?.forEach((printer) => {
  905. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  906. if (status === undefined) {
  907. // Status not yet loaded - don't count as offline yet
  908. loading++;
  909. } else if (!status.connected) {
  910. offline++;
  911. } else {
  912. // Count printers with active HMS errors as problems
  913. const knownHmsCount =
  914. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  915. if (knownHmsCount > 0) {
  916. error++;
  917. }
  918. switch (status.state) {
  919. case 'RUNNING':
  920. printing++;
  921. if (status.remaining_time != null && status.remaining_time > 0) {
  922. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  923. nextRemainingMin = status.remaining_time;
  924. nextPrinterName = printer.name;
  925. nextProgress = status.progress || 0;
  926. }
  927. }
  928. break;
  929. case 'PAUSE':
  930. paused++;
  931. break;
  932. case 'FINISH':
  933. finished++;
  934. break;
  935. case 'FAILED':
  936. // FAILED is the printer's terminal gcode_state after a print stops —
  937. // including user cancellations, where there's no actual fault. Only
  938. // count it as a "problem" when an HMS error is also active; otherwise
  939. // it's just a print that ended unsuccessfully and the plate needs
  940. // clearing (same as FINISH from the operator's perspective).
  941. if (knownHmsCount > 0) {
  942. // Already counted above
  943. } else {
  944. finished++;
  945. }
  946. break;
  947. default:
  948. idle++;
  949. break;
  950. }
  951. }
  952. });
  953. return {
  954. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  955. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  956. };
  957. // eslint-disable-next-line react-hooks/exhaustive-deps
  958. }, [printers, queryClient, cacheTick]);
  959. if (!printers?.length) return null;
  960. const badges: { count: number; dot: string; label: string }[] = [
  961. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  962. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  963. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  964. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  965. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  966. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  967. ];
  968. return (
  969. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  970. {badges.map(({ count, dot, label }) => count > 0 && (
  971. <div key={label} className="flex items-center gap-1.5">
  972. <div className={`w-2 h-2 rounded-full ${dot}`} />
  973. <span className="text-bambu-gray">
  974. <span className="text-white font-medium">{count}</span> {label}
  975. </span>
  976. </div>
  977. ))}
  978. {nextFinish && (
  979. <>
  980. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  981. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  982. <div className="flex items-center gap-2">
  983. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  984. <span className="text-white font-medium">{nextFinish.name}</span>
  985. </div>
  986. <div className="flex items-center gap-2 w-full sm:w-auto">
  987. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  988. <div
  989. className="bg-bambu-green h-1.5 rounded-full transition-all"
  990. style={{ width: `${nextFinish.progress}%` }}
  991. />
  992. </div>
  993. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  994. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  995. </div>
  996. </div>
  997. </>
  998. )}
  999. </div>
  1000. );
  1001. }
  1002. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1003. type ViewMode = 'expanded' | 'compact';
  1004. type ToolbarDropdownOption<T extends string> = {
  1005. value: T;
  1006. label: string;
  1007. };
  1008. function ToolbarDropdown<T extends string>({
  1009. value,
  1010. options,
  1011. onChange,
  1012. fullWidth = false,
  1013. }: {
  1014. value: T;
  1015. options: ToolbarDropdownOption<T>[];
  1016. onChange: (value: T) => void;
  1017. fullWidth?: boolean;
  1018. }) {
  1019. const [isOpen, setIsOpen] = useState(false);
  1020. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1021. return (
  1022. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1023. <button
  1024. type="button"
  1025. onClick={() => setIsOpen(open => !open)}
  1026. 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'}`}
  1027. >
  1028. <span className="truncate">{selectedOption?.label}</span>
  1029. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1030. </button>
  1031. {isOpen && (
  1032. <>
  1033. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1034. <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">
  1035. {options.map(option => (
  1036. <button
  1037. key={option.value}
  1038. type="button"
  1039. onClick={() => {
  1040. onChange(option.value);
  1041. setIsOpen(false);
  1042. }}
  1043. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1044. option.value === value ? 'text-bambu-green' : 'text-white'
  1045. }`}
  1046. >
  1047. {option.label}
  1048. </button>
  1049. ))}
  1050. </div>
  1051. </>
  1052. )}
  1053. </div>
  1054. );
  1055. }
  1056. function ToolbarMenu({
  1057. label,
  1058. icon,
  1059. children,
  1060. }: {
  1061. label: string;
  1062. icon: React.ReactNode;
  1063. children: React.ReactNode;
  1064. }) {
  1065. const [isOpen, setIsOpen] = useState(false);
  1066. return (
  1067. <div className="relative">
  1068. <button
  1069. type="button"
  1070. onClick={() => setIsOpen(open => !open)}
  1071. 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"
  1072. aria-label={label}
  1073. title={label}
  1074. >
  1075. {icon}
  1076. </button>
  1077. {isOpen && (
  1078. <>
  1079. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1080. <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">
  1081. {children}
  1082. </div>
  1083. </>
  1084. )}
  1085. </div>
  1086. );
  1087. }
  1088. function IndicatorControlPopover({
  1089. title,
  1090. options = [],
  1091. unit,
  1092. customMin,
  1093. customMax,
  1094. customStep = 1,
  1095. widthClass = 'w-[240px]',
  1096. popoverWidth = 240,
  1097. popoverHeight = 280,
  1098. isPending,
  1099. onClose,
  1100. onSubmit,
  1101. children,
  1102. }: {
  1103. title: string;
  1104. options?: Array<{ label: string; value: number }>;
  1105. unit?: string;
  1106. customMin?: number;
  1107. customMax?: number;
  1108. customStep?: number;
  1109. widthClass?: string;
  1110. popoverWidth?: number;
  1111. popoverHeight?: number;
  1112. isPending?: boolean;
  1113. onClose: () => void;
  1114. onSubmit?: (value: number) => void;
  1115. children?: React.ReactNode;
  1116. }) {
  1117. const anchorRef = useRef<HTMLSpanElement>(null);
  1118. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1119. const [customValue, setCustomValue] = useState('');
  1120. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1121. // can position via fixed coords. Portaling to document.body escapes
  1122. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1123. // own contexts and would otherwise cover the popover even at z-[60].
  1124. useLayoutEffect(() => {
  1125. const trigger = anchorRef.current?.parentElement;
  1126. if (!trigger) return;
  1127. const measure = () => {
  1128. const rect = trigger.getBoundingClientRect();
  1129. setCoords(computePopoverPosition({
  1130. triggerRect: rect,
  1131. popoverWidth,
  1132. estimatedHeight: popoverHeight,
  1133. horizontalAlign: 'center',
  1134. }));
  1135. };
  1136. measure();
  1137. window.addEventListener('resize', measure);
  1138. window.addEventListener('scroll', measure, true);
  1139. return () => {
  1140. window.removeEventListener('resize', measure);
  1141. window.removeEventListener('scroll', measure, true);
  1142. };
  1143. }, [popoverWidth, popoverHeight]);
  1144. const showCustomInput = unit !== undefined;
  1145. const submitCustom = () => {
  1146. const value = Number(customValue);
  1147. if (!Number.isFinite(value)) return;
  1148. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1149. onSubmit?.(Math.round(bounded));
  1150. };
  1151. return (
  1152. <>
  1153. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1154. {createPortal(
  1155. <>
  1156. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1157. <div
  1158. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1159. style={{
  1160. top: coords?.top ?? -9999,
  1161. left: coords?.left ?? -9999,
  1162. visibility: coords ? 'visible' : 'hidden',
  1163. }}
  1164. onClick={e => e.stopPropagation()}
  1165. >
  1166. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1167. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1168. {options.length > 0 && (
  1169. <div className="px-3 py-2.5">
  1170. <div className="grid grid-cols-2 gap-1.5">
  1171. {options.map(option => (
  1172. <button
  1173. key={`${option.label}-${option.value}`}
  1174. type="button"
  1175. disabled={isPending}
  1176. onClick={() => onSubmit?.(option.value)}
  1177. 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"
  1178. >
  1179. {option.label}
  1180. </button>
  1181. ))}
  1182. </div>
  1183. </div>
  1184. )}
  1185. {children}
  1186. {showCustomInput && (
  1187. <>
  1188. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1189. <form
  1190. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1191. onSubmit={(e) => {
  1192. e.preventDefault();
  1193. submitCustom();
  1194. }}
  1195. >
  1196. <input
  1197. type="number"
  1198. min={customMin}
  1199. max={customMax}
  1200. step={customStep}
  1201. value={customValue}
  1202. onChange={e => setCustomValue(e.target.value)}
  1203. placeholder="Custom"
  1204. 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"
  1205. />
  1206. <button
  1207. type="submit"
  1208. disabled={isPending || customValue.trim() === ''}
  1209. 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"
  1210. >
  1211. Set
  1212. </button>
  1213. </form>
  1214. </>
  1215. )}
  1216. </div>
  1217. </>,
  1218. document.body
  1219. )}
  1220. </>
  1221. );
  1222. }
  1223. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1224. function NozzleTemperatureControlBox({
  1225. label,
  1226. current,
  1227. target,
  1228. isActive,
  1229. isPending,
  1230. onSubmit,
  1231. options = NOZZLE_TEMPERATURE_OPTIONS,
  1232. }: {
  1233. label: string;
  1234. current?: number;
  1235. target?: number;
  1236. isActive: boolean;
  1237. isPending?: boolean;
  1238. onSubmit: (value: number) => void;
  1239. options?: Array<{ label: string; value: number }>;
  1240. }) {
  1241. const [customValue, setCustomValue] = useState('');
  1242. const submitCustom = () => {
  1243. const value = Number(customValue);
  1244. if (!Number.isFinite(value)) return;
  1245. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1246. };
  1247. return (
  1248. <div className={`rounded-lg border p-2 ${isActive ? 'border-amber-400/60 bg-amber-400/10' : 'border-bambu-dark-tertiary bg-bambu-dark'}`}>
  1249. <div className="mb-1.5 flex items-center justify-between gap-2">
  1250. <span className={`text-xs font-medium ${isActive ? 'text-amber-300' : 'text-white'}`}>{label}</span>
  1251. <span className="text-[10px] text-bambu-gray">
  1252. {Math.round(current ?? 0)}°C
  1253. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1254. </span>
  1255. </div>
  1256. <div className="grid grid-cols-2 gap-1">
  1257. {options.map(option => (
  1258. <button
  1259. key={`${label}-${option.value}`}
  1260. type="button"
  1261. disabled={isPending}
  1262. onClick={() => onSubmit(option.value)}
  1263. 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"
  1264. >
  1265. {option.label}
  1266. </button>
  1267. ))}
  1268. </div>
  1269. <form
  1270. className="mt-1.5 flex gap-1"
  1271. onSubmit={(e) => {
  1272. e.preventDefault();
  1273. submitCustom();
  1274. }}
  1275. >
  1276. <input
  1277. type="number"
  1278. min={0}
  1279. max={320}
  1280. step={1}
  1281. value={customValue}
  1282. onChange={e => setCustomValue(e.target.value)}
  1283. placeholder="Custom"
  1284. 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"
  1285. />
  1286. <button
  1287. type="submit"
  1288. disabled={isPending || customValue.trim() === ''}
  1289. 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"
  1290. >
  1291. Set
  1292. </button>
  1293. </form>
  1294. </div>
  1295. );
  1296. }
  1297. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1298. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1299. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1300. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1301. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1302. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1303. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1304. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1305. };
  1306. /** Classify a printer into one of the UI status buckets. */
  1307. function classifyPrinterStatus(
  1308. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1309. ): PrinterState {
  1310. if (!status?.connected) return 'offline';
  1311. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1312. if (hmsErrors.length > 0) return 'error';
  1313. switch (status.state) {
  1314. case 'RUNNING': return 'printing';
  1315. case 'PAUSE': return 'paused';
  1316. case 'FINISH': return 'finished';
  1317. // FAILED without an active HMS error is the printer's terminal state after
  1318. // any unsuccessful end — including user-cancellations. Treat the same as
  1319. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1320. // HMS code is actually attached (handled by the early-return above).
  1321. case 'FAILED': return 'finished';
  1322. default: return 'idle';
  1323. }
  1324. }
  1325. /**
  1326. * Get human-readable status display text for a printer.
  1327. * Uses stg_cur_name for detailed calibration/preparation stages,
  1328. * otherwise formats the gcode_state nicely.
  1329. */
  1330. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1331. // If we have a specific stage name (calibration, heating, etc.), use it
  1332. if (stg_cur_name) {
  1333. return stg_cur_name;
  1334. }
  1335. // Format the gcode_state nicely
  1336. switch (state) {
  1337. case 'RUNNING':
  1338. return 'Printing';
  1339. case 'PAUSE':
  1340. return 'Paused';
  1341. case 'FINISH':
  1342. return 'Finished';
  1343. case 'FAILED':
  1344. return 'Failed';
  1345. case 'IDLE':
  1346. return 'Idle';
  1347. default:
  1348. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1349. }
  1350. }
  1351. // Bambu models that ship with an enclosure chamber fan (firmware field
  1352. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1353. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1354. // widget is hidden in fanItems instead of rendered greyed-out.
  1355. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1356. 'X1C',
  1357. 'X1',
  1358. 'X1E',
  1359. 'X2D',
  1360. 'P1S',
  1361. 'P2S',
  1362. 'H2D',
  1363. 'H2D Pro',
  1364. 'H2C',
  1365. 'H2S',
  1366. ]);
  1367. // Map SSDP model codes to display names
  1368. function mapModelCode(ssdpModel: string | null): string {
  1369. if (!ssdpModel) return '';
  1370. const modelMap: Record<string, string> = {
  1371. // H2 Series
  1372. 'O1D': 'H2D',
  1373. 'O1E': 'H2D Pro',
  1374. 'O2D': 'H2D Pro',
  1375. 'O1C': 'H2C',
  1376. 'O1C2': 'H2C',
  1377. 'O1S': 'H2S',
  1378. // X1 Series
  1379. 'BL-P001': 'X1C',
  1380. 'BL-P002': 'X1',
  1381. 'BL-P003': 'X1E',
  1382. // X2 Series
  1383. 'N6': 'X2D',
  1384. // A2 Series
  1385. 'N9': 'A2L',
  1386. // P Series
  1387. 'C11': 'P1S',
  1388. 'C12': 'P1P',
  1389. 'C13': 'P2S',
  1390. // A1 Series
  1391. 'N2S': 'A1',
  1392. 'N1': 'A1 Mini',
  1393. // Direct matches
  1394. 'X1C': 'X1C',
  1395. 'X1': 'X1',
  1396. 'X1E': 'X1E',
  1397. 'X2D': 'X2D',
  1398. 'P1S': 'P1S',
  1399. 'P1P': 'P1P',
  1400. 'P2S': 'P2S',
  1401. 'A1': 'A1',
  1402. 'A1 Mini': 'A1 Mini',
  1403. 'A2L': 'A2L',
  1404. 'H2D': 'H2D',
  1405. 'H2D Pro': 'H2D Pro',
  1406. 'H2C': 'H2C',
  1407. 'H2S': 'H2S',
  1408. };
  1409. return modelMap[ssdpModel] || ssdpModel;
  1410. }
  1411. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1412. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1413. // • User-defined friendly name (editable, protected by printers:update)
  1414. // • AMS serial number
  1415. // • AMS firmware version
  1416. export function AmsNameHoverCard({
  1417. ams,
  1418. printerId,
  1419. label,
  1420. amsLabels,
  1421. canEdit,
  1422. onSaved,
  1423. children,
  1424. }: {
  1425. ams: import('../api/client').AMSUnit;
  1426. printerId: number;
  1427. label: string; // auto-generated label, e.g. "AMS-A"
  1428. amsLabels?: Record<number, string>;
  1429. canEdit: boolean;
  1430. onSaved: () => void;
  1431. children: React.ReactNode;
  1432. }) {
  1433. const { t } = useTranslation();
  1434. const [isVisible, setIsVisible] = useState(false);
  1435. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1436. const [editValue, setEditValue] = useState('');
  1437. const [isSaving, setIsSaving] = useState(false);
  1438. const [saveError, setSaveError] = useState<string | null>(null);
  1439. const [isInputFocused, setIsInputFocused] = useState(false);
  1440. const triggerRef = useRef<HTMLDivElement>(null);
  1441. const cardRef = useRef<HTMLDivElement>(null);
  1442. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1443. useEffect(() => {
  1444. if (isVisible) {
  1445. setEditValue(amsLabels?.[ams.id] ?? '');
  1446. setSaveError(null);
  1447. requestAnimationFrame(() => {
  1448. if (triggerRef.current && cardRef.current) {
  1449. const rect = triggerRef.current.getBoundingClientRect();
  1450. const spaceAbove = rect.top - 56;
  1451. const spaceBelow = window.innerHeight - rect.bottom;
  1452. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1453. }
  1454. });
  1455. }
  1456. }, [isVisible, amsLabels, ams.id]);
  1457. const handleMouseEnter = () => {
  1458. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1459. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1460. };
  1461. const handleMouseLeave = () => {
  1462. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1463. if (!isInputFocused) {
  1464. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1465. }
  1466. };
  1467. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1468. const handleSave = async () => {
  1469. if (!canEdit) return;
  1470. setIsSaving(true);
  1471. setSaveError(null);
  1472. try {
  1473. const trimmed = editValue.trim();
  1474. if (trimmed) {
  1475. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1476. } else {
  1477. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1478. }
  1479. onSaved();
  1480. setIsVisible(false);
  1481. } catch (err) {
  1482. setSaveError(err instanceof Error ? err.message : String(err));
  1483. } finally {
  1484. setIsSaving(false);
  1485. }
  1486. };
  1487. const handleClear = async () => {
  1488. if (!canEdit) return;
  1489. setIsSaving(true);
  1490. setSaveError(null);
  1491. try {
  1492. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1493. onSaved();
  1494. setIsVisible(false);
  1495. } catch (err) {
  1496. setSaveError(err instanceof Error ? err.message : String(err));
  1497. } finally {
  1498. setIsSaving(false);
  1499. }
  1500. };
  1501. return (
  1502. <div
  1503. ref={triggerRef}
  1504. className="relative inline-block"
  1505. onMouseEnter={handleMouseEnter}
  1506. onMouseLeave={handleMouseLeave}
  1507. >
  1508. {children}
  1509. {isVisible && (
  1510. <div
  1511. ref={cardRef}
  1512. className={`
  1513. absolute left-0 z-50
  1514. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1515. animate-in fade-in-0 zoom-in-95 duration-150
  1516. `}
  1517. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1518. onMouseEnter={handleMouseEnter}
  1519. onMouseLeave={handleMouseLeave}
  1520. >
  1521. <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">
  1522. {/* AMS auto-label */}
  1523. <div className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1524. {/* Serial number */}
  1525. <div className="flex items-center justify-between gap-2">
  1526. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1527. {t('printers.amsPopup.serialNumber')}
  1528. </span>
  1529. <span className="text-[10px] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1530. </div>
  1531. {/* Firmware version */}
  1532. <div className="flex items-center justify-between gap-2">
  1533. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1534. {t('printers.amsPopup.firmwareVersion')}
  1535. </span>
  1536. <span className="text-[10px] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1537. </div>
  1538. {/* Friendly name editor */}
  1539. <div className="space-y-1">
  1540. <div className="flex items-center gap-2">
  1541. <span className="text-[10px] text-bambu-gray font-medium shrink-0">
  1542. {t('printers.amsPopup.friendlyName')}
  1543. </span>
  1544. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1545. </div>
  1546. <input
  1547. type="text"
  1548. value={editValue}
  1549. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1550. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1551. onFocus={() => setIsInputFocused(true)}
  1552. onBlur={() => {
  1553. setIsInputFocused(false);
  1554. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1555. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1556. }}
  1557. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1558. disabled={!canEdit}
  1559. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1560. 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"
  1561. maxLength={100}
  1562. />
  1563. {canEdit && (
  1564. <div className="space-y-1">
  1565. {saveError && (
  1566. <p className="text-[10px] text-red-400 break-words">{saveError}</p>
  1567. )}
  1568. <div className="flex gap-1 justify-end">
  1569. <button
  1570. onClick={handleSave}
  1571. disabled={isSaving}
  1572. className="px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1573. >
  1574. {t('printers.amsPopup.save')}
  1575. </button>
  1576. {amsLabels?.[ams.id] && (
  1577. <button
  1578. onClick={handleClear}
  1579. disabled={isSaving}
  1580. 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"
  1581. >
  1582. {t('printers.amsPopup.clear')}
  1583. </button>
  1584. )}
  1585. </div>
  1586. </div>
  1587. )}
  1588. </div>
  1589. </div>
  1590. </div>
  1591. )}
  1592. </div>
  1593. );
  1594. }
  1595. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1596. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1597. const DRYING_PRESETS: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }> = {
  1598. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1599. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1600. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1601. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1602. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1603. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1604. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1605. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1606. };
  1607. function PrinterCard({
  1608. printer,
  1609. hideIfDisconnected,
  1610. maintenanceInfo,
  1611. viewMode = 'expanded',
  1612. cardSize = 2,
  1613. amsThresholds,
  1614. spoolmanEnabled = false,
  1615. linkedSpools,
  1616. spoolmanUrl,
  1617. spoolmanSyncMode,
  1618. onGetAssignment,
  1619. onUnassignSpool,
  1620. spoolmanSpools,
  1621. spoolmanSlotAssignments,
  1622. spoolmanLoading = false,
  1623. onUnassignSpoolmanSpool,
  1624. timeFormat = 'system',
  1625. cameraViewMode = 'window',
  1626. onOpenEmbeddedCamera,
  1627. checkPrinterFirmware = true,
  1628. dryingPresets = DRYING_PRESETS,
  1629. requirePlateClear = false,
  1630. selectionMode = false,
  1631. isSelected = false,
  1632. onToggleSelect,
  1633. onOpenCompactCard,
  1634. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1635. bedTempPresets = BED_TEMP_DEFAULTS,
  1636. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1637. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1638. }: {
  1639. printer: Printer;
  1640. hideIfDisconnected?: boolean;
  1641. maintenanceInfo?: PrinterMaintenanceInfo;
  1642. viewMode?: ViewMode;
  1643. cardSize?: number;
  1644. amsThresholds?: {
  1645. humidityGood: number;
  1646. humidityFair: number;
  1647. tempGood: number;
  1648. tempFair: number;
  1649. };
  1650. spoolmanEnabled?: boolean;
  1651. hasUnlinkedSpools?: boolean;
  1652. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1653. spoolmanUrl?: string | null;
  1654. spoolmanSyncMode?: string | null;
  1655. spoolAssignments?: SpoolAssignment[];
  1656. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1657. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1658. spoolmanSpools?: InventorySpool[];
  1659. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1660. spoolmanLoading?: boolean;
  1661. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1662. timeFormat?: 'system' | '12h' | '24h';
  1663. cameraViewMode?: 'window' | 'embedded';
  1664. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1665. checkPrinterFirmware?: boolean;
  1666. dryingPresets?: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }>;
  1667. requirePlateClear?: boolean;
  1668. selectionMode?: boolean;
  1669. isSelected?: boolean;
  1670. onToggleSelect?: (id: number) => void;
  1671. onOpenCompactCard?: (id: number) => void;
  1672. nozzleTempPresets?: readonly [number, number, number];
  1673. bedTempPresets?: readonly [number, number, number];
  1674. chamberTempPresets?: readonly [number, number, number];
  1675. fanSpeedPresets?: readonly [number, number, number];
  1676. }) {
  1677. const { t } = useTranslation();
  1678. const queryClient = useQueryClient();
  1679. const navigate = useNavigate();
  1680. const { showToast } = useToast();
  1681. const { hasPermission } = useAuth();
  1682. const [showMenu, setShowMenu] = useState(false);
  1683. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1684. const [deleteArchives, setDeleteArchives] = useState(true);
  1685. const [showEditModal, setShowEditModal] = useState(false);
  1686. const [showFileManager, setShowFileManager] = useState(false);
  1687. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1688. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1689. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1690. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1691. const [showHMSModal, setShowHMSModal] = useState(false);
  1692. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1693. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1694. const [showStopConfirm, setShowStopConfirm] = useState(false);
  1695. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  1696. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  1697. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  1698. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  1699. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  1700. const [bedJogStep, setBedJogStep] = useState<number>(10);
  1701. const [showNotHomedModal, setShowNotHomedModal] = useState<null | { distance: number }>(null);
  1702. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  1703. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  1704. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  1705. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  1706. const [showDiagnostic, setShowDiagnostic] = useState(false);
  1707. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  1708. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  1709. // AMS drying popover state: which AMS unit has the popover open
  1710. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  1711. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  1712. const [dryingFilament, setDryingFilament] = useState('PLA');
  1713. const [dryingTemp, setDryingTemp] = useState(50);
  1714. const [dryingDuration, setDryingDuration] = useState(4);
  1715. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  1716. const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
  1717. const [isDraggingFile, setIsDraggingFile] = useState(false);
  1718. const [isDropUploading, setIsDropUploading] = useState(false);
  1719. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  1720. const dragCounterRef = useRef(0);
  1721. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  1722. amsId: number;
  1723. amsLabel: string;
  1724. mode: 'humidity' | 'temperature';
  1725. } | null>(null);
  1726. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  1727. initialKind: HeaterSensorKind;
  1728. availableKinds: HeaterSensorKind[];
  1729. } | null>(null);
  1730. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  1731. tagUid: string;
  1732. trayUuid: string;
  1733. printerId: number;
  1734. amsId: number;
  1735. trayId: number;
  1736. } | null>(null);
  1737. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  1738. printerId: number;
  1739. amsId: number;
  1740. trayId: number;
  1741. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  1742. } | null>(null);
  1743. const [configureSlotModal, setConfigureSlotModal] = useState<{
  1744. amsId: number;
  1745. trayId: number;
  1746. trayCount: number;
  1747. trayType?: string;
  1748. trayColor?: string;
  1749. traySubBrands?: string;
  1750. trayInfoIdx?: string;
  1751. extruderId?: number;
  1752. caliIdx?: number | null;
  1753. savedPresetId?: string;
  1754. } | null>(null);
  1755. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  1756. const [plateCheckResult, setPlateCheckResult] = useState<{
  1757. is_empty: boolean;
  1758. confidence: number;
  1759. difference_percent: number;
  1760. message: string;
  1761. debug_image_url?: string;
  1762. needs_calibration: boolean;
  1763. light_warning?: boolean;
  1764. reference_count?: number;
  1765. max_references?: number;
  1766. roi?: { x: number; y: number; w: number; h: number };
  1767. } | null>(null);
  1768. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  1769. const [isCalibrating, setIsCalibrating] = useState(false);
  1770. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  1771. const [isSavingRoi, setIsSavingRoi] = useState(false);
  1772. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  1773. const { data: status } = useQuery({
  1774. queryKey: ['printerStatus', printer.id],
  1775. queryFn: () => api.getPrinterStatus(printer.id),
  1776. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  1777. });
  1778. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  1779. const { data: firmwareInfo } = useQuery({
  1780. queryKey: ['firmwareUpdate', printer.id],
  1781. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  1782. staleTime: 5 * 60 * 1000,
  1783. refetchInterval: 5 * 60 * 1000,
  1784. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  1785. });
  1786. // Collect unique tray_info_idx values for cloud filament info lookup
  1787. const trayInfoIds = useMemo(() => {
  1788. const ids = new Set<string>();
  1789. if (status?.ams) {
  1790. for (const ams of status.ams) {
  1791. for (const tray of ams.tray || []) {
  1792. if (tray.tray_info_idx) {
  1793. ids.add(tray.tray_info_idx);
  1794. }
  1795. }
  1796. }
  1797. }
  1798. for (const vt of status?.vt_tray ?? []) {
  1799. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  1800. }
  1801. if (status?.nozzle_rack) {
  1802. for (const slot of status.nozzle_rack) {
  1803. if (slot.filament_id) {
  1804. ids.add(slot.filament_id);
  1805. }
  1806. }
  1807. }
  1808. return Array.from(ids);
  1809. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  1810. // Collect loaded filament types for queue widget filtering
  1811. const loadedFilamentTypes = useMemo(() => {
  1812. const types = new Set<string>();
  1813. if (status?.ams) {
  1814. for (const ams of status.ams) {
  1815. for (const tray of ams.tray || []) {
  1816. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  1817. }
  1818. }
  1819. }
  1820. for (const vt of status?.vt_tray ?? []) {
  1821. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  1822. }
  1823. return types;
  1824. }, [status?.ams, status?.vt_tray]);
  1825. // Collect loaded filament type+color pairs for queue widget override matching
  1826. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  1827. const loadedFilaments = useMemo(() => {
  1828. const filaments = new Set<string>();
  1829. if (status?.ams) {
  1830. for (const ams of status.ams) {
  1831. for (const tray of ams.tray || []) {
  1832. if (tray.tray_type && tray.tray_color) {
  1833. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1834. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  1835. }
  1836. }
  1837. }
  1838. }
  1839. for (const vt of status?.vt_tray ?? []) {
  1840. if (vt.tray_type && vt.tray_color) {
  1841. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1842. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  1843. }
  1844. }
  1845. return filaments;
  1846. }, [status?.ams, status?.vt_tray]);
  1847. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  1848. const { data: filamentInfo } = useQuery({
  1849. queryKey: ['filamentInfo', trayInfoIds],
  1850. queryFn: () => api.getFilamentInfo(trayInfoIds),
  1851. enabled: trayInfoIds.length > 0,
  1852. staleTime: 5 * 60 * 1000, // 5 minutes
  1853. });
  1854. // Fetch slot preset mappings (stores preset name for user-configured slots)
  1855. const { data: slotPresets } = useQuery({
  1856. queryKey: ['slotPresets', printer.id],
  1857. queryFn: () => api.getSlotPresets(printer.id),
  1858. staleTime: 2 * 60 * 1000, // 2 minutes
  1859. });
  1860. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  1861. // Only queried when there's a running print backed by an archive; shared
  1862. // React Query cache with the Queue / Archives pages keeps it cheap.
  1863. const activeArchiveId =
  1864. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  1865. const { data: activeArchivePlates } = useQuery({
  1866. queryKey: ['archive-plates', activeArchiveId],
  1867. queryFn: () => api.getArchivePlates(activeArchiveId!),
  1868. enabled: activeArchiveId != null,
  1869. staleTime: 5 * 60 * 1000,
  1870. });
  1871. const activePlateLabel = (() => {
  1872. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  1873. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  1874. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  1875. })();
  1876. // Fetch user-defined AMS friendly names from the database
  1877. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  1878. queryKey: ['amsLabels', printer.id],
  1879. queryFn: () => api.getAmsLabels(printer.id),
  1880. staleTime: 5 * 60 * 1000, // 5 minutes
  1881. });
  1882. // Cache WiFi signal to prevent it disappearing on updates
  1883. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  1884. useEffect(() => {
  1885. if (status?.wifi_signal != null) {
  1886. setCachedWifiSignal(status.wifi_signal);
  1887. }
  1888. }, [status?.wifi_signal]);
  1889. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  1890. // Cache connected state to prevent flicker when status briefly becomes undefined
  1891. const cachedConnected = useRef<boolean | undefined>(undefined);
  1892. useEffect(() => {
  1893. if (status?.connected !== undefined) {
  1894. cachedConnected.current = status.connected;
  1895. }
  1896. }, [status?.connected]);
  1897. const isConnected = status?.connected ?? cachedConnected.current;
  1898. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  1899. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  1900. useEffect(() => {
  1901. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  1902. cachedAmsExtruderMap.current = status.ams_extruder_map;
  1903. }
  1904. }, [status?.ams_extruder_map]);
  1905. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  1906. ? status.ams_extruder_map
  1907. : cachedAmsExtruderMap.current;
  1908. // Cache AMS data to prevent it disappearing on idle/offline printers
  1909. const cachedAmsData = useRef<AMSUnit[]>([]);
  1910. useEffect(() => {
  1911. if (status?.ams && status.ams.length > 0) {
  1912. cachedAmsData.current = status.ams;
  1913. }
  1914. }, [status?.ams]);
  1915. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  1916. // Cache tray_now to prevent flickering when undefined values come in
  1917. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  1918. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  1919. const cachedTrayNow = useRef<number | undefined>(undefined);
  1920. const currentTrayNow = status?.tray_now;
  1921. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  1922. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  1923. cachedTrayNow.current = currentTrayNow;
  1924. } else if (currentTrayNow === 255) {
  1925. cachedTrayNow.current = undefined;
  1926. }
  1927. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  1928. ? currentTrayNow
  1929. : cachedTrayNow.current;
  1930. // Fetch smart plug for this printer
  1931. const { data: smartPlug } = useQuery({
  1932. queryKey: ['smartPlugByPrinter', printer.id],
  1933. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  1934. });
  1935. // Fetch script plugs for this printer (for multi-device control)
  1936. const { data: scriptPlugs } = useQuery({
  1937. queryKey: ['scriptPlugsByPrinter', printer.id],
  1938. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  1939. });
  1940. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  1941. const { data: plugStatus } = useQuery({
  1942. queryKey: ['smartPlugStatus', smartPlug?.id],
  1943. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  1944. enabled: !!smartPlug,
  1945. refetchInterval: 10000, // 10 seconds for real-time power display
  1946. });
  1947. // Fetch queue count for this printer
  1948. const { data: queueItems } = useQuery({
  1949. queryKey: ['queue', printer.id, 'pending'],
  1950. queryFn: () => api.getQueue(printer.id, 'pending'),
  1951. });
  1952. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  1953. // so the badge only shows on printers that can actually run the queued jobs.
  1954. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  1955. const queueCount = useMemo(() => {
  1956. if (!queueItems?.length) return 0;
  1957. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments).length;
  1958. }, [queueItems, loadedFilamentTypes, loadedFilaments]);
  1959. // Fetch currently printing queue item to show who started it (Issue #206)
  1960. const { data: printingQueueItems } = useQuery({
  1961. queryKey: ['queue', printer.id, 'printing'],
  1962. queryFn: () => api.getQueue(printer.id, 'printing'),
  1963. enabled: status?.state === 'RUNNING',
  1964. });
  1965. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  1966. const { data: reprintUser } = useQuery({
  1967. queryKey: ['currentPrintUser', printer.id],
  1968. queryFn: () => api.getCurrentPrintUser(printer.id),
  1969. enabled: status?.state === 'RUNNING',
  1970. });
  1971. // Combine both sources: queue item user takes precedence, then reprint user
  1972. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  1973. // Fetch last completed print for this printer
  1974. const { data: lastPrints } = useQuery({
  1975. queryKey: ['archives', printer.id, 'last'],
  1976. queryFn: () => api.getArchives(printer.id, 1, 0),
  1977. enabled: status?.connected && status?.state !== 'RUNNING',
  1978. });
  1979. const lastPrint = lastPrints?.[0];
  1980. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  1981. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  1982. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  1983. const activePrintName = status?.current_print && isPrintingOrPaused
  1984. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  1985. : null;
  1986. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  1987. useEffect(() => {
  1988. if (activePrintName) {
  1989. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  1990. } else if (!needsPlateClear) {
  1991. setRetainedPrintJob(null);
  1992. }
  1993. }, [activePrintName, needsPlateClear, status?.cover_url]);
  1994. const plateStatus = (() => {
  1995. if (!requirePlateClear || !status?.connected) return null;
  1996. if (isPrintingOrPaused) {
  1997. return {
  1998. label: t('printers.plateStatus.inUse'),
  1999. className: 'bg-blue-500/20 text-blue-400',
  2000. };
  2001. }
  2002. if (status.awaiting_plate_clear) {
  2003. return {
  2004. label: t('printers.plateStatus.notCleared'),
  2005. className: 'bg-yellow-500/20 text-yellow-400',
  2006. };
  2007. }
  2008. return {
  2009. label: t('printers.plateStatus.cleared'),
  2010. className: 'bg-status-ok/20 text-status-ok',
  2011. };
  2012. })();
  2013. const plateStatusPill = plateStatus ? (
  2014. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${plateStatus.className}`}>
  2015. {plateStatus.label}
  2016. </span>
  2017. ) : null;
  2018. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2019. const shouldHide = hideIfDisconnected && isConnected === false;
  2020. const deleteMutation = useMutation({
  2021. mutationFn: (options: { deleteArchives: boolean }) =>
  2022. api.deletePrinter(printer.id, options.deleteArchives),
  2023. onSuccess: () => {
  2024. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2025. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2026. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2027. },
  2028. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2029. });
  2030. const connectMutation = useMutation({
  2031. mutationFn: () => api.connectPrinter(printer.id),
  2032. onSuccess: () => {
  2033. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2034. },
  2035. });
  2036. const forceRefreshMutation = useMutation({
  2037. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2038. onSuccess: () => {
  2039. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2040. showToast(t('printers.forceRefreshSuccess'), 'success');
  2041. },
  2042. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2043. });
  2044. const unlinkSpoolMutation = useMutation({
  2045. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2046. onSuccess: (result) => {
  2047. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2048. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2049. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2050. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2051. },
  2052. onError: (error: Error) => {
  2053. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2054. },
  2055. });
  2056. // AMS drying mutations
  2057. const startDryingMutation = useMutation({
  2058. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2059. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2060. onSuccess: () => {
  2061. setDryingPopoverAmsId(null);
  2062. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2063. },
  2064. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2065. });
  2066. const stopDryingMutation = useMutation({
  2067. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2068. onSuccess: () => {
  2069. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2070. },
  2071. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2072. });
  2073. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2074. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2075. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2076. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2077. // showing the old backup state until the user reopens it.
  2078. const setAmsBackupMutation = useMutation({
  2079. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2080. onSuccess: (_data, enabled) => {
  2081. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2082. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2083. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2084. },
  2085. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2086. });
  2087. // Smart plug control mutations
  2088. const powerControlMutation = useMutation({
  2089. mutationFn: (action: 'on' | 'off') =>
  2090. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2091. onSuccess: () => {
  2092. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2093. },
  2094. });
  2095. const toggleAutoOffMutation = useMutation({
  2096. mutationFn: (enabled: boolean) =>
  2097. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2098. onSuccess: () => {
  2099. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2100. // Also invalidate the smart-plugs list to keep Settings page in sync
  2101. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2102. },
  2103. });
  2104. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2105. const runScriptMutation = useMutation({
  2106. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2107. onSuccess: () => {
  2108. showToast(t('printers.toast.scriptTriggered'));
  2109. },
  2110. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2111. });
  2112. // Print control mutations
  2113. const stopPrintMutation = useMutation({
  2114. mutationFn: () => api.stopPrint(printer.id),
  2115. onSuccess: () => {
  2116. showToast(t('printers.toast.printStopped'));
  2117. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2118. },
  2119. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2120. });
  2121. const pausePrintMutation = useMutation({
  2122. mutationFn: () => api.pausePrint(printer.id),
  2123. onSuccess: () => {
  2124. showToast(t('printers.toast.printPaused'));
  2125. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2126. },
  2127. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2128. });
  2129. const resumePrintMutation = useMutation({
  2130. mutationFn: () => api.resumePrint(printer.id),
  2131. onSuccess: () => {
  2132. showToast(t('printers.toast.printResumed'));
  2133. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2134. },
  2135. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2136. });
  2137. const clearPlateMutation = useMutation({
  2138. mutationFn: () => api.clearPlate(printer.id),
  2139. onSuccess: () => {
  2140. showToast(t('queue.clearPlateSuccess'));
  2141. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2142. old ? { ...old, awaiting_plate_clear: false } : old
  2143. );
  2144. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2145. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2146. },
  2147. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2148. });
  2149. const nozzleTemperatureMutation = useMutation({
  2150. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2151. api.setNozzleTemperature(printer.id, target, nozzle),
  2152. onSuccess: (result) => {
  2153. setStatusControlMenu(null);
  2154. showToast(result.message);
  2155. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2156. },
  2157. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2158. });
  2159. const bedTemperatureMutation = useMutation({
  2160. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2161. onSuccess: (result) => {
  2162. setStatusControlMenu(null);
  2163. showToast(result.message);
  2164. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2165. },
  2166. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2167. });
  2168. const chamberTemperatureMutation = useMutation({
  2169. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2170. onSuccess: (result) => {
  2171. setStatusControlMenu(null);
  2172. showToast(result.message);
  2173. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2174. },
  2175. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2176. });
  2177. const fanSpeedMutation = useMutation({
  2178. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'chamber'; speed: number }) =>
  2179. api.setFanSpeed(printer.id, fan, speed),
  2180. onMutate: async ({ fan, speed }) => {
  2181. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2182. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2183. const fanField = {
  2184. part: 'cooling_fan_speed',
  2185. aux: 'big_fan1_speed',
  2186. chamber: 'big_fan2_speed',
  2187. }[fan];
  2188. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2189. old ? { ...old, [fanField]: speed } : old
  2190. );
  2191. return { previousStatus };
  2192. },
  2193. onSuccess: (result) => {
  2194. setStatusControlMenu(null);
  2195. showToast(result.message);
  2196. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2197. },
  2198. onError: (error: Error, _variables, context) => {
  2199. if (context?.previousStatus) {
  2200. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2201. }
  2202. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2203. },
  2204. });
  2205. const selectExtruderMutation = useMutation({
  2206. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2207. onMutate: async (extruder) => {
  2208. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2209. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2210. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2211. old ? { ...old, active_extruder: extruder } : old
  2212. );
  2213. return { previousStatus };
  2214. },
  2215. onSuccess: (result) => {
  2216. setStatusControlMenu(null);
  2217. showToast(result.message);
  2218. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2219. },
  2220. onError: (error: Error, _extruder, context) => {
  2221. if (context?.previousStatus) {
  2222. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2223. }
  2224. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2225. },
  2226. });
  2227. // Chamber light mutation with optimistic update
  2228. const chamberLightMutation = useMutation({
  2229. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2230. onMutate: async (on) => {
  2231. // Cancel any outgoing refetches
  2232. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2233. // Snapshot the previous value
  2234. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2235. // Optimistically update
  2236. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2237. ...old,
  2238. chamber_light: on,
  2239. }));
  2240. return { previousStatus };
  2241. },
  2242. onSuccess: (_, on) => {
  2243. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2244. },
  2245. onError: (error: Error, _, context) => {
  2246. // Rollback on error
  2247. if (context?.previousStatus) {
  2248. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2249. }
  2250. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2251. },
  2252. });
  2253. // Print speed mutation with optimistic update
  2254. const printSpeedMutation = useMutation({
  2255. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2256. onMutate: async (mode) => {
  2257. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2258. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2259. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2260. ...old,
  2261. speed_level: mode,
  2262. }));
  2263. return { previousStatus };
  2264. },
  2265. onError: (error: Error, _, context) => {
  2266. if (context?.previousStatus) {
  2267. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2268. }
  2269. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2270. },
  2271. });
  2272. const airductMutation = useMutation({
  2273. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2274. onMutate: async (mode) => {
  2275. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2276. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2277. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2278. ...old,
  2279. airduct_mode: mode === 'cooling' ? 0 : 1,
  2280. }));
  2281. return { previousStatus };
  2282. },
  2283. onError: (error: Error, _, context) => {
  2284. if (context?.previousStatus) {
  2285. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2286. }
  2287. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2288. },
  2289. });
  2290. const bedJogMutation = useMutation({
  2291. mutationFn: ({ distance, force }: { distance: number; force?: boolean }) =>
  2292. api.bedJog(printer.id, distance, force ?? false),
  2293. onError: (error: Error) =>
  2294. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2295. });
  2296. const xyJogMutation = useMutation({
  2297. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2298. api.xyJog(printer.id, x, y),
  2299. onError: (error: Error) =>
  2300. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2301. });
  2302. const extruderJogMutation = useMutation({
  2303. mutationFn: (distance: number) =>
  2304. api.extruderJog(printer.id, distance),
  2305. onError: (error: Error) =>
  2306. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2307. });
  2308. const homeAxesMutation = useMutation({
  2309. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2310. onSuccess: () => {
  2311. // Flip the session-scoped "warned" flag so the next bed-jog click doesn't re-prompt
  2312. // the not-homed modal. The flag is the same one "Move anyway" sets; after a successful
  2313. // auto-home request the printer is (or will shortly be) in a known-homed state, so
  2314. // prompting again in the same session is noise — #1052 follow-up.
  2315. try { sessionStorage.setItem(`bambuddy.bedJog.warned.${printer.id}`, '1'); } catch { /* ignore */ }
  2316. showToast(t('printers.bedJog.homingStarted'));
  2317. },
  2318. onError: (error: Error) =>
  2319. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2320. });
  2321. // Plate detection setting mutation
  2322. const plateDetectionMutation = useMutation({
  2323. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2324. onSuccess: () => {
  2325. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2326. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2327. },
  2328. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2329. });
  2330. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2331. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2332. // metrics, and the print picker — so flipping this flag puts the printer
  2333. // out of service across every consumer in one place. Used from the
  2334. // overflow menu and EditPrinterModal.
  2335. const maintenanceMutation = useMutation({
  2336. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2337. onSuccess: (_data, isActive) => {
  2338. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2339. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2340. showToast(
  2341. isActive
  2342. ? t('printers.maintenance.toastExited', { name: printer.name })
  2343. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2344. 'success',
  2345. );
  2346. },
  2347. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2348. });
  2349. // Confirm before entering maintenance on a printing printer (entering mode
  2350. // disconnects MQTT, which stops progress tracking + completion notifications
  2351. // for the in-flight job).
  2352. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2353. const handleEnterMaintenance = () => {
  2354. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2355. setConfirmMaintenanceEnter(true);
  2356. } else {
  2357. maintenanceMutation.mutate(false);
  2358. }
  2359. };
  2360. // Query for printable objects (for skip functionality)
  2361. // Fetch when printing with 2+ objects OR when modal is open
  2362. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2363. const { data: objectsData } = useQuery({
  2364. queryKey: ['printableObjects', printer.id],
  2365. queryFn: () => api.getPrintableObjects(printer.id),
  2366. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2367. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2368. });
  2369. // State for tracking which AMS slot is being refreshed
  2370. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2371. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2372. const seenBusyStateRef = useRef<boolean>(false);
  2373. // Fallback timeout ref
  2374. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2375. // Minimum display time passed
  2376. const minTimePassedRef = useRef<boolean>(false);
  2377. // AMS slot refresh mutation
  2378. const refreshAmsSlotMutation = useMutation({
  2379. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2380. api.refreshAmsSlot(printer.id, amsId, slotId),
  2381. onMutate: ({ amsId, slotId }) => {
  2382. // Clear any existing timeout
  2383. if (refreshTimeoutRef.current) {
  2384. clearTimeout(refreshTimeoutRef.current);
  2385. }
  2386. // Reset state
  2387. seenBusyStateRef.current = false;
  2388. minTimePassedRef.current = false;
  2389. setRefreshingSlot({ amsId, slotId });
  2390. // Minimum display time (2 seconds)
  2391. setTimeout(() => {
  2392. minTimePassedRef.current = true;
  2393. }, 2000);
  2394. // Fallback timeout (30 seconds max)
  2395. refreshTimeoutRef.current = setTimeout(() => {
  2396. setRefreshingSlot(null);
  2397. }, 30000);
  2398. },
  2399. onSuccess: (data) => {
  2400. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2401. },
  2402. onError: (error: Error) => {
  2403. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2404. if (refreshTimeoutRef.current) {
  2405. clearTimeout(refreshTimeoutRef.current);
  2406. }
  2407. setRefreshingSlot(null);
  2408. },
  2409. });
  2410. // AMS load/unload mutations (#891)
  2411. const loadAmsTrayMutation = useMutation({
  2412. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2413. onSuccess: (data) => {
  2414. showToast(data.message || t('printers.toast.loadInitiated'));
  2415. },
  2416. onError: (error: Error) => {
  2417. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2418. },
  2419. });
  2420. const unloadAmsMutation = useMutation({
  2421. mutationFn: () => api.unloadAms(printer.id),
  2422. onSuccess: (data) => {
  2423. showToast(data.message || t('printers.toast.unloadInitiated'));
  2424. },
  2425. onError: (error: Error) => {
  2426. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2427. },
  2428. });
  2429. // Plate references state
  2430. const [plateReferences, setPlateReferences] = useState<{
  2431. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2432. max_references: number;
  2433. } | null>(null);
  2434. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2435. // Fetch plate references
  2436. const fetchPlateReferences = async () => {
  2437. try {
  2438. const data = await api.getPlateReferences(printer.id);
  2439. setPlateReferences(data);
  2440. } catch {
  2441. // Ignore errors - references will show as empty
  2442. }
  2443. };
  2444. // Toggle plate detection enabled/disabled
  2445. const handleTogglePlateDetection = () => {
  2446. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2447. };
  2448. // Open plate detection management modal (for calibration/references)
  2449. const handleOpenPlateManagement = async () => {
  2450. setIsCheckingPlate(true);
  2451. setPlateCheckResult(null);
  2452. // Auto-turn on light if it's off
  2453. const lightWasOff = status?.chamber_light === false;
  2454. setPlateCheckLightWasOff(lightWasOff);
  2455. if (lightWasOff) {
  2456. await api.setChamberLight(printer.id, true);
  2457. // Wait for light to physically turn on and camera to adjust exposure
  2458. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2459. await new Promise(resolve => setTimeout(resolve, 2500));
  2460. }
  2461. try {
  2462. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2463. setPlateCheckResult(result);
  2464. fetchPlateReferences();
  2465. } catch (error) {
  2466. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2467. // Restore light if check failed
  2468. if (lightWasOff) {
  2469. await api.setChamberLight(printer.id, false);
  2470. setPlateCheckLightWasOff(false);
  2471. }
  2472. } finally {
  2473. setIsCheckingPlate(false);
  2474. }
  2475. };
  2476. // Close plate check modal and restore light state
  2477. const closePlateCheckModal = useCallback(async () => {
  2478. setPlateCheckResult(null);
  2479. // Restore light to original state if we turned it on
  2480. if (plateCheckLightWasOff) {
  2481. await api.setChamberLight(printer.id, false);
  2482. setPlateCheckLightWasOff(false);
  2483. }
  2484. }, [plateCheckLightWasOff, printer.id]);
  2485. // Calibrate plate detection handler
  2486. const handleCalibratePlate = async (label?: string) => {
  2487. setIsCalibrating(true);
  2488. try {
  2489. const result = await api.calibratePlateDetection(printer.id, { label });
  2490. if (result.success) {
  2491. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2492. // Refresh references and re-check
  2493. fetchPlateReferences();
  2494. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2495. setPlateCheckResult(checkResult);
  2496. } else {
  2497. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2498. }
  2499. } catch (error) {
  2500. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2501. } finally {
  2502. setIsCalibrating(false);
  2503. }
  2504. };
  2505. // Update reference label
  2506. const handleUpdateRefLabel = async (index: number, label: string) => {
  2507. try {
  2508. await api.updatePlateReferenceLabel(printer.id, index, label);
  2509. setEditingRefLabel(null);
  2510. fetchPlateReferences();
  2511. } catch (error) {
  2512. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  2513. }
  2514. };
  2515. // Delete reference
  2516. const handleDeleteRef = async (index: number) => {
  2517. try {
  2518. await api.deletePlateReference(printer.id, index);
  2519. showToast(t('printers.toast.referenceDeleted'), 'success');
  2520. fetchPlateReferences();
  2521. // Re-check to update counts
  2522. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2523. setPlateCheckResult(checkResult);
  2524. } catch (error) {
  2525. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  2526. }
  2527. };
  2528. // Save ROI settings
  2529. const handleSaveRoi = async () => {
  2530. if (!editingRoi) return;
  2531. setIsSavingRoi(true);
  2532. try {
  2533. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  2534. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  2535. setEditingRoi(null);
  2536. // Re-check to see new ROI in action
  2537. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2538. setPlateCheckResult(checkResult);
  2539. } catch (error) {
  2540. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  2541. } finally {
  2542. setIsSavingRoi(false);
  2543. }
  2544. };
  2545. // Close plate check modal on Escape key
  2546. useEffect(() => {
  2547. const handleEscape = (e: KeyboardEvent) => {
  2548. if (e.key === 'Escape' && plateCheckResult) {
  2549. closePlateCheckModal();
  2550. }
  2551. };
  2552. window.addEventListener('keydown', handleEscape);
  2553. return () => window.removeEventListener('keydown', handleEscape);
  2554. }, [plateCheckResult, closePlateCheckModal]);
  2555. // Watch ams_status_main to detect when RFID read completes
  2556. // ams_status_main: 0=idle, 2=rfid_identifying
  2557. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2558. useEffect(() => {
  2559. if (!refreshingSlot) return;
  2560. const amsStatus = status?.ams_status_main ?? 0;
  2561. // Track when we see non-idle state (printer is working)
  2562. if (amsStatus !== 0) {
  2563. seenBusyStateRef.current = true;
  2564. // Cancel any deferred clear since we're back to busy
  2565. if (deferredClearRef.current) {
  2566. clearTimeout(deferredClearRef.current);
  2567. deferredClearRef.current = null;
  2568. }
  2569. }
  2570. // When we've seen busy and now idle, clear (with min time check)
  2571. if (seenBusyStateRef.current && amsStatus === 0) {
  2572. if (minTimePassedRef.current) {
  2573. // Min time passed - clear now
  2574. if (refreshTimeoutRef.current) {
  2575. clearTimeout(refreshTimeoutRef.current);
  2576. }
  2577. setRefreshingSlot(null);
  2578. } else {
  2579. // Schedule clear after min time (2 seconds from start)
  2580. if (!deferredClearRef.current) {
  2581. deferredClearRef.current = setTimeout(() => {
  2582. if (refreshTimeoutRef.current) {
  2583. clearTimeout(refreshTimeoutRef.current);
  2584. }
  2585. setRefreshingSlot(null);
  2586. }, 2000);
  2587. }
  2588. }
  2589. }
  2590. return () => {
  2591. if (deferredClearRef.current) {
  2592. clearTimeout(deferredClearRef.current);
  2593. }
  2594. };
  2595. }, [status?.ams_status_main, refreshingSlot]);
  2596. useEffect(() => {
  2597. if (!showMenu) return;
  2598. const handleClickOutside = (event: MouseEvent) => {
  2599. const target = event.target as Node;
  2600. if (!printerActionsMenuRef.current?.contains(target)) {
  2601. setShowMenu(false);
  2602. }
  2603. };
  2604. document.addEventListener('mousedown', handleClickOutside);
  2605. return () => document.removeEventListener('mousedown', handleClickOutside);
  2606. }, [showMenu]);
  2607. if (shouldHide) {
  2608. return null;
  2609. }
  2610. // Size-based styling helpers
  2611. const getImageSize = () => {
  2612. switch (cardSize) {
  2613. case 1: return 'w-10 h-10';
  2614. case 2: return 'w-14 h-14';
  2615. case 3: return 'w-16 h-16';
  2616. case 4: return 'w-20 h-20';
  2617. default: return 'w-14 h-14';
  2618. }
  2619. };
  2620. const getTitleSize = () => {
  2621. switch (cardSize) {
  2622. case 1: return 'text-base truncate';
  2623. case 2: return 'text-lg';
  2624. case 3: return 'text-xl';
  2625. case 4: return 'text-2xl';
  2626. default: return 'text-lg';
  2627. }
  2628. };
  2629. const getSpacing = () => {
  2630. switch (cardSize) {
  2631. case 1: return 'mb-2';
  2632. case 2: return 'mb-4';
  2633. case 3: return 'mb-5';
  2634. case 4: return 'mb-6';
  2635. default: return 'mb-4';
  2636. }
  2637. };
  2638. const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
  2639. const handleCardDragEnter = (e: React.DragEvent) => {
  2640. e.preventDefault();
  2641. dragCounterRef.current++;
  2642. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  2643. };
  2644. const handleCardDragOver = (e: React.DragEvent) => {
  2645. e.preventDefault();
  2646. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  2647. };
  2648. const handleCardDragLeave = (e: React.DragEvent) => {
  2649. e.preventDefault();
  2650. dragCounterRef.current--;
  2651. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  2652. };
  2653. const handleCardDrop = async (e: React.DragEvent) => {
  2654. e.preventDefault();
  2655. dragCounterRef.current = 0;
  2656. setIsDraggingFile(false);
  2657. if (!canDrop) return;
  2658. const droppedFiles = Array.from(e.dataTransfer.files);
  2659. const file = droppedFiles[0];
  2660. if (!file) return;
  2661. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  2662. const lower = file.name.toLowerCase();
  2663. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  2664. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  2665. return;
  2666. }
  2667. setIsDropUploading(true);
  2668. try {
  2669. const result = await api.uploadLibraryFile(file, null);
  2670. // Check printer compatibility if sliced_for_model is available in metadata
  2671. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  2672. const printerModel = mapModelCode(printer.model);
  2673. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  2674. await api.deleteLibraryFile(result.id).catch(() => {});
  2675. showToast(
  2676. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  2677. 'error'
  2678. );
  2679. return;
  2680. }
  2681. setPrintAfterUpload({ id: result.id, filename: result.filename });
  2682. } catch {
  2683. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  2684. } finally {
  2685. setIsDropUploading(false);
  2686. }
  2687. };
  2688. const handleCardClick = (e: React.MouseEvent) => {
  2689. if (viewMode !== 'compact' || selectionMode) return;
  2690. const target = e.target as HTMLElement;
  2691. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  2692. onOpenCompactCard?.(printer.id);
  2693. };
  2694. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  2695. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  2696. const renderAmsSlotActions = ({
  2697. amsId,
  2698. slotId,
  2699. loadTrayId,
  2700. isRefreshing,
  2701. includeRfid = true,
  2702. }: {
  2703. amsId: number;
  2704. slotId: number;
  2705. loadTrayId: number;
  2706. isRefreshing?: boolean;
  2707. includeRfid?: boolean;
  2708. }) => {
  2709. const printerBusy = status?.state === 'RUNNING';
  2710. return (
  2711. <>
  2712. {includeRfid && (
  2713. <button
  2714. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2715. hasPermission('printers:ams_rfid')
  2716. ? 'text-white hover:bg-bambu-dark-tertiary'
  2717. : 'text-bambu-gray/50 cursor-not-allowed'
  2718. }`}
  2719. onClick={(e) => {
  2720. e.stopPropagation();
  2721. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  2722. refreshAmsSlotMutation.mutate({ amsId, slotId });
  2723. }}
  2724. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  2725. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  2726. >
  2727. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  2728. {t('printers.rfid.reread')}
  2729. </button>
  2730. )}
  2731. <button
  2732. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2733. hasPermission('printers:control')
  2734. ? 'text-white hover:bg-bambu-dark-tertiary'
  2735. : 'text-bambu-gray/50 cursor-not-allowed'
  2736. }`}
  2737. onClick={(e) => {
  2738. e.stopPropagation();
  2739. if (printerBusy || !hasPermission('printers:control')) return;
  2740. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  2741. }}
  2742. disabled={printerBusy || !hasPermission('printers:control')}
  2743. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2744. >
  2745. <LogIn className="w-3 h-3" />
  2746. {t('printers.ams.load')}
  2747. </button>
  2748. <button
  2749. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2750. hasPermission('printers:control')
  2751. ? 'text-white hover:bg-bambu-dark-tertiary'
  2752. : 'text-bambu-gray/50 cursor-not-allowed'
  2753. }`}
  2754. onClick={(e) => {
  2755. e.stopPropagation();
  2756. if (printerBusy || !hasPermission('printers:control')) return;
  2757. unloadAmsMutation.mutate();
  2758. }}
  2759. disabled={printerBusy || !hasPermission('printers:control')}
  2760. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2761. >
  2762. <LogOut className="w-3 h-3" />
  2763. {t('printers.ams.unload')}
  2764. </button>
  2765. </>
  2766. );
  2767. };
  2768. const printerActionsMenu = (
  2769. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  2770. <Button
  2771. variant="secondary"
  2772. size="sm"
  2773. onClick={() => setShowMenu(!showMenu)}
  2774. title={t('common.more', 'More')}
  2775. className={footerIconButtonClass}
  2776. >
  2777. <MoreVertical className="w-4 h-4" />
  2778. </Button>
  2779. {showMenu && (
  2780. <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">
  2781. <button
  2782. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2783. hasPermission('printers:update')
  2784. ? 'hover:bg-bambu-dark-tertiary'
  2785. : 'opacity-50 cursor-not-allowed'
  2786. }`}
  2787. onClick={() => {
  2788. if (!hasPermission('printers:update')) return;
  2789. setShowEditModal(true);
  2790. setShowMenu(false);
  2791. }}
  2792. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2793. >
  2794. <Pencil className="w-4 h-4" />
  2795. {t('common.edit')}
  2796. </button>
  2797. <button
  2798. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2799. onClick={() => {
  2800. setShowPrinterInfo(true);
  2801. setShowMenu(false);
  2802. }}
  2803. >
  2804. <Info className="w-4 h-4" />
  2805. {t('printers.printerInformation')}
  2806. </button>
  2807. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  2808. <button
  2809. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2810. hasPermission('printers:update')
  2811. ? 'hover:bg-bambu-dark-tertiary'
  2812. : 'opacity-50 cursor-not-allowed'
  2813. }`}
  2814. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  2815. onClick={() => {
  2816. if (!hasPermission('printers:update')) return;
  2817. setShowMenu(false);
  2818. if (printer.is_active !== false) {
  2819. handleEnterMaintenance();
  2820. } else {
  2821. maintenanceMutation.mutate(true);
  2822. }
  2823. }}
  2824. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2825. >
  2826. <Wrench className="w-4 h-4" />
  2827. {printer.is_active !== false
  2828. ? t('printers.maintenance.menuEnter')
  2829. : t('printers.maintenance.menuExit')}
  2830. </button>
  2831. <button
  2832. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2833. onClick={() => {
  2834. connectMutation.mutate();
  2835. setShowMenu(false);
  2836. }}
  2837. >
  2838. <RefreshCw className="w-4 h-4" />
  2839. {t('printers.reconnect')}
  2840. </button>
  2841. <button
  2842. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  2843. disabled={forceRefreshMutation.isPending}
  2844. onClick={() => {
  2845. forceRefreshMutation.mutate();
  2846. setShowMenu(false);
  2847. }}
  2848. >
  2849. <RotateCw className={`w-4 h-4 ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  2850. {t('printers.forceRefresh')}
  2851. </button>
  2852. <button
  2853. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2854. onClick={() => {
  2855. setShowMQTTDebug(true);
  2856. setShowMenu(false);
  2857. }}
  2858. >
  2859. <Terminal className="w-4 h-4" />
  2860. {t('printers.mqttDebug')}
  2861. </button>
  2862. <button
  2863. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2864. onClick={() => {
  2865. setShowDiagnostic(true);
  2866. setShowMenu(false);
  2867. }}
  2868. >
  2869. <Stethoscope className="w-4 h-4" />
  2870. {t('diagnostic.runButton')}
  2871. </button>
  2872. <button
  2873. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2874. hasPermission('printers:delete')
  2875. ? 'text-red-400 hover:bg-bambu-dark-tertiary'
  2876. : 'text-red-400/50 cursor-not-allowed'
  2877. }`}
  2878. onClick={() => {
  2879. if (!hasPermission('printers:delete')) return;
  2880. setShowDeleteConfirm(true);
  2881. setShowMenu(false);
  2882. }}
  2883. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  2884. >
  2885. <Trash2 className="w-4 h-4" />
  2886. {t('common.delete')}
  2887. </button>
  2888. </div>
  2889. )}
  2890. </div>
  2891. );
  2892. return (
  2893. <Card
  2894. id={`printer-card-${printer.id}`}
  2895. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  2896. onClick={handleCardClick}
  2897. onDragEnter={handleCardDragEnter}
  2898. onDragOver={handleCardDragOver}
  2899. onDragLeave={handleCardDragLeave}
  2900. onDrop={handleCardDrop}
  2901. >
  2902. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  2903. {selectionMode && (
  2904. <div
  2905. className="absolute inset-0 z-20 flex items-start p-2"
  2906. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  2907. >
  2908. {isSelected ? (
  2909. <CheckSquare className="w-5 h-5 text-bambu-green" />
  2910. ) : (
  2911. <Square className="w-5 h-5 text-bambu-gray" />
  2912. )}
  2913. </div>
  2914. )}
  2915. {/* Drop zone overlay */}
  2916. {(isDraggingFile || isDropUploading) && (
  2917. <div
  2918. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  2919. isDropUploading
  2920. ? 'bg-bambu-green/10 border-bambu-green/50'
  2921. : canDrop
  2922. ? 'bg-bambu-green/10 border-bambu-green'
  2923. : 'bg-red-500/10 border-red-500/50'
  2924. }`}
  2925. >
  2926. <div className="text-center">
  2927. {isDropUploading ? (
  2928. <>
  2929. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  2930. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  2931. </>
  2932. ) : canDrop ? (
  2933. <>
  2934. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  2935. <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
  2936. </>
  2937. ) : (
  2938. <>
  2939. <X className="w-8 h-8 mx-auto mb-2 text-red-400" />
  2940. <p className="text-sm font-medium text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
  2941. </>
  2942. )}
  2943. </div>
  2944. </div>
  2945. )}
  2946. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  2947. {/* Header */}
  2948. <div className={getSpacing()}>
  2949. {/* Top row: Image, Name, Menu */}
  2950. <div className="flex items-start justify-between gap-2">
  2951. <div className="flex items-center gap-3 min-w-0 flex-1">
  2952. {/* Printer Model Image */}
  2953. <img
  2954. src={getPrinterImage(printer.model)}
  2955. alt={printer.model || t('common.printer')}
  2956. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  2957. />
  2958. <div className="min-w-0 flex-1">
  2959. <div className="flex items-center justify-between gap-2">
  2960. <div className="flex min-w-0 items-center gap-2">
  2961. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  2962. {/* Connection indicator dot for compact mode */}
  2963. {viewMode === 'compact' && (() => {
  2964. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  2965. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  2966. const hasWarning = hmsErrors.length > 0;
  2967. const pipColor = !status?.connected
  2968. ? 'bg-status-error'
  2969. : hasSevere
  2970. ? 'bg-status-error'
  2971. : hasWarning
  2972. ? 'bg-status-warning'
  2973. : 'bg-status-ok';
  2974. const pipTitle = !status?.connected
  2975. ? t('printers.connection.offline')
  2976. : hasWarning
  2977. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  2978. : t('printers.connection.connected');
  2979. return (
  2980. <div
  2981. className={`w-2 h-2 rounded-full flex-shrink-0 ${pipColor}`}
  2982. title={pipTitle}
  2983. />
  2984. );
  2985. })()}
  2986. </div>
  2987. {viewMode === 'compact' && showClearPlateButton && (
  2988. <button
  2989. type="button"
  2990. onClick={() => clearPlateMutation.mutate()}
  2991. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2992. aria-label={t('printers.plateStatus.markCleared')}
  2993. className="inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-md bg-yellow-500/20 border border-yellow-400/40 text-yellow-400 hover:bg-yellow-500/30 transition-colors disabled:opacity-50"
  2994. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2995. >
  2996. {clearPlateMutation.isPending ? (
  2997. <Loader2 className="w-3 h-3 animate-spin" />
  2998. ) : (
  2999. <PlateClearedIcon className="w-3 h-3" />
  3000. )}
  3001. </button>
  3002. )}
  3003. </div>
  3004. <p className="text-sm text-bambu-gray">
  3005. {printer.model || 'Unknown Model'}
  3006. {/* Nozzle Info - only in expanded */}
  3007. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3008. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3009. • {status.nozzles[0].nozzle_diameter}mm
  3010. </span>
  3011. )}
  3012. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3013. <span className="ml-2 text-bambu-gray">
  3014. <Clock className="w-3 h-3 inline-block mr-1" />
  3015. {Math.round(maintenanceInfo.total_print_hours)}h
  3016. </span>
  3017. )}
  3018. </p>
  3019. </div>
  3020. </div>
  3021. </div>
  3022. {/* Badges row - only in expanded mode */}
  3023. {viewMode === 'expanded' && (
  3024. <div className="mt-2">
  3025. <div className="flex flex-wrap items-center gap-2">
  3026. {/* Connection status badge (or Maintenance pill when out of service).
  3027. Defensive: only swap when is_active is EXPLICITLY false. An
  3028. undefined / missing field defaults to "active" so the regular
  3029. pill renders — matches the backend default and prevents test
  3030. fixtures (or stale clients) from accidentally tripping the
  3031. maintenance UI. */}
  3032. {printer.is_active === false ? (
  3033. <span
  3034. className="flex items-center gap-1.5 px-2 py-1 rounded-full text-xs bg-amber-500/20 text-amber-400"
  3035. title={t('printers.maintenance.subtitle')}
  3036. >
  3037. <Wrench className="w-3 h-3" />
  3038. {t('printers.maintenance.pillLabel')}
  3039. </span>
  3040. ) : (
  3041. <span
  3042. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3043. status?.connected
  3044. ? 'bg-status-ok/20 text-status-ok'
  3045. : 'bg-status-error/20 text-status-error'
  3046. }`}
  3047. >
  3048. {status?.connected ? (
  3049. <Link className="w-3 h-3" />
  3050. ) : (
  3051. <Unlink className="w-3 h-3" />
  3052. )}
  3053. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3054. </span>
  3055. )}
  3056. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3057. {printer.is_active !== false && !status?.connected && (
  3058. <button
  3059. onClick={() => setShowDiagnostic(true)}
  3060. 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"
  3061. title={t('diagnostic.runButton')}
  3062. >
  3063. <Stethoscope className="w-3 h-3" />
  3064. {t('diagnostic.runButton')}
  3065. </button>
  3066. )}
  3067. {/* Network connection indicator */}
  3068. {status?.connected && status?.wired_network && (
  3069. <span
  3070. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3071. title={t('printers.connection.ethernet', 'Ethernet')}
  3072. >
  3073. <Cable className="w-3 h-3" />
  3074. {t('printers.connection.ethernet', 'Ethernet')}
  3075. </span>
  3076. )}
  3077. {/* WiFi signal indicator */}
  3078. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3079. <span
  3080. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3081. wifiSignal >= -50
  3082. ? 'bg-status-ok/20 text-status-ok'
  3083. : wifiSignal >= -60
  3084. ? 'bg-status-ok/20 text-status-ok'
  3085. : wifiSignal >= -70
  3086. ? 'bg-status-warning/20 text-status-warning'
  3087. : wifiSignal >= -80
  3088. ? 'bg-orange-500/20 text-orange-600'
  3089. : 'bg-status-error/20 text-status-error'
  3090. }`}
  3091. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3092. >
  3093. <Signal className="w-3 h-3" />
  3094. {wifiSignal}dBm
  3095. </span>
  3096. )}
  3097. {/* HMS Status Indicator */}
  3098. {status?.connected && (() => {
  3099. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3100. return (
  3101. <button
  3102. onClick={() => setShowHMSModal(true)}
  3103. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3104. knownErrors.length > 0
  3105. ? knownErrors.some(e => e.severity <= 2)
  3106. ? 'bg-status-error/20 text-status-error'
  3107. : 'bg-status-warning/20 text-status-warning'
  3108. : 'bg-status-ok/20 text-status-ok'
  3109. }`}
  3110. title={t('printers.clickToViewHmsErrors')}
  3111. >
  3112. <AlertTriangle className="w-3 h-3" />
  3113. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3114. </button>
  3115. );
  3116. })()}
  3117. {/* Maintenance Status Indicator */}
  3118. {maintenanceInfo && (
  3119. <button
  3120. onClick={() => navigate('/maintenance')}
  3121. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3122. maintenanceInfo.due_count > 0
  3123. ? 'bg-status-error/20 text-status-error'
  3124. : maintenanceInfo.warning_count > 0
  3125. ? 'bg-status-warning/20 text-status-warning'
  3126. : 'bg-status-ok/20 text-status-ok'
  3127. }`}
  3128. title={
  3129. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3130. ? `${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`
  3131. : t('printers.maintenanceUpToDate')
  3132. }
  3133. >
  3134. <Wrench className="w-3 h-3" />
  3135. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3136. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3137. : 'OK'}
  3138. </button>
  3139. )}
  3140. {/* Queue Count Badge */}
  3141. {queueCount > 0 && (
  3142. <button
  3143. onClick={() => navigate('/queue')}
  3144. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-indigo-500/20 text-indigo-400 hover:opacity-80 transition-opacity"
  3145. title={t('printers.queue.inQueue', { count: queueCount })}
  3146. >
  3147. <Layers className="w-3 h-3" />
  3148. {queueCount}
  3149. </button>
  3150. )}
  3151. {/* Firmware Version Badge */}
  3152. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3153. <button
  3154. onClick={() => setShowFirmwareModal(true)}
  3155. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3156. firmwareInfo.update_available
  3157. ? 'bg-orange-500/20 text-orange-400'
  3158. : 'bg-status-ok/20 text-status-ok'
  3159. }`}
  3160. title={
  3161. firmwareInfo.update_available
  3162. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3163. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3164. }
  3165. >
  3166. {firmwareInfo.update_available ? <Download className="w-3 h-3" /> : <CheckCircle className="w-3 h-3" />}
  3167. {firmwareInfo.current_version}
  3168. </button>
  3169. ) : status?.firmware_version ? (
  3170. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3171. {status.firmware_version}
  3172. </span>
  3173. ) : null}
  3174. {/* Enclosure Door Badge (X1/X2D/P1S/P2S/H2*) */}
  3175. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P1S', 'P1P', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3176. <span
  3177. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3178. status.door_open
  3179. ? 'bg-yellow-500/20 text-yellow-400'
  3180. : 'bg-status-ok/20 text-status-ok'
  3181. }`}
  3182. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3183. >
  3184. {status.door_open ? <DoorOpen className="w-3 h-3" /> : <DoorClosed className="w-3 h-3" />}
  3185. </span>
  3186. )}
  3187. </div>
  3188. </div>
  3189. )}
  3190. </div>
  3191. {/* Delete Confirmation */}
  3192. {showDeleteConfirm && (
  3193. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3194. <Card className="w-full max-w-md mx-4">
  3195. <CardContent>
  3196. <div className="flex items-start gap-3 mb-4">
  3197. <div className="p-2 rounded-full bg-red-500/20">
  3198. <AlertTriangle className="w-5 h-5 text-red-400" />
  3199. </div>
  3200. <div>
  3201. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3202. <p className="text-sm text-bambu-gray mt-1">
  3203. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3204. </p>
  3205. </div>
  3206. </div>
  3207. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3208. <label className="flex items-start gap-3 cursor-pointer">
  3209. <input
  3210. type="checkbox"
  3211. checked={deleteArchives}
  3212. onChange={(e) => setDeleteArchives(e.target.checked)}
  3213. 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"
  3214. />
  3215. <div>
  3216. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3217. <p className="text-xs text-bambu-gray mt-0.5">
  3218. {deleteArchives
  3219. ? t('printers.confirm.deleteArchivesNote')
  3220. : t('printers.confirm.keepArchivesNote')}
  3221. </p>
  3222. </div>
  3223. </label>
  3224. </div>
  3225. <div className="flex justify-end gap-2">
  3226. <Button
  3227. variant="secondary"
  3228. onClick={() => {
  3229. setShowDeleteConfirm(false);
  3230. setDeleteArchives(true);
  3231. }}
  3232. >
  3233. {t('common.cancel')}
  3234. </Button>
  3235. <Button
  3236. variant="danger"
  3237. onClick={() => {
  3238. deleteMutation.mutate({ deleteArchives });
  3239. setShowDeleteConfirm(false);
  3240. setDeleteArchives(true);
  3241. }}
  3242. >
  3243. Delete
  3244. </Button>
  3245. </div>
  3246. </CardContent>
  3247. </Card>
  3248. </div>
  3249. )}
  3250. {/* Status — see the equivalent defensive `=== false` check on the
  3251. header pill above for why this is not `!printer.is_active`. */}
  3252. {printer.is_active === false ? (
  3253. // Maintenance mode (#1476) — replaces the cover/progress container
  3254. // so the card keeps the same height. Renders for both compact and
  3255. // expanded view modes so the printer stays visible but plainly
  3256. // out-of-service.
  3257. <>
  3258. {viewMode === 'compact' ? (
  3259. <div className="mt-2 flex items-center gap-2 px-2 py-1.5 rounded-full bg-amber-500/15 border border-amber-500/30">
  3260. <Wrench className="w-3 h-3 text-amber-400 shrink-0" />
  3261. <span className="text-[11px] text-amber-400 font-medium truncate">
  3262. {t('printers.maintenance.pillLabel')}
  3263. </span>
  3264. </div>
  3265. ) : (
  3266. <>
  3267. <div className="flex items-center gap-2 mb-2">
  3268. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3269. {t('printers.status.title', 'Status')}
  3270. </span>
  3271. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3272. </div>
  3273. <div className="p-3 bg-amber-500/10 border border-amber-500/30 rounded-[10px] flex items-center gap-3">
  3274. <Wrench className="w-6 h-6 text-amber-400 shrink-0" />
  3275. <div className="flex-1 min-w-0">
  3276. <p className="text-sm text-amber-400 font-medium">
  3277. {t('printers.maintenance.title')}
  3278. </p>
  3279. <p className="text-xs text-bambu-gray mt-0.5">
  3280. {t('printers.maintenance.subtitle')}
  3281. </p>
  3282. </div>
  3283. <Button
  3284. variant="secondary"
  3285. size="sm"
  3286. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3287. onClick={() => maintenanceMutation.mutate(true)}
  3288. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3289. >
  3290. {t('printers.maintenance.exitButton')}
  3291. </Button>
  3292. </div>
  3293. </>
  3294. )}
  3295. </>
  3296. ) : status?.connected && (
  3297. <>
  3298. {/* Compact: Simple status bar */}
  3299. {viewMode === 'compact' ? (
  3300. (() => {
  3301. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3302. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3303. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3304. ? Math.max(0, Math.min(100, status.progress || 0))
  3305. : showClearPlateButton
  3306. ? 100
  3307. : hasProblem
  3308. ? 100
  3309. : 0;
  3310. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3311. const compactProgressClass = hasProblem
  3312. ? 'bg-status-error'
  3313. : status.state === 'PAUSE'
  3314. ? 'bg-status-warning'
  3315. : 'bg-bambu-green';
  3316. return (
  3317. <div className="relative mt-2 flex items-center gap-2">
  3318. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3319. <div
  3320. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3321. style={{ width: `${compactProgress}%` }}
  3322. />
  3323. </div>
  3324. <span className={`w-9 shrink-0 text-right text-[11px] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3325. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3326. </span>
  3327. </div>
  3328. );
  3329. })()
  3330. ) : (
  3331. /* Expanded: Full status section */
  3332. <>
  3333. <div className="flex items-center gap-2 mb-2">
  3334. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3335. {t('printers.status.title', 'Status')}
  3336. </span>
  3337. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3338. </div>
  3339. {/* Current Print or Idle Placeholder */}
  3340. {(() => {
  3341. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3342. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3343. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3344. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3345. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3346. return (
  3347. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3348. <button
  3349. onClick={() => setShowSkipObjectsModal(true)}
  3350. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3351. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3352. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3353. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3354. : 'text-bambu-gray/30 cursor-not-allowed'
  3355. }`}
  3356. title={
  3357. !hasPermission('printers:control')
  3358. ? t('printers.permission.noControl')
  3359. : !isActivePrint
  3360. ? t('printers.skipObjects.onlyWhilePrinting')
  3361. : (status.printable_objects_count ?? 0) >= 2
  3362. ? t('printers.skipObjects.tooltip')
  3363. : t('printers.skipObjects.requiresMultiple')
  3364. }
  3365. >
  3366. <SkipObjectsIcon className="w-4 h-4" />
  3367. {objectsData && objectsData.skipped_count > 0 && (
  3368. <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">
  3369. {objectsData.skipped_count}
  3370. </span>
  3371. )}
  3372. </button>
  3373. <div className="flex items-stretch gap-2">
  3374. <CoverImage
  3375. url={coverUrl}
  3376. printName={printName || undefined}
  3377. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  3378. />
  3379. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  3380. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  3381. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  3382. {plateStatusPill}
  3383. </div>
  3384. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  3385. {printName || t('printers.noActiveJob', 'No active job')}
  3386. </p>
  3387. <div className="flex h-3 items-center gap-2 text-sm">
  3388. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  3389. <div
  3390. 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`}
  3391. style={{ width: `${progress}%` }}
  3392. />
  3393. </div>
  3394. <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>
  3395. </div>
  3396. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  3397. {isActivePrint ? (
  3398. <>
  3399. {status.remaining_time != null && status.remaining_time > 0 && (
  3400. <>
  3401. <span className="flex items-center gap-1">
  3402. <Clock className="w-3 h-3" />
  3403. {formatDuration(status.remaining_time * 60)}
  3404. </span>
  3405. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  3406. ETA {formatETA(status.remaining_time, timeFormat, t)}
  3407. </span>
  3408. </>
  3409. )}
  3410. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  3411. <span className="flex items-center gap-1">
  3412. <Layers className="w-3 h-3" />
  3413. {status.layer_num}/{status.total_layers}
  3414. </span>
  3415. )}
  3416. {currentPrintUser && (
  3417. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  3418. <User className="w-3 h-3" />
  3419. {currentPrintUser}
  3420. </span>
  3421. )}
  3422. </>
  3423. ) : lastPrint ? (
  3424. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  3425. Last: {lastPrint.print_name || lastPrint.filename}
  3426. {lastPrint.completed_at && (
  3427. <span className="ml-1 text-bambu-gray/60">
  3428. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  3429. </span>
  3430. )}
  3431. </p>
  3432. ) : (
  3433. <span>{t('printers.readyToPrint')}</span>
  3434. )}
  3435. </div>
  3436. </div>
  3437. </div>
  3438. <PrinterQueueWidget
  3439. printerId={printer.id}
  3440. printerModel={printer.model}
  3441. loadedFilamentTypes={loadedFilamentTypes}
  3442. loadedFilaments={loadedFilaments}
  3443. variant="panelExtension"
  3444. />
  3445. </div>
  3446. );
  3447. })()}
  3448. </>
  3449. )}
  3450. {/* Temperatures */}
  3451. {status.temperatures && viewMode === 'expanded' && (() => {
  3452. // Use actual heater states from MQTT stream
  3453. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  3454. const bedHeating = status.temperatures.bed_heating || false;
  3455. const chamberHeating = status.temperatures.chamber_heating || false;
  3456. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  3457. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  3458. const kinds: HeaterSensorKind[] = ['nozzle'];
  3459. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  3460. kinds.push('bed');
  3461. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  3462. return kinds;
  3463. })();
  3464. // active_extruder: 0=right, 1=left
  3465. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  3466. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  3467. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  3468. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  3469. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  3470. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  3471. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  3472. const canUseStatusControls = status.connected && hasPermission('printers:control');
  3473. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  3474. 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 ${
  3475. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3476. }`;
  3477. // Chamber fan only exists on enclosed Bambu models. Open-frame
  3478. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  3479. // the widget there is at best dead UI and at worst suggests a
  3480. // control that does nothing. Mirrors the enclosure-door badge
  3481. // gate above.
  3482. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  3483. const fanItems = [
  3484. {
  3485. key: 'part',
  3486. label: t('printers.fans.partCooling'),
  3487. value: status.cooling_fan_speed ?? 0,
  3488. Icon: Fan,
  3489. activeClass: 'text-cyan-400',
  3490. },
  3491. {
  3492. key: 'aux',
  3493. label: t('printers.fans.auxiliary'),
  3494. value: status.big_fan1_speed ?? 0,
  3495. Icon: Wind,
  3496. activeClass: 'text-blue-400',
  3497. },
  3498. ...(hasChamberFan
  3499. ? [
  3500. {
  3501. key: 'chamber',
  3502. label: t('printers.fans.chamber'),
  3503. value: status.big_fan2_speed ?? 0,
  3504. Icon: AirVent,
  3505. activeClass: 'text-green-400',
  3506. },
  3507. ]
  3508. : []),
  3509. ];
  3510. return (
  3511. <>
  3512. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  3513. {/* Nozzle temp - combined for dual nozzle */}
  3514. <div
  3515. className={statusControlClass}
  3516. title={statusControlTitle}
  3517. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  3518. >
  3519. <button
  3520. type="button"
  3521. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3522. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3523. onClick={(e) => {
  3524. e.stopPropagation();
  3525. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  3526. }}
  3527. >
  3528. <LineChartIcon className="w-2.5 h-2.5" />
  3529. </button>
  3530. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  3531. {status.temperatures.nozzle_2 !== undefined ? (
  3532. <>
  3533. <p className="text-[9px] text-bambu-gray">L / R</p>
  3534. <p className="text-[11px] text-white">
  3535. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  3536. </p>
  3537. </>
  3538. ) : singleNozzleSlot ? (
  3539. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  3540. <div className="cursor-default">
  3541. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3542. <p className="text-[11px] text-white">
  3543. {Math.round(status.temperatures.nozzle || 0)}°C
  3544. </p>
  3545. </div>
  3546. </NozzleSlotHoverCard>
  3547. ) : (
  3548. <>
  3549. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3550. <p className="text-[11px] text-white">
  3551. {Math.round(status.temperatures.nozzle || 0)}°C
  3552. </p>
  3553. </>
  3554. )}
  3555. {statusControlMenu === 'nozzle-temp' && (
  3556. isDualNozzle ? (
  3557. <IndicatorControlPopover
  3558. title="Set Nozzle Temperatures"
  3559. widthClass="w-[300px]"
  3560. popoverWidth={300}
  3561. popoverHeight={260}
  3562. isPending={nozzleTemperatureMutation.isPending}
  3563. onClose={() => setStatusControlMenu(null)}
  3564. >
  3565. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  3566. <NozzleTemperatureControlBox
  3567. label="Left Temp"
  3568. current={status.temperatures.nozzle}
  3569. target={status.temperatures.nozzle_target}
  3570. isActive={activeNozzle === 'L'}
  3571. isPending={nozzleTemperatureMutation.isPending}
  3572. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  3573. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3574. />
  3575. <NozzleTemperatureControlBox
  3576. label="Right Temp"
  3577. current={status.temperatures.nozzle_2}
  3578. target={status.temperatures.nozzle_2_target}
  3579. isActive={activeNozzle === 'R'}
  3580. isPending={nozzleTemperatureMutation.isPending}
  3581. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  3582. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3583. />
  3584. </div>
  3585. </IndicatorControlPopover>
  3586. ) : (
  3587. <IndicatorControlPopover
  3588. title="Set Nozzle Temperature"
  3589. unit="°C"
  3590. customMin={0}
  3591. customMax={320}
  3592. isPending={nozzleTemperatureMutation.isPending}
  3593. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3594. onClose={() => setStatusControlMenu(null)}
  3595. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  3596. />
  3597. )
  3598. )}
  3599. </div>
  3600. <div
  3601. className={statusControlClass}
  3602. title={statusControlTitle}
  3603. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  3604. >
  3605. <button
  3606. type="button"
  3607. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3608. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3609. onClick={(e) => {
  3610. e.stopPropagation();
  3611. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  3612. }}
  3613. >
  3614. <LineChartIcon className="w-2.5 h-2.5" />
  3615. </button>
  3616. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  3617. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  3618. <p className="text-[11px] text-white">
  3619. {Math.round(status.temperatures.bed || 0)}°C
  3620. </p>
  3621. {statusControlMenu === 'bed-temp' && (
  3622. <IndicatorControlPopover
  3623. title="Set Bed Temperature"
  3624. unit="°C"
  3625. customMin={0}
  3626. customMax={140}
  3627. isPending={bedTemperatureMutation.isPending}
  3628. options={buildPresetOptions(bedTempPresets, 'C')}
  3629. onClose={() => setStatusControlMenu(null)}
  3630. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  3631. />
  3632. )}
  3633. </div>
  3634. {status.temperatures.chamber !== undefined && (() => {
  3635. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  3636. // but can't act on M141, so we keep the card read-only there.
  3637. const hasChamberHeater = status.supports_chamber_heater === true;
  3638. return (
  3639. <div
  3640. className={hasChamberHeater
  3641. ? statusControlClass
  3642. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  3643. title={hasChamberHeater ? statusControlTitle : undefined}
  3644. onClick={hasChamberHeater
  3645. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  3646. : undefined}
  3647. >
  3648. <button
  3649. type="button"
  3650. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3651. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3652. onClick={(e) => {
  3653. e.stopPropagation();
  3654. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  3655. }}
  3656. >
  3657. <LineChartIcon className="w-2.5 h-2.5" />
  3658. </button>
  3659. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  3660. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  3661. <p className="text-[11px] text-white">
  3662. {Math.round(status.temperatures.chamber || 0)}°C
  3663. </p>
  3664. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  3665. <IndicatorControlPopover
  3666. title="Set Chamber Temperature"
  3667. unit="°C"
  3668. customMin={0}
  3669. customMax={60}
  3670. isPending={chamberTemperatureMutation.isPending}
  3671. options={buildPresetOptions(chamberTempPresets, 'C')}
  3672. onClose={() => setStatusControlMenu(null)}
  3673. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  3674. />
  3675. )}
  3676. </div>
  3677. );
  3678. })()}
  3679. {/* Active nozzle indicator for dual-nozzle printers */}
  3680. {isDualNozzle && (
  3681. <DualNozzleHoverCard
  3682. leftSlot={leftNozzleSlot}
  3683. rightSlot={rightNozzleSlot}
  3684. activeNozzle={activeNozzle}
  3685. filamentInfo={filamentInfo}
  3686. >
  3687. <div
  3688. 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 ${
  3689. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3690. }`}
  3691. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  3692. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  3693. >
  3694. <NozzleIcon className="w-3.5 h-3.5 mb-0.5 text-amber-400" />
  3695. <div className="flex items-center gap-2">
  3696. <span className={`text-[11px] font-bold ${activeNozzle === 'L' ? 'text-amber-400' : 'text-gray-500'}`}>
  3697. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  3698. </span>
  3699. <span className="text-[9px] text-bambu-gray/40">·</span>
  3700. <span className={`text-[11px] font-bold ${activeNozzle === 'R' ? 'text-amber-400' : 'text-gray-500'}`}>
  3701. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  3702. </span>
  3703. </div>
  3704. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3705. {statusControlMenu === 'nozzle-select' && (
  3706. <IndicatorControlPopover
  3707. title="Set Nozzle Selection"
  3708. widthClass="w-[300px]"
  3709. popoverWidth={300}
  3710. popoverHeight={140}
  3711. isPending={selectExtruderMutation.isPending}
  3712. options={[
  3713. { label: 'Left', value: 1 },
  3714. { label: 'Right', value: 0 },
  3715. ]}
  3716. onClose={() => setStatusControlMenu(null)}
  3717. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  3718. />
  3719. )}
  3720. </div>
  3721. </DualNozzleHoverCard>
  3722. )}
  3723. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  3724. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  3725. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  3726. )}
  3727. </div>
  3728. <div className="mt-2 flex items-center gap-1.5">
  3729. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  3730. const active = value > 0;
  3731. return (
  3732. <div
  3733. key={key}
  3734. 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 ${
  3735. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3736. }`}
  3737. title={canUseStatusControls ? label : statusControlTitle}
  3738. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  3739. >
  3740. <Icon className={`w-3 h-3 shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  3741. <span className={`text-[10px] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  3742. {value}%
  3743. </span>
  3744. {statusControlMenu === `fan-${key}` && (
  3745. <IndicatorControlPopover
  3746. title={`Set ${label} Speed`}
  3747. unit="%"
  3748. customMin={0}
  3749. customMax={100}
  3750. isPending={fanSpeedMutation.isPending}
  3751. options={buildPresetOptions(fanSpeedPresets, '%')}
  3752. onClose={() => setStatusControlMenu(null)}
  3753. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'chamber', speed })}
  3754. />
  3755. )}
  3756. </div>
  3757. );
  3758. })}
  3759. </div>
  3760. </>
  3761. );
  3762. })()}
  3763. {viewMode === 'expanded' && showClearPlateButton && (
  3764. <button
  3765. type="button"
  3766. onClick={() => clearPlateMutation.mutate()}
  3767. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3768. className="mt-2 w-full inline-flex items-center justify-center gap-2 px-3 py-1.5 rounded-lg bg-yellow-500/20 border border-yellow-400/40 text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs font-medium disabled:opacity-50"
  3769. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3770. >
  3771. {clearPlateMutation.isPending ? (
  3772. <Loader2 className="w-3 h-3 animate-spin" />
  3773. ) : (
  3774. <PlateClearedIcon className="w-4 h-4" />
  3775. )}
  3776. {t('printers.plateStatus.markCleared')}
  3777. </button>
  3778. )}
  3779. {/* Controls */}
  3780. {viewMode === 'expanded' && (() => {
  3781. // Determine print state for control buttons
  3782. const isRunning = status.state === 'RUNNING';
  3783. const isPaused = status.state === 'PAUSE';
  3784. const isPrinting = isRunning || isPaused;
  3785. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  3786. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  3787. 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';
  3788. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  3789. return (
  3790. <div className="mt-3">
  3791. {/* Section Header */}
  3792. <div className="flex items-center gap-2 mb-2">
  3793. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3794. {t('printers.controls')}
  3795. </span>
  3796. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3797. </div>
  3798. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  3799. {/* Left: Secondary controls */}
  3800. <div className="flex flex-wrap items-center gap-2 min-w-0">
  3801. <button
  3802. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  3803. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  3804. className={`${iconControlClass} ${
  3805. status.chamber_light
  3806. ? 'bg-yellow-500/10 text-yellow-400 hover:bg-yellow-500/20'
  3807. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  3808. }`}
  3809. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  3810. >
  3811. <ChamberLight on={status.chamber_light ?? false} className="w-4 h-4" />
  3812. </button>
  3813. {/* Airduct Mode (P2S / X2D / H2*) */}
  3814. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  3815. const isHeating = status.airduct_mode === 1;
  3816. const Icon = isHeating ? Flame : Snowflake;
  3817. const color = isHeating ? 'text-orange-400' : 'text-sky-400';
  3818. const bg = isHeating ? 'bg-orange-500/10 text-orange-400 hover:bg-orange-500/20' : 'bg-sky-500/10 text-sky-400 hover:bg-sky-500/20';
  3819. return (
  3820. <div className="relative">
  3821. <button
  3822. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  3823. disabled={!hasPermission('printers:control')}
  3824. className={`${iconControlClass} ${bg}`}
  3825. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  3826. >
  3827. <Icon className={`w-4 h-4 ${color}`} />
  3828. </button>
  3829. {showAirductMenu === printer.id && (
  3830. <>
  3831. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  3832. <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]">
  3833. {([
  3834. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  3835. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  3836. ] as const).map(({ mode, label, modeId }) => (
  3837. <button
  3838. key={mode}
  3839. onClick={() => {
  3840. airductMutation.mutate(mode);
  3841. setShowAirductMenu(null);
  3842. }}
  3843. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  3844. status.airduct_mode === modeId
  3845. ? 'text-bambu-green bg-bambu-green/10'
  3846. : 'text-white hover:bg-bambu-dark-tertiary'
  3847. }`}
  3848. >
  3849. {mode === 'heating' ? <Flame className="w-3 h-3" /> : <Snowflake className="w-3 h-3" />}
  3850. {label}
  3851. </button>
  3852. ))}
  3853. </div>
  3854. </>
  3855. )}
  3856. </div>
  3857. );
  3858. })()}
  3859. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  3860. {(() => {
  3861. const canControl = hasPermission('printers:control');
  3862. const disabled = isPrinting || !canControl;
  3863. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  3864. const jogButtonClass = 'flex h-8 w-8 items-center justify-center rounded bg-indigo-500/15 text-indigo-300 transition-colors hover:bg-indigo-500/30 disabled:cursor-not-allowed disabled:opacity-50';
  3865. const requestZJog = (direction: 1 | -1) => {
  3866. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  3867. const warnedKey = `bambuddy.bedJog.warned.${printer.id}`;
  3868. const warned = (() => {
  3869. try { return sessionStorage.getItem(warnedKey) === '1'; }
  3870. catch { return false; }
  3871. })();
  3872. if (warned) {
  3873. bedJogMutation.mutate({ distance: signed, force: true });
  3874. } else {
  3875. setShowNotHomedModal({ distance: signed });
  3876. }
  3877. };
  3878. const requestXyJog = (x: number, y: number) => {
  3879. xyJogMutation.mutate({ x, y });
  3880. };
  3881. const requestExtruderJog = (distance: number) => {
  3882. extruderJogMutation.mutate(distance);
  3883. };
  3884. return (
  3885. <div className="relative">
  3886. <button
  3887. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  3888. disabled={disabled}
  3889. className={`${iconControlClass} ${
  3890. disabled
  3891. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  3892. : 'bg-indigo-500/10 text-indigo-400 hover:bg-indigo-500/20'
  3893. }`}
  3894. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  3895. >
  3896. <Move className="w-4 h-4" />
  3897. </button>
  3898. {showBedJogMenu === printer.id && (
  3899. <>
  3900. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  3901. <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">
  3902. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  3903. {t('printers.bedJog.title')}
  3904. </div>
  3905. <div className="h-px bg-bambu-dark-tertiary" />
  3906. <div className="flex justify-center px-3 py-2.5">
  3907. <div className="flex items-center justify-center gap-3">
  3908. <div className="grid grid-cols-3 gap-1">
  3909. <div />
  3910. <button
  3911. onClick={() => requestXyJog(0, bedJogStep)}
  3912. disabled={xyJogMutation.isPending}
  3913. className={jogButtonClass}
  3914. aria-label="Move Y forward"
  3915. >
  3916. <ArrowUp className="w-4 h-4" />
  3917. </button>
  3918. <div />
  3919. <button
  3920. onClick={() => requestXyJog(-bedJogStep, 0)}
  3921. disabled={xyJogMutation.isPending}
  3922. className={jogButtonClass}
  3923. aria-label="Move X left"
  3924. >
  3925. <ArrowLeft className="w-4 h-4" />
  3926. </button>
  3927. <button
  3928. onClick={() => {
  3929. setShowBedJogMenu(null);
  3930. homeAxesMutation.mutate('all');
  3931. }}
  3932. disabled={homeAxesMutation.isPending}
  3933. className={jogButtonClass}
  3934. aria-label={t('printers.bedJog.homeZ')}
  3935. >
  3936. <Home className="w-4 h-4" />
  3937. </button>
  3938. <button
  3939. onClick={() => requestXyJog(bedJogStep, 0)}
  3940. disabled={xyJogMutation.isPending}
  3941. className={jogButtonClass}
  3942. aria-label="Move X right"
  3943. >
  3944. <ArrowRight className="w-4 h-4" />
  3945. </button>
  3946. <div />
  3947. <button
  3948. onClick={() => requestXyJog(0, -bedJogStep)}
  3949. disabled={xyJogMutation.isPending}
  3950. className={jogButtonClass}
  3951. aria-label="Move Y back"
  3952. >
  3953. <ArrowDown className="w-4 h-4" />
  3954. </button>
  3955. <div />
  3956. </div>
  3957. <div className="flex flex-col items-center gap-1">
  3958. <button
  3959. onClick={() => requestZJog(-1)}
  3960. disabled={bedJogMutation.isPending}
  3961. className={jogButtonClass}
  3962. aria-label={t('printers.bedJog.up')}
  3963. >
  3964. <ArrowUp className="w-4 h-4" />
  3965. </button>
  3966. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  3967. <Layers className="w-4 h-4" />
  3968. </div>
  3969. <button
  3970. onClick={() => requestZJog(1)}
  3971. disabled={bedJogMutation.isPending}
  3972. className={jogButtonClass}
  3973. aria-label={t('printers.bedJog.down')}
  3974. >
  3975. <ArrowDown className="w-4 h-4" />
  3976. </button>
  3977. </div>
  3978. <div className="flex flex-col items-center gap-1">
  3979. <button
  3980. onClick={() => requestExtruderJog(-bedJogStep)}
  3981. disabled={extruderJogMutation.isPending}
  3982. className={jogButtonClass}
  3983. aria-label="Retract filament"
  3984. >
  3985. <ArrowUp className="w-4 h-4" />
  3986. </button>
  3987. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  3988. <span className="text-sm font-semibold leading-none">E</span>
  3989. </div>
  3990. <button
  3991. onClick={() => requestExtruderJog(bedJogStep)}
  3992. disabled={extruderJogMutation.isPending}
  3993. className={jogButtonClass}
  3994. aria-label="Extrude filament"
  3995. >
  3996. <ArrowDown className="w-4 h-4" />
  3997. </button>
  3998. </div>
  3999. </div>
  4000. </div>
  4001. <div className="h-px bg-bambu-dark-tertiary" />
  4002. <div className="px-3 pt-2.5 pb-3">
  4003. <div className="mb-1 text-[9px] uppercase tracking-wider text-bambu-gray/70">
  4004. {t('printers.bedJog.step')}
  4005. </div>
  4006. <div className="flex gap-1">
  4007. {[1, 10, 50].map((step) => (
  4008. <button
  4009. key={step}
  4010. onClick={() => setBedJogStep(step)}
  4011. className={`flex-1 px-1 py-1 rounded text-[10px] transition-colors ${
  4012. bedJogStep === step
  4013. ? 'bg-bambu-green/20 text-bambu-green'
  4014. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4015. }`}
  4016. >
  4017. {step}
  4018. </button>
  4019. ))}
  4020. </div>
  4021. </div>
  4022. </div>
  4023. </>
  4024. )}
  4025. </div>
  4026. );
  4027. })()}
  4028. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4029. <button
  4030. onClick={handleTogglePlateDetection}
  4031. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4032. className={`${iconControlClass} rounded-r-none ${
  4033. printer.plate_detection_enabled
  4034. ? 'bg-green-500/10 text-green-400 hover:bg-green-500/20'
  4035. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4036. }`}
  4037. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4038. >
  4039. {plateDetectionMutation.isPending ? (
  4040. <Loader2 className="w-4 h-4 animate-spin" />
  4041. ) : (
  4042. <ScanSearch className="w-4 h-4" />
  4043. )}
  4044. </button>
  4045. <button
  4046. onClick={handleOpenPlateManagement}
  4047. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4048. 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 ${
  4049. printer.plate_detection_enabled
  4050. ? 'bg-green-500/10 text-green-400 hover:bg-green-500/20'
  4051. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4052. }`}
  4053. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4054. >
  4055. {isCheckingPlate ? (
  4056. <Loader2 className="w-4 h-4 animate-spin" />
  4057. ) : (
  4058. <ChevronDown className="w-4 h-4" />
  4059. )}
  4060. </button>
  4061. </div>
  4062. {/* Print Speed */}
  4063. {(() => (
  4064. <div className="relative">
  4065. <button
  4066. data-testid="speed-control"
  4067. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4068. disabled={!isPrinting || !hasPermission('printers:control')}
  4069. className={`${iconControlClass} ${
  4070. isPrinting
  4071. ? 'bg-amber-500/10 text-amber-400 hover:bg-amber-500/20'
  4072. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4073. }`}
  4074. title={isPrinting ? t('printers.speed.title') : undefined}
  4075. >
  4076. <Gauge className="w-4 h-4" />
  4077. </button>
  4078. {showSpeedMenu === printer.id && (
  4079. <>
  4080. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4081. <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]">
  4082. {([
  4083. { mode: 1, label: t('printers.speed.silent') },
  4084. { mode: 2, label: t('printers.speed.standard') },
  4085. { mode: 3, label: t('printers.speed.sport') },
  4086. { mode: 4, label: t('printers.speed.ludicrous') },
  4087. ] as const).map(({ mode, label }) => (
  4088. <button
  4089. key={mode}
  4090. onClick={() => {
  4091. printSpeedMutation.mutate(mode);
  4092. setShowSpeedMenu(null);
  4093. }}
  4094. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4095. status.speed_level === mode
  4096. ? 'text-bambu-green bg-bambu-green/10'
  4097. : 'text-white hover:bg-bambu-dark-tertiary'
  4098. }`}
  4099. >
  4100. {label}
  4101. </button>
  4102. ))}
  4103. </div>
  4104. </>
  4105. )}
  4106. </div>
  4107. ))()}
  4108. </div>
  4109. {/* Right: Print Control Buttons */}
  4110. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4111. {/* Pause/Resume button */}
  4112. {(() => {
  4113. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4114. return (
  4115. <button
  4116. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4117. disabled={pauseUnavailable}
  4118. className={`
  4119. ${printControlClass}
  4120. ${pauseUnavailable
  4121. ? unavailablePrintActionClass
  4122. : isPaused
  4123. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4124. : 'bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30'
  4125. }
  4126. `}
  4127. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4128. >
  4129. {isPaused ? <Play className="w-3 h-3" /> : <Pause className="w-3 h-3" />}
  4130. {isPaused ? t('printers.resume') : t('printers.pause')}
  4131. </button>
  4132. );
  4133. })()}
  4134. {/* Stop button */}
  4135. {(() => {
  4136. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4137. return (
  4138. <button
  4139. onClick={() => setShowStopConfirm(true)}
  4140. disabled={stopUnavailable}
  4141. className={`
  4142. ${printControlClass}
  4143. ${stopUnavailable
  4144. ? unavailablePrintActionClass
  4145. : 'bg-red-500/20 text-red-400 hover:bg-red-500/30'
  4146. }
  4147. `}
  4148. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4149. >
  4150. <Square className="w-3 h-3" />
  4151. {t('printers.stop')}
  4152. </button>
  4153. );
  4154. })()}
  4155. </div>
  4156. </div>
  4157. </div>
  4158. );
  4159. })()}
  4160. {/* AMS Units - 2-Column Grid Layout */}
  4161. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4162. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4163. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4164. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4165. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4166. const filamentSlotClass = 'min-w-14';
  4167. // #1762 (comment 2): while a print is running/paused, overlay a small
  4168. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4169. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4170. // staged to a printer with mismatched filament: the wrong-slot pill
  4171. // is visible the instant printing starts.
  4172. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4173. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4174. ? status.ams_mapping
  4175. : [];
  4176. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4177. const boundedSlotCount = Math.max(1, slotCount);
  4178. const gapCount = Math.max(0, boundedSlotCount - 1);
  4179. const minWidth = `calc(${boundedSlotCount} * 3.5rem + ${gapCount} * 0.25rem + 1rem)`;
  4180. return {
  4181. flex: `1 1 ${minWidth}`,
  4182. minWidth,
  4183. };
  4184. };
  4185. return (
  4186. <div className="mt-3">
  4187. {/* Section Header */}
  4188. <div className="flex items-center gap-2 mb-2">
  4189. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  4190. {t('printers.filaments')}
  4191. </span>
  4192. <AmsBackupBadge
  4193. state={status.ams_filament_backup}
  4194. onClick={() => setAmsBackupModalOpen(true)}
  4195. />
  4196. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4197. </div>
  4198. {/* AMS Content */}
  4199. <div className="flex flex-wrap gap-2">
  4200. {/* Regular AMS units */}
  4201. {regularAms.map((ams) => {
  4202. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4203. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4204. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4205. const isLeftNozzle = extruderId === 1;
  4206. const isRightNozzle = extruderId === 0;
  4207. return (
  4208. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4209. {/* Header: Label + Stats (no icon) */}
  4210. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4211. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4212. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4213. <AmsNameHoverCard
  4214. ams={ams}
  4215. printerId={printer.id}
  4216. label={getAmsLabel(ams.id, ams.tray.length)}
  4217. amsLabels={amsLabels}
  4218. canEdit={hasPermission('printers:update')}
  4219. onSaved={refetchAmsLabels}
  4220. >
  4221. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4222. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4223. </span>
  4224. </AmsNameHoverCard>
  4225. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4226. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4227. )}
  4228. </div>
  4229. {(ams.humidity != null || ams.temp != null) && (
  4230. <div className="flex shrink-0 items-center gap-1.5">
  4231. {ams.humidity != null && (
  4232. <HumidityIndicator
  4233. humidity={ams.humidity}
  4234. goodThreshold={amsThresholds?.humidityGood}
  4235. fairThreshold={amsThresholds?.humidityFair}
  4236. onClick={() => setAmsHistoryModal({
  4237. amsId: ams.id,
  4238. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4239. mode: 'humidity',
  4240. })}
  4241. compact
  4242. />
  4243. )}
  4244. {ams.temp != null && (
  4245. <div className="mr-1">
  4246. <TemperatureIndicator
  4247. temp={ams.temp}
  4248. goodThreshold={amsThresholds?.tempGood}
  4249. fairThreshold={amsThresholds?.tempFair}
  4250. onClick={() => setAmsHistoryModal({
  4251. amsId: ams.id,
  4252. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4253. mode: 'temperature',
  4254. })}
  4255. compact
  4256. />
  4257. </div>
  4258. )}
  4259. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s) */}
  4260. {status.supports_drying && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4261. <button
  4262. disabled={!!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4263. onClick={(e) => {
  4264. if (ams.dry_time > 0) {
  4265. stopDryingMutation.mutate(ams.id);
  4266. } else if (dryingPopoverAmsId === ams.id) {
  4267. setDryingPopoverAmsId(null);
  4268. } else {
  4269. const firstTray = ams.tray.find(t => t.tray_type);
  4270. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4271. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4272. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4273. setDryingFilament(filType);
  4274. setDryingTemp(preset[moduleType] || preset.n3f);
  4275. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4276. setDryingRotateTray(false);
  4277. setDryingPopoverModuleType(ams.module_type);
  4278. setDryingPopoverAmsId(ams.id);
  4279. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4280. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4281. }
  4282. }}
  4283. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4284. ams.dry_time > 0
  4285. ? 'bg-amber-500/20 text-amber-400'
  4286. : ams.dry_sf_reason?.length
  4287. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4288. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4289. }`}
  4290. title={ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t('printers.drying.powerRequired') : t('printers.drying.start')}
  4291. >
  4292. <Flame className="w-3 h-3" />
  4293. </button>
  4294. )}
  4295. </div>
  4296. )}
  4297. </div>
  4298. {/* Drying status bar */}
  4299. {ams.dry_time > 0 && (
  4300. <div className="flex items-center gap-2 rounded-lg bg-amber-500/10 px-2 py-1 text-[9px]">
  4301. <Flame className="w-3 h-3 text-amber-400 shrink-0" />
  4302. <span className="text-amber-400 font-medium">{t('printers.drying.active')}</span>
  4303. <span className="text-amber-300/70">
  4304. {t('printers.drying.timeRemaining', {
  4305. time: ams.dry_time >= 60
  4306. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4307. : `${ams.dry_time}m`
  4308. })}
  4309. </span>
  4310. <button
  4311. onClick={() => stopDryingMutation.mutate(ams.id)}
  4312. disabled={stopDryingMutation.isPending}
  4313. className="ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50"
  4314. title={t('printers.drying.stop')}
  4315. >
  4316. <X className="w-3 h-3" />
  4317. </button>
  4318. </div>
  4319. )}
  4320. {/* Slots grid: 4 columns - always render 4 slots */}
  4321. <div className="grid w-full grid-cols-[repeat(4,minmax(3.5rem,1fr))] gap-1">
  4322. {[0, 1, 2, 3].map((slotIdx) => {
  4323. // Find tray data for this slot (may be undefined if data incomplete)
  4324. // Use array index if available, as tray.id may not always be set
  4325. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  4326. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4327. const isEmpty = !tray?.tray_type;
  4328. const emptyKind = getEmptySlotKind(tray);
  4329. // Check if this is the currently loaded tray
  4330. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  4331. const globalTrayId = ams.id * 4 + slotIdx;
  4332. const isActive = effectiveTrayNow === globalTrayId;
  4333. // Get cloud preset info if available
  4334. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4335. // Get saved slot preset mapping (for user-configured slots)
  4336. const slotPreset = slotPresets?.[globalTrayId];
  4337. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4338. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  4339. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  4340. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  4341. // Slot-assigned-only spool fill (no tag link required)
  4342. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4343. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  4344. : undefined;
  4345. const slotSpoolForFill = slotAssignmentForFill
  4346. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  4347. : undefined;
  4348. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  4349. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  4350. : null;
  4351. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4352. const inventoryFill = (() => {
  4353. const sp = inventoryAssignment?.spool;
  4354. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4355. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4356. }
  4357. return null;
  4358. })();
  4359. // If inventory says 0% but AMS reports positive remain, prefer AMS
  4360. // (inventory weight_used may be stale or over-counted — #676)
  4361. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4362. ? null : inventoryFill;
  4363. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4364. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  4365. : resolvedInventoryFill !== null ? 'inventory' as const
  4366. : hasFillLevel ? 'ams' as const
  4367. : undefined;
  4368. // Build filament data for hover card
  4369. const filamentData = tray?.tray_type ? {
  4370. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4371. // Spoolman spool name wins over cloud lookup so a slot bound to
  4372. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  4373. // Design PLA") instead of whatever the printer's filament_id
  4374. // resolves to in the cloud catalog (often "Generic PLA" for
  4375. // P-prefix local presets). Spoolman's filament.name is just the
  4376. // material+subtype ("PLA Basic"); prepend the spool's brand so
  4377. // the hover card shows "Devil Design PLA Basic" rather than the
  4378. // vendor-less form. Strip the "@<printer>..." suffix that
  4379. // BambuStudio appends to user-preset names.
  4380. 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,
  4381. colorName: getColorName(tray.tray_color || ''),
  4382. colorHex: tray.tray_color || null,
  4383. kFactor: formatKValue(tray.k),
  4384. fillLevel: effectiveFill,
  4385. trayUuid: tray.tray_uuid || null,
  4386. tagUid: tray.tag_uid || null,
  4387. fillSource,
  4388. } : null;
  4389. // Check if this specific slot is being refreshed
  4390. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  4391. refreshingSlot?.slotId === slotIdx;
  4392. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  4393. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4394. const activePrintSlotLabel = activePrintSlotIdx >= 0
  4395. ? `P${activePrintSlotIdx + 1}`
  4396. : null;
  4397. // Slot visual content (goes inside hover card)
  4398. const slotVisual = (
  4399. <div
  4400. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  4401. >
  4402. {activePrintSlotLabel && (
  4403. <span
  4404. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  4405. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  4406. 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"
  4407. >
  4408. {activePrintSlotLabel}
  4409. </span>
  4410. )}
  4411. {/* Filament color circle with 1-based slot number centered inside */}
  4412. <FilamentSlotCircle
  4413. trayColor={tray?.tray_color}
  4414. trayType={tray?.tray_type}
  4415. isEmpty={isEmpty}
  4416. emptyKind={emptyKind}
  4417. slotNumber={slotIdx + 1}
  4418. />
  4419. <div className="text-[9px] text-white font-bold truncate">
  4420. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4421. </div>
  4422. {/* Fill bar */}
  4423. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4424. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  4425. <div
  4426. className="h-full rounded-full transition-all"
  4427. style={{
  4428. width: `${effectiveFill}%`,
  4429. backgroundColor: getFillBarColor(effectiveFill),
  4430. }}
  4431. />
  4432. )}
  4433. </div>
  4434. </div>
  4435. );
  4436. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  4437. return (
  4438. <div key={slotIdx} className={`relative group w-full ${filamentSlotClass}`}>
  4439. {/* Loading overlay during RFID re-read */}
  4440. {isRefreshing && (
  4441. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4442. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4443. </div>
  4444. )}
  4445. {/* Hover card wraps only the visual content */}
  4446. {filamentData ? (
  4447. <FilamentHoverCard
  4448. data={filamentData}
  4449. actions={renderAmsSlotActions({
  4450. amsId: ams.id,
  4451. slotId: slotIdx,
  4452. loadTrayId: ams.id * 4 + slotIdx,
  4453. isRefreshing,
  4454. })}
  4455. spoolman={{
  4456. enabled: spoolmanEnabled,
  4457. // #1457: slot assignment is the user's most explicit action — it must
  4458. // outrank the tag-link, which can be stale when a non-RFID slot's
  4459. // fallback tag is still attached to a previous spool in Spoolman.
  4460. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  4461. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  4462. spoolmanUrl,
  4463. syncMode: spoolmanSyncMode,
  4464. // Suppress Link button when slot is already occupied by ANY assignment
  4465. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  4466. // suppressed for Spoolman; the maintainer screenshot shows the badge
  4467. // still appearing on slots with a local Devil Design PLA assigned.
  4468. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  4469. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  4470. setLinkSpoolModal({
  4471. tagUid: filamentData.tagUid || linkTag,
  4472. trayUuid: filamentData.trayUuid || '',
  4473. printerId: printer.id,
  4474. amsId: ams.id,
  4475. trayId: slotIdx,
  4476. });
  4477. } : undefined,
  4478. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  4479. }}
  4480. inventory={(() => {
  4481. if (spoolmanEnabled) {
  4482. if (spoolmanLoading) return undefined;
  4483. const slotAssignment = slotAssignmentForFill;
  4484. const spoolmanSpool = slotSpoolForFill;
  4485. return {
  4486. assignedSpool: spoolmanSpool ? {
  4487. id: spoolmanSpool.id,
  4488. material: spoolmanSpool.material,
  4489. brand: spoolmanSpool.brand ?? null,
  4490. color_name: spoolmanSpool.color_name ?? null,
  4491. remainingWeightGrams: spoolmanSpool.label_weight
  4492. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4493. : undefined,
  4494. } : null,
  4495. onAssignSpool: () => setAssignSpoolModal({
  4496. printerId: printer.id,
  4497. amsId: ams.id,
  4498. trayId: slotIdx,
  4499. trayInfo: {
  4500. type: tray?.tray_type || filamentData.profile,
  4501. material: tray?.tray_type ?? undefined,
  4502. profile: filamentData.profile,
  4503. color: filamentData.colorHex || '',
  4504. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4505. },
  4506. }),
  4507. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4508. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4509. };
  4510. }
  4511. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4512. return {
  4513. assignedSpool: assignment?.spool ? {
  4514. id: assignment.spool.id,
  4515. material: assignment.spool.material,
  4516. brand: assignment.spool.brand,
  4517. color_name: assignment.spool.color_name,
  4518. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4519. } : null,
  4520. onAssignSpool: () => setAssignSpoolModal({
  4521. printerId: printer.id,
  4522. amsId: ams.id,
  4523. trayId: slotIdx,
  4524. trayInfo: {
  4525. type: tray?.tray_type || filamentData.profile,
  4526. material: tray?.tray_type ?? undefined,
  4527. profile: filamentData.profile,
  4528. color: filamentData.colorHex || '',
  4529. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4530. },
  4531. }),
  4532. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  4533. isAssigned: !!assignment || isBambuLabSpool(tray),
  4534. };
  4535. })()}
  4536. configureSlot={{
  4537. enabled: hasPermission('printers:control'),
  4538. onConfigure: () => setConfigureSlotModal({
  4539. amsId: ams.id,
  4540. trayId: slotIdx,
  4541. trayCount: ams.tray.length,
  4542. trayType: tray?.tray_type || undefined,
  4543. trayColor: tray?.tray_color || undefined,
  4544. traySubBrands: tray?.tray_sub_brands || undefined,
  4545. trayInfoIdx: tray?.tray_info_idx || undefined,
  4546. extruderId: mappedExtruderId,
  4547. caliIdx: tray?.cali_idx,
  4548. savedPresetId: slotPreset?.preset_id,
  4549. }),
  4550. }}
  4551. >
  4552. {slotVisual}
  4553. </FilamentHoverCard>
  4554. ) : (
  4555. <EmptySlotHoverCard
  4556. kind={emptyKind ?? undefined}
  4557. actions={renderAmsSlotActions({
  4558. amsId: ams.id,
  4559. slotId: slotIdx,
  4560. loadTrayId: ams.id * 4 + slotIdx,
  4561. isRefreshing,
  4562. })}
  4563. configureSlot={{
  4564. enabled: hasPermission('printers:control'),
  4565. onConfigure: () => setConfigureSlotModal({
  4566. amsId: ams.id,
  4567. trayId: slotIdx,
  4568. trayCount: ams.tray.length,
  4569. extruderId: mappedExtruderId,
  4570. }),
  4571. }}
  4572. onAssignSpool={() => setAssignSpoolModal({
  4573. printerId: printer.id,
  4574. amsId: ams.id,
  4575. trayId: slotIdx,
  4576. trayInfo: {
  4577. type: '',
  4578. material: undefined,
  4579. profile: '',
  4580. color: '',
  4581. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4582. },
  4583. })}
  4584. >
  4585. {slotVisual}
  4586. </EmptySlotHoverCard>
  4587. )}
  4588. </div>
  4589. );
  4590. })}
  4591. </div>
  4592. </div>
  4593. );
  4594. })}
  4595. {/* HT AMS units */}
  4596. {htAms.map((ams) => {
  4597. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4598. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4599. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4600. const isLeftNozzle = extruderId === 1;
  4601. const isRightNozzle = extruderId === 0;
  4602. const tray = ams.tray[0];
  4603. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4604. const isEmpty = !tray?.tray_type;
  4605. const emptyKind = getEmptySlotKind(tray);
  4606. // Check if this is the currently loaded tray
  4607. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  4608. const isActive = effectiveTrayNow === globalTrayId;
  4609. // Get cloud preset info if available
  4610. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4611. // Get saved slot preset mapping (for user-configured slots)
  4612. const slotPreset = slotPresets?.[globalTrayId];
  4613. const htSlotId = tray?.id ?? 0;
  4614. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4615. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  4616. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  4617. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  4618. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4619. const htInventoryFill = (() => {
  4620. const sp = htInventoryAssignment?.spool;
  4621. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4622. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4623. }
  4624. return null;
  4625. })();
  4626. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  4627. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4628. ? null : htInventoryFill;
  4629. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  4630. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4631. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  4632. : undefined;
  4633. const htSlotSpoolForFill = htSlotAssignmentForFill
  4634. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  4635. : undefined;
  4636. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  4637. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  4638. : null;
  4639. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4640. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  4641. : htResolvedInventoryFill !== null ? 'inventory' as const
  4642. : hasFillLevel ? 'ams' as const
  4643. : undefined;
  4644. // Build filament data for hover card
  4645. const filamentData = tray?.tray_type ? {
  4646. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4647. 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,
  4648. colorName: getColorName(tray.tray_color || ''),
  4649. colorHex: tray.tray_color || null,
  4650. kFactor: formatKValue(tray.k),
  4651. fillLevel: htEffectiveFill,
  4652. trayUuid: tray.tray_uuid || null,
  4653. tagUid: tray.tag_uid || null,
  4654. fillSource: htFillSource,
  4655. } : null;
  4656. // Check if this specific slot is being refreshed
  4657. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  4658. refreshingSlot?.slotId === htSlotId;
  4659. // #1762 (comment 2): active print-slot index for this HT slot.
  4660. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4661. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  4662. ? `P${htActivePrintSlotIdx + 1}`
  4663. : null;
  4664. // Slot visual content (goes inside hover card)
  4665. const slotVisual = (
  4666. <div
  4667. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  4668. >
  4669. {htActivePrintSlotLabel && (
  4670. <span
  4671. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  4672. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  4673. 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"
  4674. >
  4675. {htActivePrintSlotLabel}
  4676. </span>
  4677. )}
  4678. {/* Filament color circle with 1-based slot number centered inside */}
  4679. <FilamentSlotCircle
  4680. trayColor={tray?.tray_color}
  4681. trayType={tray?.tray_type}
  4682. isEmpty={isEmpty}
  4683. emptyKind={emptyKind}
  4684. slotNumber={1}
  4685. />
  4686. <div className="text-[9px] text-white font-bold truncate">
  4687. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4688. </div>
  4689. {/* Fill bar */}
  4690. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4691. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  4692. <div
  4693. className="h-full rounded-full transition-all"
  4694. style={{
  4695. width: `${htEffectiveFill}%`,
  4696. backgroundColor: getFillBarColor(htEffectiveFill),
  4697. }}
  4698. />
  4699. )}
  4700. </div>
  4701. </div>
  4702. );
  4703. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  4704. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  4705. // Without this override, the L view squishes HT into a sliver next to the
  4706. // 4-slot AMS neighbors.
  4707. const htCardStyle: React.CSSProperties = { flex: '1 1 11rem', minWidth: '11rem' };
  4708. return (
  4709. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4710. {/* Row 1: Label + Nozzle + Drying */}
  4711. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4712. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4713. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4714. <AmsNameHoverCard
  4715. ams={ams}
  4716. printerId={printer.id}
  4717. label={getAmsLabel(ams.id, ams.tray.length)}
  4718. amsLabels={amsLabels}
  4719. canEdit={hasPermission('printers:update')}
  4720. onSaved={refetchAmsLabels}
  4721. >
  4722. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4723. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4724. </span>
  4725. </AmsNameHoverCard>
  4726. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4727. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4728. )}
  4729. </div>
  4730. {/* Drying button for HT AMS */}
  4731. {status.supports_drying && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4732. <div className="relative ml-auto">
  4733. <button
  4734. onClick={(e) => {
  4735. if (ams.dry_time > 0) {
  4736. stopDryingMutation.mutate(ams.id);
  4737. } else if (dryingPopoverAmsId === ams.id) {
  4738. setDryingPopoverAmsId(null);
  4739. } else {
  4740. const firstTray = ams.tray.find(t => t.tray_type);
  4741. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4742. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4743. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4744. setDryingFilament(filType);
  4745. setDryingTemp(preset[moduleType] || preset.n3f);
  4746. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4747. setDryingRotateTray(false);
  4748. setDryingPopoverModuleType(ams.module_type);
  4749. setDryingPopoverAmsId(ams.id);
  4750. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4751. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4752. }
  4753. }}
  4754. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4755. ams.dry_time > 0
  4756. ? 'bg-amber-500/20 text-amber-400'
  4757. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4758. }`}
  4759. title={ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  4760. >
  4761. <Flame className="w-3 h-3" />
  4762. </button>
  4763. </div>
  4764. )}
  4765. </div>
  4766. {/* HT AMS drying status bar */}
  4767. {ams.dry_time > 0 && (
  4768. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-500/10 px-2 py-1 text-[9px]">
  4769. <Flame className="w-3 h-3 text-amber-400 shrink-0" />
  4770. <span className="text-amber-300/70 text-[8px] truncate">
  4771. {ams.dry_time >= 60
  4772. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4773. : `${ams.dry_time}m`}
  4774. </span>
  4775. <button
  4776. onClick={() => stopDryingMutation.mutate(ams.id)}
  4777. disabled={stopDryingMutation.isPending}
  4778. className="ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0"
  4779. title={t('printers.drying.stop')}
  4780. >
  4781. <X className="w-3 h-3" />
  4782. </button>
  4783. </div>
  4784. )}
  4785. {/* Row 2: Slot (left) + Stats (right stacked) */}
  4786. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  4787. {/* Slot wrapper with loading overlay */}
  4788. <div className="relative group min-w-14 flex-1">
  4789. {/* Loading overlay during RFID re-read */}
  4790. {isHtRefreshing && (
  4791. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4792. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4793. </div>
  4794. )}
  4795. {/* Hover card wraps only the visual content */}
  4796. {filamentData ? (
  4797. <FilamentHoverCard
  4798. data={filamentData}
  4799. actions={renderAmsSlotActions({
  4800. amsId: ams.id,
  4801. slotId: htSlotId,
  4802. loadTrayId: ams.id * 4 + htSlotId,
  4803. isRefreshing: isHtRefreshing,
  4804. })}
  4805. spoolman={{
  4806. enabled: spoolmanEnabled,
  4807. // #1457: slot assignment outranks tag-link (see top-level slot block).
  4808. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  4809. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  4810. spoolmanUrl,
  4811. syncMode: spoolmanSyncMode,
  4812. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  4813. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  4814. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  4815. setLinkSpoolModal({
  4816. tagUid: filamentData.tagUid || linkTag,
  4817. trayUuid: filamentData.trayUuid || '',
  4818. printerId: printer.id,
  4819. amsId: ams.id,
  4820. trayId: htSlotId,
  4821. });
  4822. } : undefined,
  4823. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  4824. }}
  4825. inventory={(() => {
  4826. if (spoolmanEnabled) {
  4827. if (spoolmanLoading) return undefined;
  4828. const slotAssignment = htSlotAssignmentForFill;
  4829. const spoolmanSpool = htSlotSpoolForFill;
  4830. return {
  4831. assignedSpool: spoolmanSpool ? {
  4832. id: spoolmanSpool.id,
  4833. material: spoolmanSpool.material,
  4834. brand: spoolmanSpool.brand ?? null,
  4835. color_name: spoolmanSpool.color_name ?? null,
  4836. remainingWeightGrams: spoolmanSpool.label_weight
  4837. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4838. : undefined,
  4839. } : null,
  4840. onAssignSpool: () => setAssignSpoolModal({
  4841. printerId: printer.id,
  4842. amsId: ams.id,
  4843. trayId: htSlotId,
  4844. trayInfo: {
  4845. type: tray?.tray_type || filamentData.profile,
  4846. material: tray?.tray_type ?? undefined,
  4847. profile: filamentData.profile,
  4848. color: filamentData.colorHex || '',
  4849. location: getAmsLabel(ams.id, ams.tray.length),
  4850. },
  4851. }),
  4852. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4853. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4854. };
  4855. }
  4856. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4857. return {
  4858. assignedSpool: assignment?.spool ? {
  4859. id: assignment.spool.id,
  4860. material: assignment.spool.material,
  4861. brand: assignment.spool.brand,
  4862. color_name: assignment.spool.color_name,
  4863. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4864. } : null,
  4865. onAssignSpool: () => setAssignSpoolModal({
  4866. printerId: printer.id,
  4867. amsId: ams.id,
  4868. trayId: htSlotId,
  4869. trayInfo: {
  4870. type: tray?.tray_type || filamentData.profile,
  4871. material: tray?.tray_type ?? undefined,
  4872. profile: filamentData.profile,
  4873. color: filamentData.colorHex || '',
  4874. location: getAmsLabel(ams.id, ams.tray.length),
  4875. },
  4876. }),
  4877. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  4878. isAssigned: !!assignment || isBambuLabSpool(tray),
  4879. };
  4880. })()}
  4881. configureSlot={{
  4882. enabled: hasPermission('printers:control'),
  4883. onConfigure: () => setConfigureSlotModal({
  4884. amsId: ams.id,
  4885. trayId: htSlotId,
  4886. trayCount: ams.tray.length,
  4887. trayType: tray?.tray_type || undefined,
  4888. trayColor: tray?.tray_color || undefined,
  4889. traySubBrands: tray?.tray_sub_brands || undefined,
  4890. trayInfoIdx: tray?.tray_info_idx || undefined,
  4891. extruderId: mappedExtruderId,
  4892. caliIdx: tray?.cali_idx,
  4893. savedPresetId: slotPreset?.preset_id,
  4894. }),
  4895. }}
  4896. >
  4897. {slotVisual}
  4898. </FilamentHoverCard>
  4899. ) : (
  4900. <EmptySlotHoverCard
  4901. kind={emptyKind ?? undefined}
  4902. actions={renderAmsSlotActions({
  4903. amsId: ams.id,
  4904. slotId: htSlotId,
  4905. loadTrayId: ams.id * 4 + htSlotId,
  4906. isRefreshing: isHtRefreshing,
  4907. })}
  4908. configureSlot={{
  4909. enabled: hasPermission('printers:control'),
  4910. onConfigure: () => setConfigureSlotModal({
  4911. amsId: ams.id,
  4912. trayId: htSlotId,
  4913. trayCount: ams.tray.length,
  4914. extruderId: mappedExtruderId,
  4915. }),
  4916. }}
  4917. onAssignSpool={() => setAssignSpoolModal({
  4918. printerId: printer.id,
  4919. amsId: ams.id,
  4920. trayId: htSlotId,
  4921. trayInfo: {
  4922. type: '',
  4923. material: undefined,
  4924. profile: '',
  4925. color: '',
  4926. location: getAmsLabel(ams.id, ams.tray.length),
  4927. },
  4928. })}
  4929. >
  4930. {slotVisual}
  4931. </EmptySlotHoverCard>
  4932. )}
  4933. </div>
  4934. {/* Stats stacked vertically: Temp on top, Humidity below */}
  4935. {(ams.humidity != null || ams.temp != null) && (
  4936. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  4937. {ams.temp != null && (
  4938. <TemperatureIndicator
  4939. temp={ams.temp}
  4940. goodThreshold={amsThresholds?.tempGood}
  4941. fairThreshold={amsThresholds?.tempFair}
  4942. onClick={() => setAmsHistoryModal({
  4943. amsId: ams.id,
  4944. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4945. mode: 'temperature',
  4946. })}
  4947. compact
  4948. />
  4949. )}
  4950. {ams.humidity != null && (
  4951. <HumidityIndicator
  4952. humidity={ams.humidity}
  4953. goodThreshold={amsThresholds?.humidityGood}
  4954. fairThreshold={amsThresholds?.humidityFair}
  4955. onClick={() => setAmsHistoryModal({
  4956. amsId: ams.id,
  4957. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4958. mode: 'humidity',
  4959. })}
  4960. compact
  4961. />
  4962. )}
  4963. </div>
  4964. )}
  4965. </div>
  4966. </div>
  4967. );
  4968. })}
  4969. {/* External spool(s) - grouped in one card like regular AMS */}
  4970. {status.vt_tray.length > 0 && (
  4971. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4972. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4973. <span className="block min-w-0 flex-1 truncate text-[10px] text-white font-medium">{t('printers.external')}</span>
  4974. </div>
  4975. <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`}>
  4976. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  4977. const extTrayId = extTray.id ?? 254;
  4978. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  4979. // generically — use active_extruder to determine L vs R:
  4980. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  4981. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  4982. ? (extTrayId === 254 && status.active_extruder === 1) ||
  4983. (extTrayId === 255 && status.active_extruder === 0)
  4984. : effectiveTrayNow === extTrayId;
  4985. const slotTrayId = extTrayId - 254; // 0 or 1
  4986. const extLabel = isDualNozzle
  4987. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  4988. : '';
  4989. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  4990. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  4991. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  4992. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  4993. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  4994. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  4995. const extInventoryFill = (() => {
  4996. const sp = extInventoryAssignment?.spool;
  4997. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4998. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4999. }
  5000. return null;
  5001. })();
  5002. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5003. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5004. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5005. ? null : extInventoryFill;
  5006. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5007. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5008. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5009. : undefined;
  5010. const extSlotSpoolForFill = extSlotAssignmentForFill
  5011. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5012. : undefined;
  5013. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5014. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5015. : null;
  5016. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5017. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5018. : extResolvedInventoryFill !== null ? 'inventory' as const
  5019. : extHasFillLevel ? 'ams' as const
  5020. : undefined;
  5021. const extFilamentData = {
  5022. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5023. 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',
  5024. colorName: getColorName(extTray.tray_color || ''),
  5025. colorHex: extTray.tray_color || null,
  5026. kFactor: formatKValue(extTray.k),
  5027. fillLevel: extEffectiveFill,
  5028. trayUuid: extTray.tray_uuid || null,
  5029. tagUid: extTray.tag_uid || null,
  5030. fillSource: extFillSource,
  5031. };
  5032. const isEmpty = !extTray.tray_type;
  5033. const emptyKind = getEmptySlotKind(extTray);
  5034. const extSlotContent = (
  5035. <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' : ''}`}>
  5036. {/* Filament color circle with 1-based slot number centered inside */}
  5037. <FilamentSlotCircle
  5038. trayColor={extTray.tray_color}
  5039. trayType={extTray.tray_type}
  5040. isEmpty={isEmpty}
  5041. emptyKind={emptyKind}
  5042. slotNumber={slotTrayId + 1}
  5043. />
  5044. <div className={`text-[9px] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5045. {extTray.tray_type || t('ams.slotEmpty')}
  5046. </div>
  5047. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5048. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5049. <div
  5050. className="h-full rounded-full transition-all"
  5051. style={{
  5052. width: `${extEffectiveFill}%`,
  5053. backgroundColor: getFillBarColor(extEffectiveFill),
  5054. }}
  5055. />
  5056. )}
  5057. </div>
  5058. {extLabel && <div className="text-[7px] text-white/40 mt-0.5 truncate">{extLabel}</div>}
  5059. </div>
  5060. );
  5061. return (
  5062. <div key={extTrayId} className={`relative group w-full ${filamentSlotClass}`}>
  5063. {!isEmpty ? (
  5064. <FilamentHoverCard
  5065. data={extFilamentData}
  5066. actions={renderAmsSlotActions({
  5067. amsId: 255,
  5068. slotId: slotTrayId,
  5069. loadTrayId: extTrayId,
  5070. includeRfid: false,
  5071. })}
  5072. spoolman={{
  5073. enabled: spoolmanEnabled,
  5074. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5075. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5076. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5077. spoolmanUrl,
  5078. syncMode: spoolmanSyncMode,
  5079. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5080. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5081. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5082. setLinkSpoolModal({
  5083. tagUid: extFilamentData.tagUid || linkTag,
  5084. trayUuid: extFilamentData.trayUuid || '',
  5085. printerId: printer.id,
  5086. amsId: 255,
  5087. trayId: slotTrayId,
  5088. });
  5089. } : undefined,
  5090. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5091. }}
  5092. inventory={(() => {
  5093. if (spoolmanEnabled) {
  5094. if (spoolmanLoading) return undefined;
  5095. const slotAssignment = extSlotAssignmentForFill;
  5096. const spoolmanSpool = extSlotSpoolForFill;
  5097. return {
  5098. assignedSpool: spoolmanSpool ? {
  5099. id: spoolmanSpool.id,
  5100. material: spoolmanSpool.material,
  5101. brand: spoolmanSpool.brand ?? null,
  5102. color_name: spoolmanSpool.color_name ?? null,
  5103. remainingWeightGrams: spoolmanSpool.label_weight
  5104. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5105. : undefined,
  5106. } : null,
  5107. onAssignSpool: () => setAssignSpoolModal({
  5108. printerId: printer.id,
  5109. amsId: 255,
  5110. trayId: slotTrayId,
  5111. trayInfo: {
  5112. type: extTray.tray_type || extFilamentData.profile,
  5113. material: extTray.tray_type ?? undefined,
  5114. profile: extFilamentData.profile,
  5115. color: extFilamentData.colorHex || '',
  5116. location: extLabel || t('printers.external'),
  5117. },
  5118. }),
  5119. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5120. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5121. };
  5122. }
  5123. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5124. return {
  5125. assignedSpool: assignment?.spool ? {
  5126. id: assignment.spool.id,
  5127. material: assignment.spool.material,
  5128. brand: assignment.spool.brand,
  5129. color_name: assignment.spool.color_name,
  5130. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5131. } : null,
  5132. onAssignSpool: () => setAssignSpoolModal({
  5133. printerId: printer.id,
  5134. amsId: 255,
  5135. trayId: slotTrayId,
  5136. trayInfo: {
  5137. type: extTray.tray_type || extFilamentData.profile,
  5138. material: extTray.tray_type ?? undefined,
  5139. profile: extFilamentData.profile,
  5140. color: extFilamentData.colorHex || '',
  5141. location: extLabel || t('printers.external'),
  5142. },
  5143. }),
  5144. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5145. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5146. };
  5147. })()}
  5148. configureSlot={{
  5149. enabled: hasPermission('printers:control'),
  5150. onConfigure: () => setConfigureSlotModal({
  5151. amsId: 255,
  5152. trayId: slotTrayId,
  5153. trayCount: 1,
  5154. trayType: extTray.tray_type || undefined,
  5155. trayColor: extTray.tray_color || undefined,
  5156. traySubBrands: extTray.tray_sub_brands || undefined,
  5157. trayInfoIdx: extTray.tray_info_idx || undefined,
  5158. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5159. caliIdx: extTray.cali_idx,
  5160. savedPresetId: extSlotPreset?.preset_id,
  5161. }),
  5162. }}
  5163. >
  5164. {extSlotContent}
  5165. </FilamentHoverCard>
  5166. ) : (
  5167. <EmptySlotHoverCard
  5168. kind={emptyKind ?? undefined}
  5169. actions={renderAmsSlotActions({
  5170. amsId: 255,
  5171. slotId: slotTrayId,
  5172. loadTrayId: extTrayId,
  5173. includeRfid: false,
  5174. })}
  5175. configureSlot={{
  5176. enabled: hasPermission('printers:control'),
  5177. onConfigure: () => setConfigureSlotModal({
  5178. amsId: 255,
  5179. trayId: slotTrayId,
  5180. trayCount: 1,
  5181. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5182. }),
  5183. }}
  5184. onAssignSpool={() => setAssignSpoolModal({
  5185. printerId: printer.id,
  5186. amsId: 255,
  5187. trayId: slotTrayId,
  5188. trayInfo: {
  5189. type: '',
  5190. material: undefined,
  5191. profile: '',
  5192. color: '',
  5193. location: `External Slot ${slotTrayId + 1}`,
  5194. },
  5195. })}
  5196. >
  5197. {extSlotContent}
  5198. </EmptySlotHoverCard>
  5199. )}
  5200. </div>
  5201. );
  5202. })}
  5203. </div>
  5204. </div>
  5205. )}
  5206. </div>
  5207. </div>
  5208. );
  5209. })()}
  5210. </>
  5211. )}
  5212. {/* Bottom block (power row + action bar). Wrapped together so the
  5213. power row hugs the action bar at the card bottom instead of
  5214. floating up when there's less filament content above. */}
  5215. {viewMode === 'expanded' && (
  5216. <div className="mt-auto">
  5217. {smartPlug && (
  5218. <div className="pt-4">
  5219. <div className="flex items-center gap-2 mb-2">
  5220. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  5221. {t('printers.power', 'Power')}
  5222. </span>
  5223. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5224. </div>
  5225. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  5226. {/* Plug name + current power */}
  5227. <div className="flex items-center gap-2 min-w-0 pl-1">
  5228. <Zap className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  5229. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  5230. <span
  5231. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[10px] font-medium flex-shrink-0"
  5232. title={t('smartPlugs.power')}
  5233. >
  5234. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  5235. </span>
  5236. </div>
  5237. {/* Spacer */}
  5238. <div className="flex-1" />
  5239. <div className="flex items-center gap-2">
  5240. {/* Auto-off */}
  5241. <button
  5242. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  5243. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  5244. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  5245. 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 ${
  5246. !hasPermission('smart_plugs:control')
  5247. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5248. : smartPlug.auto_off || smartPlug.auto_off_executed
  5249. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5250. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5251. }`}
  5252. >
  5253. <Clock className="w-4 h-4" />
  5254. </button>
  5255. <button
  5256. onClick={() => {
  5257. if (plugStatus?.state === 'ON') {
  5258. setShowPowerOffConfirm(true);
  5259. } else {
  5260. setShowPowerOnConfirm(true);
  5261. }
  5262. }}
  5263. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  5264. 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 ${
  5265. !hasPermission('smart_plugs:control')
  5266. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5267. : plugStatus?.state === 'ON'
  5268. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5269. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5270. }`}
  5271. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  5272. >
  5273. <Zap className="w-4 h-4" />
  5274. </button>
  5275. </div>
  5276. </div>
  5277. {/* HA entity buttons row */}
  5278. {scriptPlugs && scriptPlugs.length > 0 && (
  5279. <div className="flex items-center gap-2 mt-2">
  5280. <Home className="w-3.5 h-3.5 text-blue-400 flex-shrink-0" />
  5281. <span className="text-xs text-bambu-gray">HA:</span>
  5282. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  5283. <div className="flex flex-wrap gap-1">
  5284. {scriptPlugs.map(script => {
  5285. const isScript = script.ha_entity_id?.startsWith('script.');
  5286. return (
  5287. <button
  5288. key={script.id}
  5289. onClick={() => {
  5290. if (isScript) {
  5291. runScriptMutation.mutate({ id: script.id, action: 'on' });
  5292. } else {
  5293. setHaToggleConfirm(script);
  5294. }
  5295. }}
  5296. disabled={runScriptMutation.isPending}
  5297. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  5298. className="px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1"
  5299. >
  5300. <Play className="w-2.5 h-2.5" />
  5301. {script.name}
  5302. </button>
  5303. );
  5304. })}
  5305. </div>
  5306. </div>
  5307. )}
  5308. </div>
  5309. )}
  5310. {/* Connection Info & Actions */}
  5311. <div className="pt-4">
  5312. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  5313. <div className="flex items-center justify-between gap-2">
  5314. {printerActionsMenu}
  5315. <div className="flex items-center justify-end gap-2 flex-wrap">
  5316. {/* Camera Button */}
  5317. <Button
  5318. variant="secondary"
  5319. size="sm"
  5320. onClick={() => {
  5321. if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
  5322. onOpenEmbeddedCamera(printer.id, printer.name);
  5323. } else {
  5324. // Use saved window state or defaults
  5325. const saved = localStorage.getItem('cameraWindowState');
  5326. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  5327. const features = [
  5328. `width=${state.width}`,
  5329. `height=${state.height}`,
  5330. state.left !== undefined ? `left=${state.left}` : '',
  5331. state.top !== undefined ? `top=${state.top}` : '',
  5332. // No `noopener`: same-origin popup needs opener so the browser
  5333. // copies sessionStorage (auth token) into the new window.
  5334. 'menubar=no,toolbar=no,location=no,status=no',
  5335. ].filter(Boolean).join(',');
  5336. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  5337. }
  5338. }}
  5339. disabled={!status?.connected || !hasPermission('camera:view')}
  5340. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  5341. className={footerIconButtonClass}
  5342. >
  5343. <Video className="w-4 h-4" />
  5344. </Button>
  5345. <Button
  5346. variant="secondary"
  5347. size="sm"
  5348. onClick={() => setShowFileManager(true)}
  5349. disabled={!isConnected || !hasPermission('printers:files')}
  5350. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  5351. className={footerIconButtonClass}
  5352. >
  5353. <HardDrive className="w-4 h-4" />
  5354. </Button>
  5355. {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
  5356. <Button
  5357. size="sm"
  5358. onClick={() => setShowUploadForPrint(true)}
  5359. disabled={!hasPermission('printers:control')}
  5360. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('common.print')}
  5361. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  5362. >
  5363. <PrinterIcon className="w-4 h-4" />
  5364. {t('common.print')}
  5365. </Button>
  5366. )}
  5367. </div>
  5368. </div>
  5369. </div>
  5370. </div>
  5371. )}
  5372. </CardContent>
  5373. {/* File Manager Modal */}
  5374. {showFileManager && (
  5375. <FileManagerModal
  5376. printerId={printer.id}
  5377. printerName={printer.name}
  5378. onClose={() => setShowFileManager(false)}
  5379. />
  5380. )}
  5381. {/* Upload for Print Modal */}
  5382. {showUploadForPrint && (
  5383. <FileUploadModal
  5384. folderId={null}
  5385. onClose={() => setShowUploadForPrint(false)}
  5386. onUploadComplete={() => {}}
  5387. autoUpload
  5388. accept=".gcode,.3mf"
  5389. validateFile={(file) => {
  5390. const lower = file.name.toLowerCase();
  5391. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  5392. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  5393. }
  5394. }}
  5395. onFileUploaded={(uploadedFile) => {
  5396. // Check printer compatibility if sliced_for_model is available in metadata
  5397. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  5398. const printerModel = mapModelCode(printer.model);
  5399. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  5400. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  5401. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  5402. }
  5403. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  5404. }}
  5405. />
  5406. )}
  5407. {/* Print Modal (after upload) */}
  5408. {printAfterUpload && (
  5409. <PrintModal
  5410. mode="reprint"
  5411. libraryFileId={printAfterUpload.id}
  5412. archiveName={printAfterUpload.filename}
  5413. initialSelectedPrinterIds={[printer.id]}
  5414. onClose={() => setPrintAfterUpload(null)}
  5415. onSuccess={() => setPrintAfterUpload(null)}
  5416. cleanupLibraryAfterDispatch
  5417. />
  5418. )}
  5419. {/* MQTT Debug Modal */}
  5420. {showMQTTDebug && (
  5421. <MQTTDebugModal
  5422. printerId={printer.id}
  5423. printerName={printer.name}
  5424. onClose={() => setShowMQTTDebug(false)}
  5425. />
  5426. )}
  5427. {showDiagnostic && (
  5428. <ConnectionDiagnosticModal
  5429. printerId={printer.id}
  5430. printerName={printer.name}
  5431. onClose={() => setShowDiagnostic(false)}
  5432. />
  5433. )}
  5434. {showPrinterInfo && (
  5435. <PrinterInfoModal
  5436. printer={printer}
  5437. status={status}
  5438. totalPrintHours={maintenanceInfo?.total_print_hours}
  5439. onClose={closePrinterInfo}
  5440. />
  5441. )}
  5442. {/* Plate Check Result Modal */}
  5443. {plateCheckResult && (
  5444. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  5445. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  5446. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  5447. <div className="flex items-center gap-2">
  5448. {plateCheckResult.needs_calibration ? (
  5449. <ScanSearch className="w-5 h-5 text-blue-500" />
  5450. ) : plateCheckResult.is_empty ? (
  5451. <CheckCircle className="w-5 h-5 text-green-500" />
  5452. ) : (
  5453. <XCircle className="w-5 h-5 text-yellow-500" />
  5454. )}
  5455. <h2 className="text-lg font-semibold text-white">
  5456. Build Plate Check
  5457. </h2>
  5458. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  5459. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  5460. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  5461. </span>
  5462. )}
  5463. </div>
  5464. <button
  5465. onClick={() => closePlateCheckModal()}
  5466. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  5467. >
  5468. <X className="w-5 h-5" />
  5469. </button>
  5470. </div>
  5471. <div className="p-4 space-y-4">
  5472. {plateCheckResult.needs_calibration ? (
  5473. <>
  5474. <div className="p-3 rounded-lg bg-blue-500/20 border border-blue-500/50">
  5475. <p className="font-medium text-blue-400">
  5476. {t('printers.plateDetection.calibrationRequired')}
  5477. </p>
  5478. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  5479. </div>
  5480. <div className="text-sm text-bambu-gray space-y-2">
  5481. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  5482. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  5483. </div>
  5484. </>
  5485. ) : (
  5486. <>
  5487. <div className={`p-3 rounded-lg ${plateCheckResult.is_empty ? 'bg-green-500/20 border border-green-500/50' : 'bg-yellow-500/20 border border-yellow-500/50'}`}>
  5488. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-400' : 'text-yellow-400'}`}>
  5489. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  5490. </p>
  5491. <p className="text-sm text-bambu-gray mt-1">
  5492. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  5493. </p>
  5494. </div>
  5495. {plateCheckResult.debug_image_url && (
  5496. <div>
  5497. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  5498. <img
  5499. src={plateCheckResult.debug_image_url}
  5500. alt={t('printers.plateDetection.analysisPreview')}
  5501. className="w-full rounded-lg border border-bambu-dark-tertiary"
  5502. />
  5503. <p className="text-xs text-bambu-gray mt-2">
  5504. {t('printers.plateDetection.analysisLegend')}
  5505. </p>
  5506. </div>
  5507. )}
  5508. <p className="text-xs text-bambu-gray">
  5509. {plateCheckResult.message}
  5510. </p>
  5511. </>
  5512. )}
  5513. {/* Saved References Grid */}
  5514. {plateReferences && plateReferences.references.length > 0 && (
  5515. <div className="mt-4">
  5516. <div className="flex items-center gap-2 mb-2">
  5517. <p className="text-sm font-medium text-white shrink-0">
  5518. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  5519. </p>
  5520. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5521. </div>
  5522. <div className="grid grid-cols-5 gap-2">
  5523. {plateReferences.references.map((ref) => (
  5524. <div key={ref.index} className="relative group">
  5525. <img
  5526. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  5527. alt={ref.label || `Reference ${ref.index + 1}`}
  5528. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  5529. />
  5530. {/* Delete button */}
  5531. <button
  5532. onClick={() => handleDeleteRef(ref.index)}
  5533. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  5534. title={t('printers.plateDetection.deleteReference')}
  5535. >
  5536. <X className="w-3 h-3 text-white" />
  5537. </button>
  5538. {/* Label */}
  5539. {editingRefLabel?.index === ref.index ? (
  5540. <input
  5541. type="text"
  5542. value={editingRefLabel.label}
  5543. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  5544. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  5545. onKeyDown={(e) => {
  5546. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  5547. if (e.key === 'Escape') setEditingRefLabel(null);
  5548. }}
  5549. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  5550. autoFocus
  5551. placeholder={t('printers.plateDetection.labelPlaceholder')}
  5552. />
  5553. ) : (
  5554. <p
  5555. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  5556. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  5557. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  5558. >
  5559. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  5560. </p>
  5561. )}
  5562. {/* Timestamp */}
  5563. <p className="text-[10px] text-bambu-gray/60">
  5564. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  5565. </p>
  5566. </div>
  5567. ))}
  5568. </div>
  5569. </div>
  5570. )}
  5571. {/* ROI Editor */}
  5572. {!plateCheckResult.needs_calibration && (
  5573. <div className="mt-4">
  5574. <div className="flex items-center justify-between mb-2">
  5575. <div className="flex min-w-0 flex-1 items-center gap-2">
  5576. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  5577. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5578. </div>
  5579. {!editingRoi ? (
  5580. <Button
  5581. variant="ghost"
  5582. size="sm"
  5583. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  5584. >
  5585. <Pencil className="w-3 h-3 mr-1" />
  5586. {t('common.edit')}
  5587. </Button>
  5588. ) : (
  5589. <div className="flex gap-1">
  5590. <Button
  5591. variant="ghost"
  5592. size="sm"
  5593. onClick={() => setEditingRoi(null)}
  5594. disabled={isSavingRoi}
  5595. >
  5596. {t('common.cancel')}
  5597. </Button>
  5598. <Button
  5599. size="sm"
  5600. onClick={handleSaveRoi}
  5601. disabled={isSavingRoi}
  5602. >
  5603. {isSavingRoi ? <Loader2 className="w-3 h-3 animate-spin" /> : t('common.save')}
  5604. </Button>
  5605. </div>
  5606. )}
  5607. </div>
  5608. {editingRoi ? (
  5609. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  5610. <div className="grid grid-cols-2 gap-3">
  5611. <div>
  5612. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  5613. <input
  5614. type="range"
  5615. min="0"
  5616. max="0.9"
  5617. step="0.01"
  5618. value={editingRoi.x}
  5619. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  5620. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5621. />
  5622. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  5623. </div>
  5624. <div>
  5625. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  5626. <input
  5627. type="range"
  5628. min="0"
  5629. max="0.9"
  5630. step="0.01"
  5631. value={editingRoi.y}
  5632. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  5633. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5634. />
  5635. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  5636. </div>
  5637. <div>
  5638. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  5639. <input
  5640. type="range"
  5641. min="0.1"
  5642. max="1"
  5643. step="0.01"
  5644. value={editingRoi.w}
  5645. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  5646. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5647. />
  5648. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  5649. </div>
  5650. <div>
  5651. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  5652. <input
  5653. type="range"
  5654. min="0.1"
  5655. max="1"
  5656. step="0.01"
  5657. value={editingRoi.h}
  5658. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  5659. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5660. />
  5661. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  5662. </div>
  5663. </div>
  5664. <p className="text-xs text-bambu-gray">
  5665. {t('printers.roi.instruction')}
  5666. </p>
  5667. </div>
  5668. ) : (
  5669. <p className="text-xs text-bambu-gray">
  5670. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  5671. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  5672. </p>
  5673. )}
  5674. </div>
  5675. )}
  5676. </div>
  5677. <div className="flex justify-end gap-2 p-4">
  5678. {plateCheckResult.needs_calibration ? (
  5679. <>
  5680. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  5681. {t('common.cancel')}
  5682. </Button>
  5683. <Button
  5684. onClick={() => handleCalibratePlate()}
  5685. disabled={isCalibrating}
  5686. >
  5687. {isCalibrating ? (
  5688. <>
  5689. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  5690. Calibrating...
  5691. </>
  5692. ) : (
  5693. 'Calibrate Empty Plate'
  5694. )}
  5695. </Button>
  5696. </>
  5697. ) : (
  5698. <>
  5699. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  5700. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  5701. </Button>
  5702. <Button onClick={() => closePlateCheckModal()}>
  5703. Close
  5704. </Button>
  5705. </>
  5706. )}
  5707. </div>
  5708. </div>
  5709. </div>
  5710. )}
  5711. {/* Power On Confirmation */}
  5712. {showPowerOnConfirm && smartPlug && (
  5713. <ConfirmModal
  5714. title={t('printers.confirm.powerOnTitle')}
  5715. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  5716. confirmText={t('printers.confirm.powerOnButton')}
  5717. variant="default"
  5718. onConfirm={() => {
  5719. powerControlMutation.mutate('on');
  5720. setShowPowerOnConfirm(false);
  5721. }}
  5722. onCancel={() => setShowPowerOnConfirm(false)}
  5723. />
  5724. )}
  5725. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  5726. disconnects MQTT, which stops progress tracking + completion
  5727. notifications for the in-flight job. Idle / FINISH / FAILED states
  5728. skip this dialog and toggle directly. */}
  5729. {confirmMaintenanceEnter && (
  5730. <ConfirmModal
  5731. title={t('printers.maintenance.confirmMidPrintTitle')}
  5732. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  5733. confirmText={t('printers.maintenance.menuEnter')}
  5734. variant="danger"
  5735. onConfirm={() => {
  5736. maintenanceMutation.mutate(false);
  5737. setConfirmMaintenanceEnter(false);
  5738. }}
  5739. onCancel={() => setConfirmMaintenanceEnter(false)}
  5740. />
  5741. )}
  5742. {/* Power Off Confirmation */}
  5743. {showPowerOffConfirm && smartPlug && (
  5744. <ConfirmModal
  5745. title={t('printers.confirm.powerOffTitle')}
  5746. message={
  5747. status?.state === 'RUNNING'
  5748. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  5749. : t('printers.confirm.powerOffMessage', { name: printer.name })
  5750. }
  5751. confirmText={t('printers.confirm.powerOffButton')}
  5752. variant="danger"
  5753. onConfirm={() => {
  5754. powerControlMutation.mutate('off');
  5755. setShowPowerOffConfirm(false);
  5756. }}
  5757. onCancel={() => setShowPowerOffConfirm(false)}
  5758. />
  5759. )}
  5760. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  5761. {haToggleConfirm && (
  5762. <ConfirmModal
  5763. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  5764. message={
  5765. status?.state === 'RUNNING'
  5766. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5767. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5768. }
  5769. confirmText={t('printers.confirm.haToggleButton')}
  5770. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  5771. onConfirm={() => {
  5772. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  5773. setHaToggleConfirm(null);
  5774. }}
  5775. onCancel={() => setHaToggleConfirm(null)}
  5776. />
  5777. )}
  5778. {/* Stop Print Confirmation */}
  5779. {showStopConfirm && (
  5780. <ConfirmModal
  5781. title={t('printers.confirm.stopTitle')}
  5782. message={t('printers.confirm.stopMessage', { name: printer.name })}
  5783. confirmText={t('printers.confirm.stopButton')}
  5784. variant="danger"
  5785. onConfirm={() => {
  5786. stopPrintMutation.mutate();
  5787. setShowStopConfirm(false);
  5788. }}
  5789. onCancel={() => setShowStopConfirm(false)}
  5790. />
  5791. )}
  5792. {/* Pause Print Confirmation */}
  5793. {showPauseConfirm && (
  5794. <ConfirmModal
  5795. title={t('printers.confirm.pauseTitle')}
  5796. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  5797. confirmText={t('printers.confirm.pauseButton')}
  5798. variant="default"
  5799. onConfirm={() => {
  5800. pausePrintMutation.mutate();
  5801. setShowPauseConfirm(false);
  5802. }}
  5803. onCancel={() => setShowPauseConfirm(false)}
  5804. />
  5805. )}
  5806. {/* Resume Print Confirmation */}
  5807. {showResumeConfirm && (
  5808. <ConfirmModal
  5809. title={t('printers.confirm.resumeTitle')}
  5810. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  5811. confirmText={t('printers.confirm.resumeButton')}
  5812. variant="default"
  5813. onConfirm={() => {
  5814. resumePrintMutation.mutate();
  5815. setShowResumeConfirm(false);
  5816. }}
  5817. onCancel={() => setShowResumeConfirm(false)}
  5818. />
  5819. )}
  5820. {/* Bed Jog — not-homed warning (Studio-style) */}
  5821. {showNotHomedModal && (
  5822. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
  5823. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5">
  5824. <div className="flex items-start gap-3 mb-4">
  5825. <AlertTriangle className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
  5826. <div>
  5827. <h3 className="text-sm font-semibold text-white mb-1">
  5828. {t('printers.bedJog.notHomedTitle')}
  5829. </h3>
  5830. <p className="text-xs text-bambu-gray leading-relaxed">
  5831. {t('printers.bedJog.notHomedMessage')}
  5832. </p>
  5833. </div>
  5834. </div>
  5835. <div className="flex flex-col gap-2">
  5836. <button
  5837. onClick={() => {
  5838. homeAxesMutation.mutate('all');
  5839. setShowNotHomedModal(null);
  5840. }}
  5841. className="w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors"
  5842. >
  5843. {t('printers.bedJog.homeZ')}
  5844. </button>
  5845. <button
  5846. onClick={() => {
  5847. const d = showNotHomedModal.distance;
  5848. try { sessionStorage.setItem(`bambuddy.bedJog.warned.${printer.id}`, '1'); } catch { /* ignore */ }
  5849. bedJogMutation.mutate({ distance: d, force: true });
  5850. setShowNotHomedModal(null);
  5851. }}
  5852. className="w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors"
  5853. >
  5854. {t('printers.bedJog.moveAnyway')}
  5855. </button>
  5856. <button
  5857. onClick={() => setShowNotHomedModal(null)}
  5858. className="w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors"
  5859. >
  5860. {t('common.cancel')}
  5861. </button>
  5862. </div>
  5863. </div>
  5864. </div>
  5865. )}
  5866. {/* Skip Objects Modal */}
  5867. <SkipObjectsModal
  5868. printerId={printer.id}
  5869. isOpen={showSkipObjectsModal}
  5870. onClose={() => setShowSkipObjectsModal(false)}
  5871. />
  5872. {/* HMS Error Modal */}
  5873. {showHMSModal && (
  5874. <HMSErrorModal
  5875. printerName={printer.name}
  5876. errors={status?.hms_errors || []}
  5877. onClose={() => setShowHMSModal(false)}
  5878. printerId={printer.id}
  5879. hasPermission={hasPermission}
  5880. />
  5881. )}
  5882. {/* AMS Filament Backup status / control modal (#1762) */}
  5883. {amsBackupModalOpen && status && (
  5884. <AmsBackupModal
  5885. isOpen={amsBackupModalOpen}
  5886. state={status.ams_filament_backup}
  5887. amsUnits={status.ams}
  5888. amsExtruderMap={status.ams_extruder_map}
  5889. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  5890. canToggle={hasPermission('printers:control')}
  5891. pending={setAmsBackupMutation.isPending}
  5892. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  5893. onClose={() => setAmsBackupModalOpen(false)}
  5894. />
  5895. )}
  5896. {/* AMS History Modal */}
  5897. {amsHistoryModal && (
  5898. <AMSHistoryModal
  5899. isOpen={!!amsHistoryModal}
  5900. onClose={() => setAmsHistoryModal(null)}
  5901. printerId={printer.id}
  5902. printerName={printer.name}
  5903. amsId={amsHistoryModal.amsId}
  5904. amsLabel={amsHistoryModal.amsLabel}
  5905. initialMode={amsHistoryModal.mode}
  5906. thresholds={amsThresholds}
  5907. />
  5908. )}
  5909. {/* Heater History Modal (nozzle / bed / chamber) */}
  5910. {heaterHistoryModal && (
  5911. <HeaterHistoryModal
  5912. isOpen={!!heaterHistoryModal}
  5913. onClose={() => setHeaterHistoryModal(null)}
  5914. printerId={printer.id}
  5915. printerName={printer.name}
  5916. initialKind={heaterHistoryModal.initialKind}
  5917. availableKinds={heaterHistoryModal.availableKinds}
  5918. />
  5919. )}
  5920. {/* Link Spool Modal */}
  5921. {linkSpoolModal && (
  5922. <LinkSpoolModal
  5923. isOpen={!!linkSpoolModal}
  5924. onClose={() => setLinkSpoolModal(null)}
  5925. tagUid={linkSpoolModal.tagUid}
  5926. trayUuid={linkSpoolModal.trayUuid}
  5927. printerId={linkSpoolModal.printerId}
  5928. amsId={linkSpoolModal.amsId}
  5929. trayId={linkSpoolModal.trayId}
  5930. />
  5931. )}
  5932. {/* Assign Spool Modal */}
  5933. {assignSpoolModal && (
  5934. <AssignSpoolModal
  5935. isOpen={!!assignSpoolModal}
  5936. onClose={() => setAssignSpoolModal(null)}
  5937. printerId={assignSpoolModal.printerId}
  5938. amsId={assignSpoolModal.amsId}
  5939. trayId={assignSpoolModal.trayId}
  5940. trayInfo={assignSpoolModal.trayInfo}
  5941. spoolmanEnabled={!!spoolmanEnabled}
  5942. />
  5943. )}
  5944. {/* Configure AMS Slot Modal */}
  5945. {configureSlotModal && (
  5946. <ConfigureAmsSlotModal
  5947. isOpen={!!configureSlotModal}
  5948. onClose={() => setConfigureSlotModal(null)}
  5949. printerId={printer.id}
  5950. slotInfo={configureSlotModal}
  5951. printerModel={mapModelCode(printer.model) || undefined}
  5952. onSuccess={() => {
  5953. // Refresh slot presets to show updated profile name
  5954. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  5955. // Printer status will update automatically via WebSocket when AMS data changes
  5956. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  5957. }}
  5958. />
  5959. )}
  5960. {/* Edit Printer Modal */}
  5961. {showEditModal && (
  5962. <EditPrinterModal
  5963. printer={printer}
  5964. onClose={() => setShowEditModal(false)}
  5965. />
  5966. )}
  5967. {/* Firmware Update Modal */}
  5968. {showFirmwareModal && firmwareInfo && (
  5969. <FirmwareUpdateModal
  5970. printer={printer}
  5971. firmwareInfo={firmwareInfo}
  5972. onClose={() => setShowFirmwareModal(false)}
  5973. />
  5974. )}
  5975. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  5976. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  5977. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  5978. const sliderMin = 35;
  5979. const sliderMax = maxTemp + 10;
  5980. return (
  5981. <>
  5982. {/* Backdrop */}
  5983. <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
  5984. {/* Popover */}
  5985. <div
  5986. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  5987. style={{
  5988. top: dryingPopoverPos.top,
  5989. left: dryingPopoverPos.left,
  5990. // Cap to the space between the popover's top and the bottom
  5991. // viewport margin (8px, matching computePopoverPosition's
  5992. // margin). When the popover is taller than that space — short
  5993. // viewport, landscape phone, zoomed-in — the body scrolls and
  5994. // the footer stays pinned, so the Start button is always
  5995. // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
  5996. // Safari's bottom toolbar overlay doesn't clip the footer
  5997. // (#1669, iPhone 17 Safari).
  5998. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  5999. }}
  6000. onClick={e => e.stopPropagation()}
  6001. >
  6002. {/* Header */}
  6003. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6004. <Flame className="w-3.5 h-3.5 text-bambu-green" />
  6005. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6006. </div>
  6007. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6008. {/* Body */}
  6009. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6010. {/* Filament type select */}
  6011. <div>
  6012. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6013. <ToolbarDropdown
  6014. value={dryingFilament}
  6015. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6016. onChange={fil => {
  6017. setDryingFilament(fil);
  6018. const preset = dryingPresets[fil];
  6019. if (preset) {
  6020. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6021. setDryingTemp(preset[key]);
  6022. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6023. }
  6024. }}
  6025. fullWidth
  6026. />
  6027. </div>
  6028. {/* Temperature */}
  6029. <div>
  6030. <div className="flex items-center justify-between mb-1">
  6031. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6032. <div className="flex items-center gap-1">
  6033. <input
  6034. type="number"
  6035. min={45}
  6036. max={maxTemp}
  6037. value={dryingTemp}
  6038. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6039. 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"
  6040. />
  6041. <span className="text-[10px] text-bambu-gray">°C</span>
  6042. </div>
  6043. </div>
  6044. <input
  6045. type="range"
  6046. min={sliderMin}
  6047. max={sliderMax}
  6048. value={dryingTemp}
  6049. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6050. className="w-full h-1 accent-bambu-green cursor-pointer"
  6051. />
  6052. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6053. <span>45°C</span>
  6054. <span>{maxTemp}°C</span>
  6055. </div>
  6056. </div>
  6057. {/* Duration */}
  6058. <div>
  6059. <div className="flex items-center justify-between mb-1">
  6060. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6061. <div className="flex items-center gap-1">
  6062. <input
  6063. type="number"
  6064. min={1}
  6065. max={24}
  6066. value={dryingDuration}
  6067. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6068. 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"
  6069. />
  6070. <span className="text-[10px] text-bambu-gray">{t('printers.drying.hours')}</span>
  6071. </div>
  6072. </div>
  6073. <input
  6074. type="range"
  6075. min={1}
  6076. max={24}
  6077. value={dryingDuration}
  6078. onChange={e => setDryingDuration(Number(e.target.value))}
  6079. className="w-full h-1 accent-bambu-green cursor-pointer"
  6080. />
  6081. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6082. <span>1h</span>
  6083. <span>24h</span>
  6084. </div>
  6085. </div>
  6086. {/* Rotate tray */}
  6087. <button
  6088. type="button"
  6089. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6090. aria-pressed={dryingRotateTray}
  6091. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors ${
  6092. dryingRotateTray
  6093. ? 'bg-bambu-green border-bambu-green text-white'
  6094. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  6095. }`}
  6096. >
  6097. {t('printers.drying.rotateTray')}
  6098. </button>
  6099. </div>
  6100. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6101. {/* Footer */}
  6102. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6103. <button
  6104. onClick={() => {
  6105. if (dryingPopoverAmsId !== null) {
  6106. startDryingMutation.mutate({ amsId: dryingPopoverAmsId, temp: dryingTemp, duration: dryingDuration, filament: dryingFilament, rotateTray: dryingRotateTray });
  6107. }
  6108. }}
  6109. disabled={startDryingMutation.isPending}
  6110. 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"
  6111. >
  6112. {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
  6113. </button>
  6114. </div>
  6115. </div>
  6116. </>
  6117. );
  6118. })()}
  6119. </Card>
  6120. );
  6121. }
  6122. export function AddPrinterModal({
  6123. onClose,
  6124. onAdd,
  6125. existingSerials,
  6126. }: {
  6127. onClose: () => void;
  6128. onAdd: (data: PrinterCreate) => void;
  6129. existingSerials: string[];
  6130. }) {
  6131. const { t } = useTranslation();
  6132. const [form, setForm] = useState<PrinterCreate>({
  6133. name: '',
  6134. serial_number: '',
  6135. ip_address: '',
  6136. access_code: '',
  6137. model: '',
  6138. location: '',
  6139. auto_archive: true,
  6140. });
  6141. // Discovery state
  6142. const [discovering, setDiscovering] = useState(false);
  6143. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  6144. const [discoveryError, setDiscoveryError] = useState('');
  6145. const [hasScanned, setHasScanned] = useState(false);
  6146. const [isDocker, setIsDocker] = useState(false);
  6147. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  6148. const [subnet, setSubnet] = useState('');
  6149. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  6150. // text input so users can scan a subnet Bambuddy isn't directly on
  6151. // (printer behind a router on a different L3 segment — SSDP multicast
  6152. // won't cross that boundary, only an active unicast scan will). #1564
  6153. const [customSubnet, setCustomSubnet] = useState('');
  6154. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  6155. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  6156. const [showDiagnostic, setShowDiagnostic] = useState(false);
  6157. // Setup-time pre-flight: run the connection diagnostic on save and warn
  6158. // (not block) when checks fail, so the user doesn't add a printer that
  6159. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  6160. // failed result awaiting an explicit "save anyway".
  6161. const [checkingSave, setCheckingSave] = useState(false);
  6162. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6163. // Fetch discovery info on mount + restore the last custom CIDR the user
  6164. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  6165. // time they open this modal).
  6166. useEffect(() => {
  6167. discoveryApi.getInfo().then(info => {
  6168. setIsDocker(info.is_docker);
  6169. if (info.subnets.length > 0) {
  6170. setDetectedSubnets(info.subnets);
  6171. setSubnet(info.subnets[0]);
  6172. }
  6173. }).catch(() => {
  6174. // Ignore errors, assume not Docker
  6175. });
  6176. try {
  6177. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  6178. if (saved) setCustomSubnet(saved);
  6179. } catch {
  6180. // localStorage unavailable (private mode, quota); recall is opportunistic
  6181. }
  6182. }, []);
  6183. // Filter out already-added printers
  6184. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  6185. const handleAddSubmit = async (e: React.FormEvent) => {
  6186. e.preventDefault();
  6187. setCheckingSave(true);
  6188. try {
  6189. const result = await api.diagnoseConnection({
  6190. ip_address: form.ip_address.trim(),
  6191. serial_number: form.serial_number.trim() || undefined,
  6192. access_code: form.access_code || undefined,
  6193. });
  6194. if (result.checks.some((c) => c.status === 'fail')) {
  6195. setSaveWarning(result);
  6196. return;
  6197. }
  6198. } catch {
  6199. // Diagnostic infrastructure failed — never block the save on it.
  6200. } finally {
  6201. setCheckingSave(false);
  6202. }
  6203. onAdd(form);
  6204. };
  6205. const startDiscovery = async () => {
  6206. setDiscoveryError('');
  6207. setDiscovered([]);
  6208. setDiscovering(true);
  6209. setHasScanned(false);
  6210. setScanProgress({ scanned: 0, total: 0 });
  6211. // Native installs fall back to subnet scanning when the user picks
  6212. // "Custom" — SSDP can't reach a printer on a different L3 segment
  6213. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  6214. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  6215. const wantsSubnetScan = isDocker || useCustomSubnet;
  6216. if (wantsSubnetScan && useCustomSubnet) {
  6217. try {
  6218. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  6219. } catch {
  6220. // localStorage write best-effort; user just retypes next time
  6221. }
  6222. }
  6223. try {
  6224. if (wantsSubnetScan) {
  6225. await discoveryApi.startSubnetScan(scanCidr);
  6226. // Poll for scan status and results
  6227. const pollInterval = setInterval(async () => {
  6228. try {
  6229. const status = await discoveryApi.getScanStatus();
  6230. setScanProgress({ scanned: status.scanned, total: status.total });
  6231. const printers = await discoveryApi.getDiscoveredPrinters();
  6232. setDiscovered(printers);
  6233. if (!status.running) {
  6234. clearInterval(pollInterval);
  6235. setDiscovering(false);
  6236. setHasScanned(true);
  6237. }
  6238. } catch (e) {
  6239. console.error('Failed to get scan status:', e);
  6240. }
  6241. }, 500);
  6242. } else {
  6243. // Use SSDP discovery for native installs
  6244. await discoveryApi.startDiscovery(10);
  6245. // Poll for discovered printers every second
  6246. const pollInterval = setInterval(async () => {
  6247. try {
  6248. const printers = await discoveryApi.getDiscoveredPrinters();
  6249. setDiscovered(printers);
  6250. } catch (e) {
  6251. console.error('Failed to get discovered printers:', e);
  6252. }
  6253. }, 1000);
  6254. // Stop after 10 seconds
  6255. setTimeout(async () => {
  6256. clearInterval(pollInterval);
  6257. try {
  6258. await discoveryApi.stopDiscovery();
  6259. } catch {
  6260. // Ignore stop errors
  6261. }
  6262. setDiscovering(false);
  6263. setHasScanned(true);
  6264. // Final fetch
  6265. try {
  6266. const printers = await discoveryApi.getDiscoveredPrinters();
  6267. setDiscovered(printers);
  6268. } catch (e) {
  6269. console.error('Failed to get final discovered printers:', e);
  6270. }
  6271. }, 10000);
  6272. }
  6273. } catch (e) {
  6274. console.error('Failed to start discovery:', e);
  6275. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  6276. setDiscovering(false);
  6277. setHasScanned(true);
  6278. }
  6279. };
  6280. // Reuse module-level mapModelCode
  6281. const selectPrinter = (printer: DiscoveredPrinter) => {
  6282. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  6283. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  6284. setForm({
  6285. ...form,
  6286. name: printer.name || '',
  6287. serial_number: serialNumber,
  6288. ip_address: printer.ip_address,
  6289. model: mapModelCode(printer.model),
  6290. });
  6291. // Clear discovery results after selection
  6292. setDiscovered([]);
  6293. };
  6294. // Cleanup discovery on unmount
  6295. useEffect(() => {
  6296. return () => {
  6297. discoveryApi.stopDiscovery().catch(() => {});
  6298. discoveryApi.stopSubnetScan().catch(() => {});
  6299. };
  6300. }, []);
  6301. // Close on Escape key
  6302. useEffect(() => {
  6303. const handleKeyDown = (e: KeyboardEvent) => {
  6304. if (e.key === 'Escape') onClose();
  6305. };
  6306. window.addEventListener('keydown', handleKeyDown);
  6307. return () => window.removeEventListener('keydown', handleKeyDown);
  6308. }, [onClose]);
  6309. return (
  6310. <>
  6311. <div
  6312. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6313. onClick={onClose}
  6314. >
  6315. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6316. <CardContent>
  6317. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  6318. {/* Discovery Section */}
  6319. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  6320. {/* Subnet picker — always visible. The dropdown lists detected
  6321. interface subnets and a "Custom..." sentinel that reveals
  6322. a CIDR text input for printers on a different L3 segment
  6323. (router, VLAN, etc.). #1564 */}
  6324. <div className="mb-3">
  6325. <label className="block text-sm text-bambu-gray mb-1">
  6326. {t('printers.discovery.subnetToScan')}
  6327. </label>
  6328. {detectedSubnets.length > 0 ? (
  6329. <select
  6330. 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"
  6331. value={useCustomSubnet ? '__custom__' : subnet}
  6332. onChange={(e) => {
  6333. if (e.target.value === '__custom__') {
  6334. setUseCustomSubnet(true);
  6335. } else {
  6336. setUseCustomSubnet(false);
  6337. setSubnet(e.target.value);
  6338. }
  6339. }}
  6340. disabled={discovering}
  6341. >
  6342. {detectedSubnets.map(s => (
  6343. <option key={s} value={s}>{s}</option>
  6344. ))}
  6345. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  6346. </select>
  6347. ) : (
  6348. <input
  6349. type="text"
  6350. 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"
  6351. value={subnet}
  6352. onChange={(e) => setSubnet(e.target.value)}
  6353. placeholder="192.168.1.0/24"
  6354. disabled={discovering}
  6355. />
  6356. )}
  6357. {useCustomSubnet && (
  6358. <input
  6359. type="text"
  6360. aria-label={t('printers.discovery.customSubnetLabel')}
  6361. 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"
  6362. value={customSubnet}
  6363. onChange={(e) => setCustomSubnet(e.target.value)}
  6364. placeholder="10.1.1.0/24"
  6365. disabled={discovering}
  6366. />
  6367. )}
  6368. <p className="mt-1 text-xs text-bambu-gray">
  6369. {isDocker
  6370. ? t('printers.discovery.dockerNote')
  6371. : t('printers.discovery.customSubnetNote')}
  6372. </p>
  6373. </div>
  6374. <Button
  6375. type="button"
  6376. variant="secondary"
  6377. onClick={startDiscovery}
  6378. disabled={discovering}
  6379. className="w-full"
  6380. >
  6381. {discovering ? (
  6382. <>
  6383. <Loader2 className="w-4 h-4 animate-spin" />
  6384. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  6385. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  6386. : t('printers.discovery.scanning')}
  6387. </>
  6388. ) : (
  6389. <>
  6390. <Search className="w-4 h-4" />
  6391. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  6392. </>
  6393. )}
  6394. </Button>
  6395. {discoveryError && (
  6396. <div className="mt-2 text-sm text-red-400">{discoveryError}</div>
  6397. )}
  6398. {newPrinters.length > 0 && (
  6399. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  6400. {newPrinters.map((printer) => (
  6401. <div
  6402. key={printer.serial}
  6403. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  6404. onClick={() => selectPrinter(printer)}
  6405. >
  6406. <div className="min-w-0 flex-1">
  6407. <p className="font-medium text-white text-sm truncate">
  6408. {printer.name || printer.serial}
  6409. </p>
  6410. <p className="text-xs text-bambu-gray truncate">
  6411. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  6412. {printer.serial.startsWith('unknown-') && (
  6413. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  6414. )}
  6415. </p>
  6416. </div>
  6417. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  6418. </div>
  6419. ))}
  6420. </div>
  6421. )}
  6422. {discovering && (
  6423. <p className="mt-2 text-sm text-bambu-gray text-center">
  6424. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  6425. </p>
  6426. )}
  6427. {hasScanned && !discovering && discovered.length === 0 && (
  6428. <p className="mt-2 text-sm text-bambu-gray text-center">
  6429. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  6430. </p>
  6431. )}
  6432. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  6433. <p className="mt-2 text-sm text-bambu-gray text-center">
  6434. {t('printers.discovery.allConfigured')}
  6435. </p>
  6436. )}
  6437. </div>
  6438. <form onSubmit={handleAddSubmit} className="space-y-4">
  6439. <div>
  6440. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6441. <input
  6442. type="text"
  6443. required
  6444. 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"
  6445. value={form.name}
  6446. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6447. placeholder={t('printers.modal.myPrinter')}
  6448. />
  6449. </div>
  6450. <div>
  6451. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6452. <input
  6453. type="text"
  6454. required
  6455. 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])?)*)"
  6456. 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"
  6457. value={form.ip_address}
  6458. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6459. placeholder="192.168.1.100 or printer.local"
  6460. />
  6461. </div>
  6462. <div>
  6463. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6464. <input
  6465. type="text"
  6466. required
  6467. 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"
  6468. value={form.serial_number}
  6469. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  6470. placeholder="01P00A000000000"
  6471. />
  6472. </div>
  6473. <div>
  6474. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6475. <input
  6476. type="password"
  6477. required
  6478. 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"
  6479. value={form.access_code}
  6480. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6481. placeholder={t('printers.modal.fromPrinterSettings')}
  6482. />
  6483. </div>
  6484. <div>
  6485. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  6486. <select
  6487. 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"
  6488. value={form.model || ''}
  6489. onChange={(e) => setForm({ ...form, model: e.target.value })}
  6490. >
  6491. <option value="">{t('printers.modal.selectModel')}</option>
  6492. <optgroup label="A1 Series">
  6493. <option value="A1">A1</option>
  6494. <option value="A1 Mini">A1 Mini</option>
  6495. </optgroup>
  6496. <optgroup label="A2 Series">
  6497. <option value="A2L">A2L</option>
  6498. </optgroup>
  6499. <optgroup label="H2 Series">
  6500. <option value="H2C">H2C</option>
  6501. <option value="H2D">H2D</option>
  6502. <option value="H2D Pro">H2D Pro</option>
  6503. <option value="H2S">H2S</option>
  6504. </optgroup>
  6505. <optgroup label="P Series">
  6506. <option value="P1P">P1P</option>
  6507. <option value="P1S">P1S</option>
  6508. <option value="P2S">P2S</option>
  6509. </optgroup>
  6510. <optgroup label="X1 Series">
  6511. <option value="X1">X1</option>
  6512. <option value="X1C">X1 Carbon</option>
  6513. <option value="X1E">X1E</option>
  6514. </optgroup>
  6515. <optgroup label="X2 Series">
  6516. <option value="X2D">X2D</option>
  6517. </optgroup>
  6518. </select>
  6519. </div>
  6520. <div>
  6521. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  6522. <input
  6523. type="text"
  6524. 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"
  6525. value={form.location || ''}
  6526. onChange={(e) => setForm({ ...form, location: e.target.value })}
  6527. placeholder={t('printers.modal.locationPlaceholder')}
  6528. />
  6529. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  6530. </div>
  6531. <div className="flex items-center gap-2">
  6532. <input
  6533. type="checkbox"
  6534. id="auto_archive"
  6535. checked={form.auto_archive}
  6536. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  6537. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  6538. />
  6539. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  6540. {t('printers.modal.autoArchiveLabel')}
  6541. </label>
  6542. </div>
  6543. <button
  6544. type="button"
  6545. onClick={() => setShowDiagnostic(true)}
  6546. disabled={!form.ip_address.trim()}
  6547. 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"
  6548. >
  6549. <Stethoscope className="w-4 h-4" />
  6550. {t('diagnostic.runButton')}
  6551. </button>
  6552. {saveWarning ? (
  6553. <div className="rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3">
  6554. <div className="flex items-start gap-2">
  6555. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400" />
  6556. <p className="text-sm text-amber-300">{t('printers.addPreflight.warning')}</p>
  6557. </div>
  6558. <DiagnosticChecklist result={saveWarning} />
  6559. <div className="flex gap-3">
  6560. <Button
  6561. type="button"
  6562. variant="secondary"
  6563. onClick={() => setSaveWarning(null)}
  6564. className="flex-1"
  6565. >
  6566. {t('printers.addPreflight.back')}
  6567. </Button>
  6568. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  6569. {t('printers.addPreflight.saveAnyway')}
  6570. </Button>
  6571. </div>
  6572. </div>
  6573. ) : (
  6574. <div className="flex gap-3 pt-2">
  6575. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  6576. {t('common.cancel')}
  6577. </Button>
  6578. <Button type="submit" disabled={checkingSave} className="flex-1">
  6579. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  6580. </Button>
  6581. </div>
  6582. )}
  6583. </form>
  6584. </CardContent>
  6585. </Card>
  6586. </div>
  6587. {showDiagnostic && (
  6588. <ConnectionDiagnosticModal
  6589. connection={{
  6590. ip_address: form.ip_address.trim(),
  6591. serial_number: form.serial_number.trim() || undefined,
  6592. access_code: form.access_code || undefined,
  6593. }}
  6594. printerName={form.name || null}
  6595. onClose={() => setShowDiagnostic(false)}
  6596. />
  6597. )}
  6598. </>
  6599. );
  6600. }
  6601. function FirmwareUpdateModal({
  6602. printer,
  6603. firmwareInfo,
  6604. onClose,
  6605. }: {
  6606. printer: Printer;
  6607. firmwareInfo: FirmwareUpdateInfo;
  6608. onClose: () => void;
  6609. }) {
  6610. const { t } = useTranslation();
  6611. const queryClient = useQueryClient();
  6612. const { showToast } = useToast();
  6613. const { hasPermission } = useAuth();
  6614. const canUpdate = hasPermission('firmware:update');
  6615. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  6616. const [isUploading, setIsUploading] = useState(false);
  6617. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  6618. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  6619. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  6620. );
  6621. // Prepare check query — runs when a version is selected and user can update
  6622. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  6623. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  6624. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  6625. staleTime: 30000,
  6626. enabled: !!selectedVersion && canUpdate && !isUploading,
  6627. });
  6628. // Start upload mutation
  6629. const uploadMutation = useMutation({
  6630. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  6631. onSuccess: () => {
  6632. setIsUploading(true);
  6633. // Start polling for status
  6634. const interval = setInterval(async () => {
  6635. try {
  6636. const status = await firmwareApi.getUploadStatus(printer.id);
  6637. setUploadStatus(status);
  6638. if (status.status === 'complete' || status.status === 'error') {
  6639. clearInterval(interval);
  6640. setPollInterval(null);
  6641. setIsUploading(false);
  6642. if (status.status === 'complete') {
  6643. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  6644. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  6645. }
  6646. }
  6647. } catch {
  6648. // Ignore errors during polling
  6649. }
  6650. }, 2000);
  6651. setPollInterval(interval);
  6652. },
  6653. onError: (error: Error) => {
  6654. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  6655. setIsUploading(false);
  6656. },
  6657. });
  6658. // Cleanup on unmount
  6659. useEffect(() => {
  6660. return () => {
  6661. if (pollInterval) clearInterval(pollInterval);
  6662. };
  6663. }, [pollInterval]);
  6664. const handleStartUpload = () => {
  6665. setUploadStatus(null);
  6666. uploadMutation.mutate();
  6667. };
  6668. return (
  6669. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  6670. <Card className="w-full max-w-md mx-4">
  6671. <CardContent>
  6672. <div className="flex items-start gap-3 mb-4">
  6673. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-500/20' : 'bg-status-ok/20'}`}>
  6674. {firmwareInfo.update_available
  6675. ? <Download className="w-5 h-5 text-orange-400" />
  6676. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  6677. </div>
  6678. <div className="flex-1">
  6679. <h3 className="text-lg font-semibold text-white">
  6680. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  6681. </h3>
  6682. <p className="text-sm text-bambu-gray mt-1">
  6683. {printer.name}
  6684. </p>
  6685. </div>
  6686. </div>
  6687. {/* Version Info */}
  6688. {(() => {
  6689. const selectedEntry = selectedVersion
  6690. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  6691. : null;
  6692. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  6693. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  6694. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  6695. return (
  6696. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  6697. <div className="flex justify-between items-center text-sm">
  6698. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  6699. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  6700. {firmwareInfo.current_version || t('common.unknown')}
  6701. </span>
  6702. </div>
  6703. {showSecondLine && (
  6704. <div className="flex justify-between items-center text-sm mt-1">
  6705. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  6706. <span className="text-orange-400 font-mono">{displayVersion}</span>
  6707. </div>
  6708. )}
  6709. {displayNotes && (
  6710. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  6711. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-400' : 'text-status-ok'}`}>
  6712. {t('printers.firmwareModal.releaseNotes')}
  6713. </summary>
  6714. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  6715. {displayNotes}
  6716. </div>
  6717. </details>
  6718. )}
  6719. </div>
  6720. );
  6721. })()}
  6722. {/* Available versions list */}
  6723. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  6724. <div className="mb-4">
  6725. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  6726. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  6727. {firmwareInfo.available_versions.map((v) => {
  6728. const isCurrent = firmwareInfo.current_version === v.version;
  6729. const isSelected = selectedVersion === v.version;
  6730. const cmp = firmwareInfo.current_version
  6731. ? compareFwVersions(v.version, firmwareInfo.current_version)
  6732. : 0;
  6733. const relLabel = isCurrent
  6734. ? t('printers.firmwareModal.currentBadge')
  6735. : cmp > 0
  6736. ? t('printers.firmwareModal.newerBadge')
  6737. : t('printers.firmwareModal.olderBadge');
  6738. const relClass = isCurrent
  6739. ? 'text-bambu-gray'
  6740. : cmp > 0
  6741. ? 'text-orange-400'
  6742. : 'text-blue-400';
  6743. return (
  6744. <button
  6745. key={v.version}
  6746. type="button"
  6747. disabled={!v.file_available || !canUpdate || isCurrent}
  6748. onClick={() => setSelectedVersion(v.version)}
  6749. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  6750. isSelected ? 'bg-orange-500/10' : 'hover:bg-bambu-dark'
  6751. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  6752. >
  6753. <div className="flex items-center gap-2 min-w-0">
  6754. <span className="font-mono text-white">{v.version}</span>
  6755. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  6756. </div>
  6757. <span className={`text-xs px-2 py-0.5 rounded-full ${
  6758. isCurrent
  6759. ? 'bg-blue-500/15 text-blue-400 border border-blue-500/30'
  6760. : v.file_available
  6761. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  6762. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  6763. }`}>
  6764. {isCurrent
  6765. ? t('printers.firmwareModal.installed')
  6766. : v.file_available
  6767. ? t('printers.firmwareModal.usable')
  6768. : t('printers.firmwareModal.unavailable')}
  6769. </span>
  6770. </button>
  6771. );
  6772. })}
  6773. </div>
  6774. </div>
  6775. )}
  6776. {/* Status / Progress (only when a version is selected) */}
  6777. {!selectedVersion ? null : isPreparing ? (
  6778. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  6779. <Loader2 className="w-4 h-4 animate-spin" />
  6780. {t('printers.firmwareModal.checkingPrereqs')}
  6781. </div>
  6782. ) : prepareInfo && !isUploading && !uploadStatus ? (
  6783. <div className="mb-4">
  6784. {prepareInfo.can_proceed ? (
  6785. <div className="flex items-center gap-2 text-bambu-green text-sm">
  6786. <Box className="w-4 h-4" />
  6787. {t('printers.firmwareModal.sdCardReady')}
  6788. </div>
  6789. ) : (
  6790. <div className="space-y-1">
  6791. {prepareInfo.errors.map((error, i) => (
  6792. <div key={i} className="flex items-center gap-2 text-red-400 text-sm">
  6793. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  6794. {error}
  6795. </div>
  6796. ))}
  6797. </div>
  6798. )}
  6799. </div>
  6800. ) : null}
  6801. {/* Upload Progress */}
  6802. {(isUploading || uploadStatus) && uploadStatus && (
  6803. <div className="mb-4">
  6804. <div className="flex items-center justify-between text-sm mb-1">
  6805. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  6806. <span className="text-white">{uploadStatus.progress}%</span>
  6807. </div>
  6808. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  6809. <div
  6810. className={`h-2 rounded-full transition-all ${
  6811. uploadStatus.status === 'error' ? 'bg-status-error' :
  6812. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  6813. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  6814. style={{ width: `${uploadStatus.progress}%` }}
  6815. />
  6816. </div>
  6817. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  6818. {uploadStatus.error && (
  6819. <p className="text-xs text-red-400 mt-1">{uploadStatus.error}</p>
  6820. )}
  6821. </div>
  6822. )}
  6823. {/* Success Message */}
  6824. {uploadStatus?.status === 'complete' && (
  6825. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  6826. <p className="text-sm text-bambu-green font-medium mb-2">
  6827. {t('printers.firmwareModal.uploadedSuccess')}
  6828. </p>
  6829. <p className="text-xs text-bambu-gray">
  6830. {t('printers.firmwareModal.applyInstructions')}
  6831. </p>
  6832. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  6833. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  6834. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  6835. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  6836. <li>{t('printers.firmwareModal.step4')}</li>
  6837. </ol>
  6838. </div>
  6839. )}
  6840. {/* Buttons */}
  6841. <div className="flex gap-2 justify-end">
  6842. <Button variant="secondary" onClick={onClose}>
  6843. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  6844. </Button>
  6845. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  6846. <Button
  6847. onClick={handleStartUpload}
  6848. disabled={uploadMutation.isPending}
  6849. >
  6850. {uploadMutation.isPending ? (
  6851. <>
  6852. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  6853. {t('printers.firmwareModal.starting')}
  6854. </>
  6855. ) : (
  6856. <>
  6857. <Download className="w-4 h-4 mr-2" />
  6858. {t('printers.firmwareModal.uploadFirmware')}
  6859. </>
  6860. )}
  6861. </Button>
  6862. )}
  6863. </div>
  6864. </CardContent>
  6865. </Card>
  6866. </div>
  6867. );
  6868. }
  6869. function EditPrinterModal({
  6870. printer,
  6871. onClose,
  6872. }: {
  6873. printer: Printer;
  6874. onClose: () => void;
  6875. }) {
  6876. const { t } = useTranslation();
  6877. const queryClient = useQueryClient();
  6878. const { showToast } = useToast();
  6879. const [form, setForm] = useState({
  6880. name: printer.name,
  6881. ip_address: printer.ip_address,
  6882. access_code: '',
  6883. model: printer.model || '',
  6884. location: printer.location || '',
  6885. auto_archive: printer.auto_archive,
  6886. is_active: printer.is_active,
  6887. });
  6888. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  6889. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  6890. const [checkingSave, setCheckingSave] = useState(false);
  6891. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6892. const updateMutation = useMutation({
  6893. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  6894. onSuccess: () => {
  6895. queryClient.invalidateQueries({ queryKey: ['printers'] });
  6896. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6897. onClose();
  6898. },
  6899. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  6900. });
  6901. // Close on Escape key
  6902. useEffect(() => {
  6903. const handleKeyDown = (e: KeyboardEvent) => {
  6904. if (e.key === 'Escape') onClose();
  6905. };
  6906. window.addEventListener('keydown', handleKeyDown);
  6907. return () => window.removeEventListener('keydown', handleKeyDown);
  6908. }, [onClose]);
  6909. const doSave = () => {
  6910. const data: Partial<PrinterCreate> = {
  6911. name: form.name,
  6912. ip_address: form.ip_address,
  6913. model: form.model || undefined,
  6914. location: form.location || undefined,
  6915. auto_archive: form.auto_archive,
  6916. is_active: form.is_active,
  6917. };
  6918. // Only include access_code if it was changed
  6919. if (form.access_code) {
  6920. data.access_code = form.access_code;
  6921. }
  6922. updateMutation.mutate(data);
  6923. };
  6924. const handleSubmit = async (e: React.FormEvent) => {
  6925. e.preventDefault();
  6926. setCheckingSave(true);
  6927. try {
  6928. const result = await api.diagnoseConnection({
  6929. ip_address: form.ip_address.trim(),
  6930. serial_number: printer.serial_number,
  6931. access_code: form.access_code || undefined,
  6932. });
  6933. if (result.checks.some((c) => c.status === 'fail')) {
  6934. setSaveWarning(result);
  6935. return;
  6936. }
  6937. } catch {
  6938. // Diagnostic infrastructure failed — never block the save on it.
  6939. } finally {
  6940. setCheckingSave(false);
  6941. }
  6942. doSave();
  6943. };
  6944. return (
  6945. <div
  6946. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6947. onClick={onClose}
  6948. >
  6949. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6950. <CardContent>
  6951. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  6952. <form onSubmit={handleSubmit} className="space-y-4">
  6953. <div>
  6954. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6955. <input
  6956. type="text"
  6957. required
  6958. 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"
  6959. value={form.name}
  6960. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6961. placeholder={t('printers.modal.myPrinter')}
  6962. />
  6963. </div>
  6964. <div>
  6965. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6966. <input
  6967. type="text"
  6968. required
  6969. 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])?)*)"
  6970. 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"
  6971. value={form.ip_address}
  6972. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6973. placeholder="192.168.1.100 or printer.local"
  6974. />
  6975. </div>
  6976. <div>
  6977. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6978. <input
  6979. type="text"
  6980. disabled
  6981. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  6982. value={printer.serial_number}
  6983. />
  6984. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  6985. </div>
  6986. <div>
  6987. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6988. <input
  6989. type="password"
  6990. 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"
  6991. value={form.access_code}
  6992. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6993. placeholder={t('printers.accessCodePlaceholder')}
  6994. />
  6995. </div>
  6996. <div>
  6997. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  6998. <select
  6999. 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"
  7000. value={form.model}
  7001. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7002. >
  7003. <option value="">{t('printers.modal.selectModel')}</option>
  7004. <optgroup label="A1 Series">
  7005. <option value="A1">A1</option>
  7006. <option value="A1 Mini">A1 Mini</option>
  7007. </optgroup>
  7008. <optgroup label="A2 Series">
  7009. <option value="A2L">A2L</option>
  7010. </optgroup>
  7011. <optgroup label="H2 Series">
  7012. <option value="H2C">H2C</option>
  7013. <option value="H2D">H2D</option>
  7014. <option value="H2D Pro">H2D Pro</option>
  7015. <option value="H2S">H2S</option>
  7016. </optgroup>
  7017. <optgroup label="P Series">
  7018. <option value="P1P">P1P</option>
  7019. <option value="P1S">P1S</option>
  7020. <option value="P2S">P2S</option>
  7021. </optgroup>
  7022. <optgroup label="X1 Series">
  7023. <option value="X1">X1</option>
  7024. <option value="X1C">X1 Carbon</option>
  7025. <option value="X1E">X1E</option>
  7026. </optgroup>
  7027. <optgroup label="X2 Series">
  7028. <option value="X2D">X2D</option>
  7029. </optgroup>
  7030. </select>
  7031. </div>
  7032. <div>
  7033. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7034. <input
  7035. type="text"
  7036. 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"
  7037. value={form.location}
  7038. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7039. placeholder={t('printers.modal.locationPlaceholder')}
  7040. />
  7041. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7042. </div>
  7043. <div className="flex items-center gap-2">
  7044. <input
  7045. type="checkbox"
  7046. id="edit_auto_archive"
  7047. checked={form.auto_archive}
  7048. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7049. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7050. />
  7051. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7052. {t('printers.modal.autoArchiveLabel')}
  7053. </label>
  7054. </div>
  7055. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7056. is_active because the user-facing concept is "is this printer
  7057. in maintenance" not "is it active". */}
  7058. <div>
  7059. <div className="flex items-center gap-2">
  7060. <input
  7061. type="checkbox"
  7062. id="edit_maintenance_mode"
  7063. checked={!form.is_active}
  7064. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  7065. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  7066. />
  7067. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  7068. <Wrench className="w-3.5 h-3.5 text-amber-400" />
  7069. {t('printers.maintenance.editFieldLabel')}
  7070. </label>
  7071. </div>
  7072. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  7073. {t('printers.maintenance.editFieldHelp')}
  7074. </p>
  7075. </div>
  7076. {saveWarning ? (
  7077. <div className="rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3">
  7078. <div className="flex items-start gap-2">
  7079. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400" />
  7080. <p className="text-sm text-amber-300">{t('printers.addPreflight.warning')}</p>
  7081. </div>
  7082. <DiagnosticChecklist result={saveWarning} />
  7083. <div className="flex gap-3">
  7084. <Button
  7085. type="button"
  7086. variant="secondary"
  7087. onClick={() => setSaveWarning(null)}
  7088. className="flex-1"
  7089. >
  7090. {t('printers.addPreflight.back')}
  7091. </Button>
  7092. <Button
  7093. type="button"
  7094. onClick={doSave}
  7095. className="flex-1"
  7096. disabled={updateMutation.isPending}
  7097. >
  7098. {t('printers.addPreflight.saveAnyway')}
  7099. </Button>
  7100. </div>
  7101. </div>
  7102. ) : (
  7103. <div className="flex gap-3 pt-4">
  7104. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7105. {t('common.cancel')}
  7106. </Button>
  7107. <Button
  7108. type="submit"
  7109. className="flex-1"
  7110. disabled={updateMutation.isPending || checkingSave}
  7111. >
  7112. {checkingSave
  7113. ? t('printers.addPreflight.checking')
  7114. : updateMutation.isPending
  7115. ? t('common.saving')
  7116. : t('printers.modal.saveChanges')}
  7117. </Button>
  7118. </div>
  7119. )}
  7120. </form>
  7121. </CardContent>
  7122. </Card>
  7123. </div>
  7124. );
  7125. }
  7126. // Component to check if a printer is offline (for power dropdown)
  7127. function usePrinterOfflineStatus(printerId: number) {
  7128. const { data: status } = useQuery({
  7129. queryKey: ['printerStatus', printerId],
  7130. queryFn: () => api.getPrinterStatus(printerId),
  7131. refetchInterval: 30000,
  7132. });
  7133. return !status?.connected;
  7134. }
  7135. // Power dropdown item for an offline printer
  7136. function PowerDropdownItem({
  7137. printer,
  7138. plug,
  7139. onPowerOn,
  7140. isPowering,
  7141. }: {
  7142. printer: Printer;
  7143. plug: { id: number; name: string };
  7144. onPowerOn: (plugId: number) => void;
  7145. isPowering: boolean;
  7146. }) {
  7147. const isOffline = usePrinterOfflineStatus(printer.id);
  7148. // Fetch plug status
  7149. const { data: plugStatus } = useQuery({
  7150. queryKey: ['smartPlugStatus', plug.id],
  7151. queryFn: () => api.getSmartPlugStatus(plug.id),
  7152. refetchInterval: 10000,
  7153. });
  7154. // Only show if printer is offline
  7155. if (!isOffline) {
  7156. return null;
  7157. }
  7158. return (
  7159. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  7160. <div className="flex items-center gap-2 min-w-0">
  7161. <span className="text-sm text-gray-900 dark:text-white truncate">{printer.name}</span>
  7162. {plugStatus && (
  7163. <span
  7164. className={`text-xs px-1.5 py-0.5 rounded ${
  7165. plugStatus.state === 'ON'
  7166. ? 'bg-bambu-green/20 text-bambu-green'
  7167. : 'bg-red-500/20 text-red-400'
  7168. }`}
  7169. >
  7170. {plugStatus.state || '?'}
  7171. </span>
  7172. )}
  7173. </div>
  7174. <button
  7175. onClick={() => onPowerOn(plug.id)}
  7176. disabled={isPowering || plugStatus?.state === 'ON'}
  7177. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  7178. plugStatus?.state === 'ON'
  7179. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  7180. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  7181. }`}
  7182. >
  7183. <Power className="w-3 h-3" />
  7184. {isPowering ? '...' : 'On'}
  7185. </button>
  7186. </div>
  7187. );
  7188. }
  7189. export function PrintersPage() {
  7190. const { t } = useTranslation();
  7191. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  7192. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  7193. const accentButtonClass = {
  7194. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  7195. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  7196. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  7197. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  7198. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  7199. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  7200. }[activeAccent];
  7201. const [showAddModal, setShowAddModal] = useState(false);
  7202. const [hideDisconnected, setHideDisconnected] = useState(() => {
  7203. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  7204. });
  7205. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  7206. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  7207. const [sortBy, setSortBy] = useState<SortOption>(() => {
  7208. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  7209. });
  7210. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  7211. return localStorage.getItem('printerSortAsc') !== 'false';
  7212. });
  7213. // Card size: 1=small, 2=medium, 3=large, 4=xl
  7214. const [cardSize, setCardSize] = useState<number>(() => {
  7215. const saved = localStorage.getItem('printerCardSize');
  7216. return saved ? parseInt(saved, 10) : 2; // Default to medium
  7217. });
  7218. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  7219. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  7220. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  7221. const scrollPrinterIntoView = useCallback((printerId: number) => {
  7222. requestAnimationFrame(() => {
  7223. requestAnimationFrame(() => {
  7224. const card = document.getElementById(`printer-card-${printerId}`);
  7225. if (!card) return;
  7226. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  7227. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  7228. window.scrollTo({
  7229. top: Math.max(0, top),
  7230. behavior: 'smooth',
  7231. });
  7232. });
  7233. });
  7234. }, []);
  7235. const openCompactCard = useCallback((printerId: number) => {
  7236. setCompactDrilldownPrinterId(printerId);
  7237. setCardSize(2);
  7238. localStorage.setItem('printerCardSize', '2');
  7239. scrollPrinterIntoView(printerId);
  7240. }, [scrollPrinterIntoView]);
  7241. const returnToCompactCards = useCallback(() => {
  7242. const printerId = compactDrilldownPrinterId;
  7243. setCompactDrilldownPrinterId(null);
  7244. setCardSize(1);
  7245. localStorage.setItem('printerCardSize', '1');
  7246. if (printerId != null) {
  7247. scrollPrinterIntoView(printerId);
  7248. }
  7249. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  7250. const [search, setSearch] = useState('');
  7251. const [statusFilter, setStatusFilter] = useState<string>('all');
  7252. const [locationFilter, setLocationFilter] = useState<string>('all');
  7253. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  7254. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  7255. try {
  7256. const saved = localStorage.getItem('printerCollapsedSections');
  7257. return saved ? JSON.parse(saved) : {};
  7258. } catch { return {}; }
  7259. });
  7260. const queryClient = useQueryClient();
  7261. const { showToast } = useToast();
  7262. const { hasPermission } = useAuth();
  7263. // Embedded camera viewer state - supports multiple simultaneous viewers
  7264. // Persisted to localStorage so cameras reopen after navigation
  7265. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  7266. // Initialize from localStorage if camera_view_mode is embedded
  7267. const saved = localStorage.getItem('openEmbeddedCameras');
  7268. if (saved) {
  7269. try {
  7270. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  7271. return new Map(cameras.map(c => [c.id, c]));
  7272. } catch {
  7273. return new Map();
  7274. }
  7275. }
  7276. return new Map();
  7277. });
  7278. // Persist open cameras to localStorage when they change
  7279. useEffect(() => {
  7280. const cameras = Array.from(embeddedCameraPrinters.values());
  7281. if (cameras.length > 0) {
  7282. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  7283. } else {
  7284. localStorage.removeItem('openEmbeddedCameras');
  7285. }
  7286. }, [embeddedCameraPrinters]);
  7287. const { data: printers, isLoading } = useQuery({
  7288. queryKey: ['printers'],
  7289. queryFn: api.getPrinters,
  7290. });
  7291. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  7292. // so users with printers:read but no settings:read still get the values needed
  7293. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  7294. const { data: settings } = useQuery({
  7295. queryKey: ['ui-preferences'],
  7296. queryFn: api.getUiPreferences,
  7297. });
  7298. // Parse user-configured temperature/fan presets once, with defensive fallback
  7299. // to built-in defaults on parse failure (validators on the backend already
  7300. // reject malformed writes, so this is just forward-compat).
  7301. const effectiveNozzleTempPresets = useMemo(
  7302. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  7303. [settings?.nozzle_temp_presets],
  7304. );
  7305. const effectiveBedTempPresets = useMemo(
  7306. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  7307. [settings?.bed_temp_presets],
  7308. );
  7309. const effectiveChamberTempPresets = useMemo(
  7310. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, 60),
  7311. [settings?.chamber_temp_presets],
  7312. );
  7313. const effectiveFanSpeedPresets = useMemo(
  7314. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  7315. [settings?.fan_speed_presets],
  7316. );
  7317. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  7318. const effectiveDryingPresets = useMemo(() => {
  7319. if (settings?.drying_presets) {
  7320. try {
  7321. const userPresets = JSON.parse(settings.drying_presets);
  7322. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  7323. return { ...DRYING_PRESETS, ...userPresets };
  7324. }
  7325. } catch { /* ignore parse errors, use defaults */ }
  7326. }
  7327. return DRYING_PRESETS;
  7328. }, [settings?.drying_presets]);
  7329. // Close embedded cameras if mode changes to 'window'
  7330. useEffect(() => {
  7331. if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
  7332. setEmbeddedCameraPrinters(new Map());
  7333. }
  7334. }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
  7335. // Fetch all smart plugs to know which printers have them
  7336. const { data: smartPlugs } = useQuery({
  7337. queryKey: ['smart-plugs'],
  7338. queryFn: api.getSmartPlugs,
  7339. });
  7340. // Fetch maintenance overview for all printers to show badges
  7341. const { data: maintenanceOverview } = useQuery({
  7342. queryKey: ['maintenanceOverview'],
  7343. queryFn: api.getMaintenanceOverview,
  7344. staleTime: 60 * 1000, // 1 minute
  7345. });
  7346. // Fetch Spoolman status to enable link spool feature
  7347. const { data: spoolmanStatus } = useQuery({
  7348. queryKey: ['spoolman-status'],
  7349. queryFn: api.getSpoolmanStatus,
  7350. staleTime: 60 * 1000, // 1 minute
  7351. });
  7352. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  7353. // Fetch Spoolman settings to get sync mode
  7354. const { data: spoolmanSettings } = useQuery({
  7355. queryKey: ['spoolman-settings'],
  7356. queryFn: api.getSpoolmanSettings,
  7357. enabled: !!spoolmanEnabled,
  7358. staleTime: 60 * 1000, // 1 minute
  7359. });
  7360. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  7361. // Fetch unlinked spools to know if link button should be enabled
  7362. const { data: unlinkedSpools } = useQuery({
  7363. queryKey: ['unlinked-spools'],
  7364. queryFn: api.getUnlinkedSpools,
  7365. enabled: !!spoolmanEnabled,
  7366. staleTime: 30 * 1000, // 30 seconds
  7367. });
  7368. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  7369. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  7370. const { data: linkedSpoolsData } = useQuery({
  7371. queryKey: ['linked-spools'],
  7372. queryFn: api.getLinkedSpools,
  7373. enabled: !!spoolmanEnabled,
  7374. staleTime: 30 * 1000, // 30 seconds
  7375. });
  7376. const linkedSpools = linkedSpoolsData?.linked;
  7377. // Fetch spool assignments for inventory feature
  7378. const { data: spoolAssignments } = useQuery({
  7379. queryKey: ['spool-assignments'],
  7380. queryFn: () => api.getAssignments(),
  7381. enabled: hasPermission('inventory:view_assignments'),
  7382. staleTime: 30 * 1000,
  7383. });
  7384. const unassignMutation = useMutation({
  7385. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  7386. api.unassignSpool(printerId, amsId, trayId),
  7387. onSuccess: () => {
  7388. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  7389. },
  7390. });
  7391. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  7392. queryKey: ['spoolman-inventory-spools'],
  7393. queryFn: () => api.getSpoolmanInventorySpools(false),
  7394. enabled: !!spoolmanEnabled,
  7395. staleTime: 30 * 1000,
  7396. });
  7397. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  7398. queryKey: ['spoolman-slot-assignments'],
  7399. queryFn: () => api.getSpoolmanSlotAssignments(),
  7400. enabled: !!spoolmanEnabled,
  7401. staleTime: 30 * 1000,
  7402. });
  7403. const unassignSpoolmanMutation = useMutation({
  7404. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  7405. onSuccess: () => {
  7406. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  7407. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  7408. },
  7409. });
  7410. // Helper to find assignment for a specific slot
  7411. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  7412. return spoolAssignments?.find(
  7413. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  7414. );
  7415. };
  7416. // Create a map of printer_id -> maintenance info for quick lookup
  7417. const maintenanceByPrinter = maintenanceOverview?.reduce(
  7418. (acc, overview) => {
  7419. acc[overview.printer_id] = {
  7420. due_count: overview.due_count,
  7421. warning_count: overview.warning_count,
  7422. total_print_hours: overview.total_print_hours,
  7423. };
  7424. return acc;
  7425. },
  7426. {} as Record<number, PrinterMaintenanceInfo>
  7427. ) || {};
  7428. // Create a map of printer_id -> smart plug
  7429. const smartPlugByPrinter = smartPlugs?.reduce(
  7430. (acc, plug) => {
  7431. if (plug.printer_id) {
  7432. acc[plug.printer_id] = plug;
  7433. }
  7434. return acc;
  7435. },
  7436. {} as Record<number, typeof smartPlugs[0]>
  7437. ) || {};
  7438. const addMutation = useMutation({
  7439. mutationFn: api.createPrinter,
  7440. onSuccess: () => {
  7441. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7442. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  7443. setShowAddModal(false);
  7444. },
  7445. onError: (error: Error) => {
  7446. // Localized message when the backend returns a stable error code;
  7447. // the raw message is an English fallback for non-UI clients.
  7448. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  7449. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  7450. return;
  7451. }
  7452. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  7453. },
  7454. });
  7455. const powerOnMutation = useMutation({
  7456. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  7457. onSuccess: () => {
  7458. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  7459. setPoweringOn(null);
  7460. },
  7461. onError: () => {
  7462. setPoweringOn(null);
  7463. },
  7464. });
  7465. // Bulk selection state
  7466. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  7467. const [isSelectionMode, setIsSelectionMode] = useState(false);
  7468. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  7469. const [bulkActionPending, setBulkActionPending] = useState(false);
  7470. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  7471. const toggleSelect = useCallback((id: number) => {
  7472. setSelectedPrinterIds(prev => {
  7473. const next = new Set(prev);
  7474. if (next.has(id)) next.delete(id);
  7475. else next.add(id);
  7476. return next;
  7477. });
  7478. }, []);
  7479. const clearSelection = useCallback(() => {
  7480. setSelectedPrinterIds(new Set());
  7481. setIsSelectionMode(false);
  7482. }, []);
  7483. // Escape key exits selection mode
  7484. useEffect(() => {
  7485. const handleKeyDown = (e: KeyboardEvent) => {
  7486. if (e.key === 'Escape' && selectionMode) {
  7487. clearSelection();
  7488. }
  7489. };
  7490. window.addEventListener('keydown', handleKeyDown);
  7491. return () => window.removeEventListener('keydown', handleKeyDown);
  7492. }, [selectionMode, clearSelection]);
  7493. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7494. setBulkActionPending(true);
  7495. const ids = Array.from(selectedPrinterIds);
  7496. // Filter to only applicable printers based on cached state
  7497. const applicableIds = ids.filter(id => {
  7498. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  7499. if (!status?.connected) return false;
  7500. switch (action) {
  7501. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  7502. case 'pause': return status.state === 'RUNNING';
  7503. case 'resume': return status.state === 'PAUSE';
  7504. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  7505. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  7506. default: return false;
  7507. }
  7508. });
  7509. if (applicableIds.length === 0) {
  7510. showToast(t('printers.bulk.noneApplicable'), 'error');
  7511. setBulkActionPending(false);
  7512. setBulkConfirmAction(null);
  7513. return;
  7514. }
  7515. const apiCall = {
  7516. stop: api.stopPrint,
  7517. pause: api.pausePrint,
  7518. resume: api.resumePrint,
  7519. clearPlate: api.clearPlate,
  7520. clearHMS: api.clearHMSErrors,
  7521. }[action];
  7522. const results = await Promise.allSettled(
  7523. applicableIds.map(id => apiCall(id))
  7524. );
  7525. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  7526. const failed = results.filter(r => r.status === 'rejected').length;
  7527. if (failed === 0) {
  7528. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  7529. } else {
  7530. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  7531. }
  7532. // Invalidate status queries for affected printers
  7533. applicableIds.forEach(id => {
  7534. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  7535. });
  7536. setBulkActionPending(false);
  7537. setBulkConfirmAction(null);
  7538. }, [selectedPrinterIds, queryClient, showToast, t]);
  7539. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7540. // Actions that need confirmation
  7541. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  7542. setBulkConfirmAction(action);
  7543. } else {
  7544. executeBulkAction(action);
  7545. }
  7546. }, [executeBulkAction]);
  7547. const toggleHideDisconnected = () => {
  7548. const newValue = !hideDisconnected;
  7549. setHideDisconnected(newValue);
  7550. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  7551. };
  7552. const handleSortChange = (newSort: SortOption) => {
  7553. setSortBy(newSort);
  7554. localStorage.setItem('printerSortBy', newSort);
  7555. };
  7556. const toggleSortDirection = () => {
  7557. const newAsc = !sortAsc;
  7558. setSortAsc(newAsc);
  7559. localStorage.setItem('printerSortAsc', String(newAsc));
  7560. };
  7561. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  7562. const getGridClasses = () => {
  7563. switch (cardSize) {
  7564. 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
  7565. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  7566. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  7567. case 4: return 'grid-cols-1'; // XL: single column, full width
  7568. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  7569. }
  7570. };
  7571. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  7572. // Increment version counter whenever a printer status cache entry is updated so
  7573. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  7574. useEffect(() => {
  7575. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  7576. if (
  7577. event.type === 'updated' &&
  7578. Array.isArray(event.query.queryKey) &&
  7579. event.query.queryKey[0] === 'printerStatus'
  7580. ) {
  7581. setStatusCacheVersion(v => v + 1);
  7582. }
  7583. });
  7584. return unsubscribe;
  7585. }, [queryClient]);
  7586. // Filter printers by search term, status, and location
  7587. const filteredPrinters = useMemo(() => {
  7588. if (!printers) return [];
  7589. let result = printers;
  7590. // Text search
  7591. if (search.trim()) {
  7592. const q = search.trim().toLowerCase();
  7593. result = result.filter(p =>
  7594. p.name.toLowerCase().includes(q) ||
  7595. (p.model || '').toLowerCase().includes(q) ||
  7596. (p.location || '').toLowerCase().includes(q) ||
  7597. (p.serial_number || '').toLowerCase().includes(q)
  7598. );
  7599. }
  7600. // Location filter
  7601. if (locationFilter !== 'all') {
  7602. result = result.filter(p => (p.location || '') === locationFilter);
  7603. }
  7604. // Status filter
  7605. if (statusFilter !== 'all') {
  7606. result = result.filter(p => {
  7607. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7608. if (!status?.connected) return statusFilter === 'offline';
  7609. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  7610. switch (statusFilter) {
  7611. case 'printing': return status.state === 'RUNNING';
  7612. case 'paused': return status.state === 'PAUSE';
  7613. case 'finished': return status.state === 'FINISH';
  7614. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  7615. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  7616. case 'offline': return false; // Connected printers are never offline
  7617. default: return true;
  7618. }
  7619. });
  7620. }
  7621. return result;
  7622. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  7623. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  7624. // Derive unique locations for the location filter dropdown
  7625. const availableLocations = useMemo(() => {
  7626. if (!printers) return [];
  7627. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  7628. }, [printers]);
  7629. // Sort printers based on selected option
  7630. const sortedPrinters = useMemo(() => {
  7631. const sorted = [...filteredPrinters];
  7632. switch (sortBy) {
  7633. case 'name':
  7634. sorted.sort((a, b) => a.name.localeCompare(b.name));
  7635. break;
  7636. case 'model':
  7637. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  7638. break;
  7639. case 'location':
  7640. // Sort by location, with ungrouped printers last
  7641. sorted.sort((a, b) => {
  7642. const locA = a.location || '';
  7643. const locB = b.location || '';
  7644. if (!locA && locB) return 1;
  7645. if (locA && !locB) return -1;
  7646. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  7647. });
  7648. break;
  7649. case 'status':
  7650. // Sort by status: HMS errors > printing > idle > offline
  7651. sorted.sort((a, b) => {
  7652. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  7653. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  7654. const getPriority = (s: typeof statusA) => {
  7655. if (!s?.connected) return 3; // offline
  7656. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  7657. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  7658. if (s.state === 'RUNNING') return 1; // printing
  7659. return 2; // idle
  7660. };
  7661. return getPriority(statusA) - getPriority(statusB);
  7662. });
  7663. break;
  7664. case 'eta':
  7665. sorted.sort((a, b) => {
  7666. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  7667. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  7668. const tier = (s: typeof statusA) => {
  7669. if (!s?.connected) return 3; // offline last
  7670. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  7671. if (s.state === 'RUNNING') return 1; // printing without ETA
  7672. return 2; // idle
  7673. };
  7674. const ta = tier(statusA);
  7675. const tb = tier(statusB);
  7676. if (ta !== tb) return ta - tb;
  7677. if (ta === 0) {
  7678. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  7679. if (diff !== 0) return diff;
  7680. }
  7681. return a.name.localeCompare(b.name);
  7682. });
  7683. break;
  7684. }
  7685. // Apply ascending/descending
  7686. if (!sortAsc) {
  7687. sorted.reverse();
  7688. }
  7689. return sorted;
  7690. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  7691. const selectAll = useCallback(() => {
  7692. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  7693. setIsSelectionMode(true);
  7694. }, [sortedPrinters]);
  7695. const selectByState = useCallback((state: PrinterState) => {
  7696. setSelectedPrinterIds(prev => {
  7697. const next = new Set(prev);
  7698. sortedPrinters.forEach(p => {
  7699. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7700. if (classifyPrinterStatus(status) === state) next.add(p.id);
  7701. });
  7702. return next;
  7703. });
  7704. setIsSelectionMode(true);
  7705. }, [sortedPrinters, queryClient]);
  7706. const selectByLocation = useCallback((location: string) => {
  7707. setSelectedPrinterIds(prev => {
  7708. const next = new Set(prev);
  7709. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  7710. return next;
  7711. });
  7712. setIsSelectionMode(true);
  7713. }, [sortedPrinters]);
  7714. const selectByModel = useCallback((model: string) => {
  7715. setSelectedPrinterIds(prev => {
  7716. const next = new Set(prev);
  7717. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  7718. return next;
  7719. });
  7720. setIsSelectionMode(true);
  7721. }, [sortedPrinters]);
  7722. const toggleSectionCollapse = useCallback((key: string) => {
  7723. setCollapsedSections(prev => {
  7724. const next = { ...prev, [key]: !prev[key] };
  7725. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  7726. return next;
  7727. });
  7728. }, []);
  7729. // Group printers when sorted by location, status, or model
  7730. const groupedPrinters = useMemo(() => {
  7731. if (sortBy === 'name' || sortBy === 'eta') return null;
  7732. const groups: Record<string, typeof sortedPrinters> = {};
  7733. if (sortBy === 'location') {
  7734. sortedPrinters.forEach(printer => {
  7735. const location = printer.location || 'Ungrouped';
  7736. if (!groups[location]) groups[location] = [];
  7737. groups[location].push(printer);
  7738. });
  7739. } else if (sortBy === 'model') {
  7740. sortedPrinters.forEach(printer => {
  7741. const model = printer.model || 'Unknown';
  7742. if (!groups[model]) groups[model] = [];
  7743. groups[model].push(printer);
  7744. });
  7745. } else if (sortBy === 'status') {
  7746. sortedPrinters.forEach(printer => {
  7747. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  7748. const group = classifyPrinterStatus(status);
  7749. if (!groups[group]) groups[group] = [];
  7750. groups[group].push(printer);
  7751. });
  7752. }
  7753. return groups;
  7754. // 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
  7755. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  7756. const toolbarRef = useRef<HTMLDivElement>(null);
  7757. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  7758. const expandedToolbarWidthRef = useRef(0);
  7759. const [compactToolbar, setCompactToolbar] = useState(false);
  7760. const measureToolbar = useCallback(() => {
  7761. const toolbar = toolbarRef.current;
  7762. if (!toolbar) return;
  7763. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  7764. if (measuredControlsWidth) {
  7765. expandedToolbarWidthRef.current = measuredControlsWidth;
  7766. }
  7767. const searchMinimumWidth = 220;
  7768. const gapWidth = 8;
  7769. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  7770. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  7771. }, []);
  7772. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  7773. useLayoutEffect(() => {
  7774. measureToolbar();
  7775. const toolbar = toolbarRef.current;
  7776. if (!toolbar) return;
  7777. if (typeof ResizeObserver === 'undefined') {
  7778. window.addEventListener('resize', measureToolbar);
  7779. return () => window.removeEventListener('resize', measureToolbar);
  7780. }
  7781. const resizeObserver = new ResizeObserver(() => measureToolbar());
  7782. resizeObserver.observe(toolbar);
  7783. window.addEventListener('resize', measureToolbar);
  7784. return () => {
  7785. resizeObserver.disconnect();
  7786. window.removeEventListener('resize', measureToolbar);
  7787. };
  7788. }, [
  7789. measureToolbar,
  7790. printers?.length,
  7791. availableLocations.length,
  7792. hideDisconnected,
  7793. smartPlugCount,
  7794. ]);
  7795. const renderFilterControls = (inMenu = false) => (
  7796. <>
  7797. {/* Status filter */}
  7798. {printers && printers.length > 0 && (
  7799. <ToolbarDropdown
  7800. value={statusFilter}
  7801. onChange={setStatusFilter}
  7802. fullWidth={inMenu}
  7803. options={[
  7804. { value: 'all', label: t('printers.filter.allStatuses') },
  7805. { value: 'printing', label: t('printers.status.printing') },
  7806. { value: 'paused', label: t('printers.status.paused') },
  7807. { value: 'idle', label: t('printers.status.idle') },
  7808. { value: 'finished', label: t('printers.status.finished') },
  7809. { value: 'error', label: t('printers.status.error') },
  7810. { value: 'offline', label: t('printers.status.offline') },
  7811. ]}
  7812. />
  7813. )}
  7814. {/* Location filter — only shown when at least one printer has a location */}
  7815. {printers && printers.length > 0 && availableLocations.length > 0 && (
  7816. <ToolbarDropdown
  7817. value={locationFilter}
  7818. onChange={setLocationFilter}
  7819. fullWidth={inMenu}
  7820. options={[
  7821. { value: 'all', label: t('printers.filter.allLocations') },
  7822. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  7823. ]}
  7824. />
  7825. )}
  7826. <button
  7827. type="button"
  7828. onClick={toggleHideDisconnected}
  7829. aria-pressed={hideDisconnected}
  7830. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  7831. hideDisconnected
  7832. ? 'bg-bambu-green border-bambu-green text-white'
  7833. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7834. }`}
  7835. >
  7836. {t('printers.hideOffline')}
  7837. </button>
  7838. </>
  7839. );
  7840. const renderViewControls = (inMenu = false) => (
  7841. <>
  7842. {/* Sort dropdown */}
  7843. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  7844. <ToolbarDropdown<SortOption>
  7845. value={sortBy}
  7846. onChange={handleSortChange}
  7847. fullWidth={inMenu}
  7848. options={[
  7849. { value: 'name', label: t('printers.sort.name') },
  7850. { value: 'status', label: t('printers.sort.status') },
  7851. { value: 'model', label: t('printers.sort.model') },
  7852. { value: 'location', label: t('printers.sort.location') },
  7853. { value: 'eta', label: t('printers.sort.eta') },
  7854. ]}
  7855. />
  7856. <button
  7857. onClick={toggleSortDirection}
  7858. 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"
  7859. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  7860. >
  7861. {sortAsc ? (
  7862. <ArrowUp className="w-4 h-4 text-white" />
  7863. ) : (
  7864. <ArrowDown className="w-4 h-4 text-white" />
  7865. )}
  7866. </button>
  7867. </div>
  7868. {/* Card size selector */}
  7869. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  7870. {cardSizeLabels.map((label, index) => {
  7871. const size = index + 1;
  7872. const isSelected = cardSize === size;
  7873. return (
  7874. <button
  7875. key={label}
  7876. onClick={() => {
  7877. setCompactDrilldownPrinterId(null);
  7878. setCardSize(size);
  7879. localStorage.setItem('printerCardSize', String(size));
  7880. }}
  7881. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  7882. index === 0 ? 'rounded-l-lg' : ''
  7883. } ${
  7884. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  7885. } ${
  7886. isSelected
  7887. ? 'bg-bambu-green text-white'
  7888. : 'text-white hover:bg-bambu-dark-tertiary'
  7889. }`}
  7890. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  7891. >
  7892. {label}
  7893. </button>
  7894. );
  7895. })}
  7896. </div>
  7897. </>
  7898. );
  7899. const renderActionControls = (inMenu = false) => (
  7900. <>
  7901. {/* Bulk select toggle */}
  7902. <button
  7903. onClick={() => {
  7904. if (selectionMode) clearSelection();
  7905. else setIsSelectionMode(true);
  7906. }}
  7907. 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' : ''} ${
  7908. selectionMode
  7909. ? 'bg-bambu-green border-bambu-green text-white'
  7910. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7911. }`}
  7912. title={t('printers.bulk.select')}
  7913. disabled={!hasPermission('printers:control')}
  7914. >
  7915. <CheckSquare className="w-4 h-4" />
  7916. {inMenu && <span>{t('printers.bulk.select')}</span>}
  7917. </button>
  7918. {/* Power dropdown for offline printers with smart plugs */}
  7919. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  7920. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  7921. <button
  7922. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  7923. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  7924. inMenu
  7925. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  7926. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7927. }`}
  7928. >
  7929. <span className="flex items-center gap-1.5">
  7930. <Power className="w-4 h-4" />
  7931. {t('printers.powerOn')}
  7932. </span>
  7933. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  7934. </button>
  7935. {showPowerDropdown && (
  7936. <>
  7937. {/* Backdrop to close dropdown */}
  7938. <div
  7939. className="fixed inset-0 z-10"
  7940. onClick={() => setShowPowerDropdown(false)}
  7941. />
  7942. <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">
  7943. <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">
  7944. {t('printers.offlinePrintersWithPlugs')}
  7945. </div>
  7946. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  7947. <PowerDropdownItem
  7948. key={printer.id}
  7949. printer={printer}
  7950. plug={smartPlugByPrinter[printer.id]}
  7951. onPowerOn={(plugId) => {
  7952. setPoweringOn(plugId);
  7953. powerOnMutation.mutate(plugId);
  7954. }}
  7955. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  7956. />
  7957. ))}
  7958. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  7959. <div className="px-3 py-2 text-sm text-bambu-gray">
  7960. No printers with smart plugs
  7961. </div>
  7962. )}
  7963. </div>
  7964. </>
  7965. )}
  7966. </div>
  7967. )}
  7968. <Button
  7969. onClick={() => setShowAddModal(true)}
  7970. disabled={!hasPermission('printers:create')}
  7971. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  7972. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  7973. >
  7974. <Plus className="w-4 h-4" />
  7975. {t('printers.addPrinter')}
  7976. </Button>
  7977. </>
  7978. );
  7979. return (
  7980. <div className="p-4 md:p-8">
  7981. <div className="space-y-3 mb-6">
  7982. <div>
  7983. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  7984. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  7985. {t('printers.title')}
  7986. </h1>
  7987. <StatusSummaryBar printers={printers} />
  7988. </div>
  7989. <div ref={toolbarRef} className="relative flex items-center gap-2">
  7990. {/* Only show search bar when printers exist */}
  7991. {printers && printers.length > 0 && (
  7992. <div className="relative min-w-0 flex-1">
  7993. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  7994. <input
  7995. type="search"
  7996. name="printer-search"
  7997. autoComplete="off"
  7998. data-1p-ignore
  7999. data-lpignore="true"
  8000. value={search}
  8001. onChange={(e) => setSearch(e.target.value)}
  8002. placeholder={t('printers.search')}
  8003. aria-label={t('printers.search')}
  8004. 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"
  8005. />
  8006. {search && (
  8007. <button
  8008. type="button"
  8009. aria-label={t('common.clear')}
  8010. onClick={() => setSearch('')}
  8011. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  8012. >
  8013. <X className="w-4 h-4" />
  8014. </button>
  8015. )}
  8016. </div>
  8017. )}
  8018. <div
  8019. ref={expandedToolbarControlsRef}
  8020. aria-hidden={compactToolbar}
  8021. inert={compactToolbar}
  8022. 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`}
  8023. >
  8024. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8025. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  8026. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8027. <div className="flex items-center gap-2">{renderViewControls()}</div>
  8028. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8029. <div className="flex items-center gap-2">{renderActionControls()}</div>
  8030. </div>
  8031. {compactToolbar && (
  8032. <div className="ml-auto flex items-center justify-end gap-1">
  8033. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  8034. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  8035. </ToolbarMenu>
  8036. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  8037. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  8038. </ToolbarMenu>
  8039. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  8040. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  8041. </ToolbarMenu>
  8042. </div>
  8043. )}
  8044. </div>
  8045. </div>
  8046. {isLoading ? (
  8047. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  8048. ) : printers?.length === 0 ? (
  8049. <Card>
  8050. <CardContent className="text-center py-12">
  8051. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  8052. <Button
  8053. onClick={() => setShowAddModal(true)}
  8054. disabled={!hasPermission('printers:create')}
  8055. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8056. >
  8057. <Plus className="w-4 h-4" />
  8058. {t('printers.addPrinter')}
  8059. </Button>
  8060. </CardContent>
  8061. </Card>
  8062. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  8063. <Card>
  8064. <CardContent className="text-center py-12">
  8065. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  8066. </CardContent>
  8067. </Card>
  8068. ) : groupedPrinters ? (
  8069. /* Grouped view (location, status, or model) */
  8070. <div className="space-y-6">
  8071. {(() => {
  8072. const keys = sortBy === 'status'
  8073. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  8074. : Object.keys(groupedPrinters);
  8075. // For status grouping, asc/desc flips the fixed priority order
  8076. // (asc = error→offline, desc = offline→error). This matches the
  8077. // sort-toggle behaviour for other groupings.
  8078. return (sortAsc ? keys : [...keys].reverse());
  8079. })().map((groupKey) => {
  8080. const groupPrinters = groupedPrinters[groupKey];
  8081. const collapseKey = `${sortBy}:${groupKey}`;
  8082. const isOpen = !collapsedSections[collapseKey];
  8083. const dot = sortBy === 'status'
  8084. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  8085. : 'bg-bambu-green';
  8086. const label = sortBy === 'status'
  8087. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  8088. : groupKey;
  8089. return (
  8090. <Collapsible
  8091. key={groupKey}
  8092. open={isOpen}
  8093. onToggle={() => toggleSectionCollapse(collapseKey)}
  8094. summaryClassName="py-1"
  8095. summary={
  8096. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  8097. <span className={`w-2 h-2 rounded-full ${dot}`} />
  8098. {label}
  8099. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  8100. {selectionMode && (
  8101. <button
  8102. onClick={(e) => {
  8103. e.stopPropagation();
  8104. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  8105. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  8106. else if (sortBy === 'model') selectByModel(groupKey);
  8107. }}
  8108. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  8109. >
  8110. {t('printers.bulk.selectAll')}
  8111. </button>
  8112. )}
  8113. </h2>
  8114. }
  8115. >
  8116. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8117. {groupPrinters.map((printer) => (
  8118. <PrinterCard
  8119. key={printer.id}
  8120. printer={printer}
  8121. hideIfDisconnected={hideDisconnected}
  8122. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8123. viewMode={viewMode}
  8124. cardSize={cardSize}
  8125. amsThresholds={settings ? {
  8126. humidityGood: Number(settings.ams_humidity_good) || 40,
  8127. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8128. tempGood: Number(settings.ams_temp_good) || 28,
  8129. tempFair: Number(settings.ams_temp_fair) || 35,
  8130. } : undefined}
  8131. spoolmanEnabled={spoolmanEnabled}
  8132. hasUnlinkedSpools={hasUnlinkedSpools}
  8133. linkedSpools={linkedSpools}
  8134. spoolmanUrl={spoolmanStatus?.url}
  8135. spoolmanSyncMode={spoolmanSyncMode}
  8136. onGetAssignment={getAssignment}
  8137. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8138. spoolmanSpools={spoolmanSpools}
  8139. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8140. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8141. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8142. timeFormat={settings?.time_format || 'system'}
  8143. cameraViewMode={settings?.camera_view_mode || 'window'}
  8144. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8145. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8146. dryingPresets={effectiveDryingPresets}
  8147. nozzleTempPresets={effectiveNozzleTempPresets}
  8148. bedTempPresets={effectiveBedTempPresets}
  8149. chamberTempPresets={effectiveChamberTempPresets}
  8150. fanSpeedPresets={effectiveFanSpeedPresets}
  8151. requirePlateClear={settings?.require_plate_clear === true}
  8152. selectionMode={selectionMode}
  8153. isSelected={selectedPrinterIds.has(printer.id)}
  8154. onToggleSelect={toggleSelect}
  8155. onOpenCompactCard={openCompactCard}
  8156. />
  8157. ))}
  8158. </div>
  8159. </Collapsible>
  8160. );
  8161. })}
  8162. </div>
  8163. ) : (
  8164. /* Regular grid view */
  8165. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8166. {sortedPrinters.map((printer) => (
  8167. <PrinterCard
  8168. key={printer.id}
  8169. printer={printer}
  8170. hideIfDisconnected={hideDisconnected}
  8171. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8172. viewMode={viewMode}
  8173. cardSize={cardSize}
  8174. spoolmanEnabled={spoolmanEnabled}
  8175. hasUnlinkedSpools={hasUnlinkedSpools}
  8176. linkedSpools={linkedSpools}
  8177. spoolmanUrl={spoolmanStatus?.url}
  8178. spoolmanSyncMode={spoolmanSyncMode}
  8179. onGetAssignment={getAssignment}
  8180. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8181. spoolmanSpools={spoolmanSpools}
  8182. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8183. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8184. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8185. amsThresholds={settings ? {
  8186. humidityGood: Number(settings.ams_humidity_good) || 40,
  8187. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8188. tempGood: Number(settings.ams_temp_good) || 28,
  8189. tempFair: Number(settings.ams_temp_fair) || 35,
  8190. } : undefined}
  8191. timeFormat={settings?.time_format || 'system'}
  8192. cameraViewMode={settings?.camera_view_mode || 'window'}
  8193. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8194. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8195. dryingPresets={effectiveDryingPresets}
  8196. nozzleTempPresets={effectiveNozzleTempPresets}
  8197. bedTempPresets={effectiveBedTempPresets}
  8198. chamberTempPresets={effectiveChamberTempPresets}
  8199. fanSpeedPresets={effectiveFanSpeedPresets}
  8200. requirePlateClear={settings?.require_plate_clear === true}
  8201. selectionMode={selectionMode}
  8202. isSelected={selectedPrinterIds.has(printer.id)}
  8203. onToggleSelect={toggleSelect}
  8204. onOpenCompactCard={openCompactCard}
  8205. />
  8206. ))}
  8207. </div>
  8208. )}
  8209. {cardSize === 2 && compactDrilldownPrinterId != null && (
  8210. <button
  8211. type="button"
  8212. onClick={returnToCompactCards}
  8213. 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}`}
  8214. title={t('common.back', 'Back')}
  8215. >
  8216. <ArrowLeft className="w-4 h-4" />
  8217. {t('common.back', 'Back')}
  8218. </button>
  8219. )}
  8220. {showAddModal && (
  8221. <AddPrinterModal
  8222. onClose={() => setShowAddModal(false)}
  8223. onAdd={(data) => addMutation.mutate(data)}
  8224. existingSerials={printers?.map(p => p.serial_number) || []}
  8225. />
  8226. )}
  8227. {/* Bulk selection toolbar */}
  8228. {selectionMode && printers && (
  8229. <BulkPrinterToolbar
  8230. selectedIds={selectedPrinterIds}
  8231. printers={printers}
  8232. onClose={clearSelection}
  8233. onSelectAll={selectAll}
  8234. onSelectByLocation={selectByLocation}
  8235. onSelectByState={selectByState}
  8236. onAction={handleBulkAction}
  8237. actionPending={bulkActionPending}
  8238. />
  8239. )}
  8240. {/* Bulk action confirmation modals */}
  8241. {bulkConfirmAction === 'stop' && (
  8242. <ConfirmModal
  8243. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  8244. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  8245. confirmText={t('printers.bulk.confirm.stopButton')}
  8246. variant="danger"
  8247. isLoading={bulkActionPending}
  8248. onConfirm={() => executeBulkAction('stop')}
  8249. onCancel={() => setBulkConfirmAction(null)}
  8250. />
  8251. )}
  8252. {bulkConfirmAction === 'pause' && (
  8253. <ConfirmModal
  8254. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  8255. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  8256. confirmText={t('printers.bulk.confirm.pauseButton')}
  8257. isLoading={bulkActionPending}
  8258. onConfirm={() => executeBulkAction('pause')}
  8259. onCancel={() => setBulkConfirmAction(null)}
  8260. />
  8261. )}
  8262. {bulkConfirmAction === 'clearPlate' && (
  8263. <ConfirmModal
  8264. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  8265. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  8266. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  8267. isLoading={bulkActionPending}
  8268. onConfirm={() => executeBulkAction('clearPlate')}
  8269. onCancel={() => setBulkConfirmAction(null)}
  8270. />
  8271. )}
  8272. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  8273. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  8274. <EmbeddedCameraViewer
  8275. key={camera.id}
  8276. printerId={camera.id}
  8277. printerName={camera.name}
  8278. viewerIndex={index}
  8279. onClose={() => setEmbeddedCameraPrinters(prev => {
  8280. const next = new Map(prev);
  8281. next.delete(camera.id);
  8282. return next;
  8283. })}
  8284. />
  8285. ))}
  8286. </div>
  8287. );
  8288. }