PrintersPage.tsx 497 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196
  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 { isBedSlinger } from '../utils/bedSlinger';
  6. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  7. import {
  8. openCameraWindow,
  9. readStoredCameraViewMode,
  10. storeCameraViewMode,
  11. type CameraViewMode,
  12. } from '../utils/camera';
  13. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  14. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  15. import {
  16. isExternalSpoolHidden,
  17. setExternalSpoolHidden as persistExternalSpoolHidden,
  18. } from '../utils/printerCardPrefs';
  19. import {
  20. BED_TEMP_DEFAULTS,
  21. CHAMBER_TEMP_DEFAULTS,
  22. FAN_SPEED_DEFAULTS,
  23. NOZZLE_TEMP_DEFAULTS,
  24. buildPresetOptions,
  25. parsePresetTriple,
  26. } from '../utils/temperatureFanPresets';
  27. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  28. // covers header + filament select + temp slider + duration + rotate-tray
  29. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  30. // earlier); under-estimating leaves the popover clipped off the bottom (the
  31. // original bug at #1447).
  32. const DRYING_POPOVER_WIDTH = 240;
  33. // Height in "now" mode plus the tallest start-mode control; a conservative
  34. // over-estimate just flips the popover above the trigger sooner.
  35. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  36. // Delay presets for the "After delay" drying start mode, in minutes.
  37. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  38. // Every printer card reads the same fleet-wide scheduled-drying list.
  39. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  40. // Why a due run has not started yet: every waiting_reason the scheduler can
  41. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  42. // for ..." with no hint why nothing is happening.
  43. const WAITING_REASON_KEYS: Record<string, string> = {
  44. ams_power_required: 'printers.drying.powerRequired',
  45. ams_retract_filament: 'printers.drying.retractFilament',
  46. ams_blocked: 'printers.drying.cannotDryNow',
  47. ams_not_found: 'printers.drying.waitingAmsNotFound',
  48. printer_offline: 'printers.drying.waitingOffline',
  49. printer_busy: 'printers.drying.waitingPrinterBusy',
  50. already_drying: 'printers.drying.waitingAlreadyDrying',
  51. interrupted: 'printers.drying.waitingInterrupted',
  52. };
  53. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  54. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  55. }
  56. // Why a scheduled drying failed, by the code the scheduler stores. A row with
  57. // no code (failed before codes existed) or an unknown one shows the backend's
  58. // English error_message instead.
  59. const FAILED_REASON_KEYS: Record<string, string> = {
  60. screen_only: 'printers.drying.screenOnly',
  61. unsupported: 'printers.drying.notSupported',
  62. did_not_start: 'printers.drying.scheduleFailedDidNotStart',
  63. };
  64. function failedReasonKey(code: string | null | undefined): string | undefined {
  65. return code ? FAILED_REASON_KEYS[code] : undefined;
  66. }
  67. // Which cannot-dry code to name when the firmware reports several at once.
  68. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  69. // button's tooltip and a scheduled row's waiting reason describe one blocked
  70. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  71. // left at the outlet, and both need the user to go and do something. The rest
  72. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  73. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  74. const codes = (reasons ?? []).map(r => Number(r));
  75. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  76. if (codes.includes(3)) return 'printers.drying.retractFilament';
  77. return 'printers.drying.cannotDryNow';
  78. }
  79. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  80. import { useTranslation } from 'react-i18next';
  81. import { useTheme } from '../contexts/ThemeContext';
  82. import { useAuth } from '../contexts/AuthContext';
  83. import {
  84. Plus,
  85. Link,
  86. Unlink,
  87. Signal,
  88. Clock,
  89. MoreVertical,
  90. Trash2,
  91. RefreshCw,
  92. RotateCw,
  93. Box,
  94. HardDrive,
  95. AlertTriangle,
  96. AlertCircle,
  97. Terminal,
  98. Power,
  99. Zap,
  100. Wrench,
  101. ChevronDown,
  102. Eye,
  103. EyeOff,
  104. Filter,
  105. Pencil,
  106. ArrowLeft,
  107. ArrowRight,
  108. ArrowUp,
  109. ArrowDown,
  110. Layers,
  111. Video,
  112. Search,
  113. Loader2,
  114. Square,
  115. Pause,
  116. Play,
  117. X,
  118. Fan,
  119. Wind,
  120. AirVent,
  121. Download,
  122. ScanSearch,
  123. CheckCircle,
  124. CheckSquare,
  125. XCircle,
  126. User,
  127. Home,
  128. Printer as PrinterIcon,
  129. Info,
  130. Cable,
  131. Flame,
  132. Hourglass,
  133. Repeat,
  134. Snowflake,
  135. Gauge,
  136. DoorOpen,
  137. DoorClosed,
  138. Move,
  139. LogIn,
  140. LogOut,
  141. MoreHorizontal,
  142. SlidersHorizontal,
  143. Stethoscope,
  144. ScanEye,
  145. LineChart as LineChartIcon,
  146. LayoutGrid,
  147. MonitorPlay,
  148. ExternalLink,
  149. PictureInPicture2,
  150. ThumbsUp,
  151. ThumbsDown,
  152. } from 'lucide-react';
  153. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  154. // Aliased: lucide-react already exports a `Link` icon into this module.
  155. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  156. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  157. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  158. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  159. import { Card, CardContent } from '../components/Card';
  160. import { Button } from '../components/Button';
  161. import { ConfirmModal } from '../components/ConfirmModal';
  162. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  163. import { FileManagerModal } from '../components/FileManagerModal';
  164. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  165. import { CameraWall } from '../components/CameraWall';
  166. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  167. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  168. import { HMSErrorModal, filterKnownHMSErrors, isSevereHMSError } from '../components/HMSErrorModal';
  169. import { AiDetectionModal } from '../components/AiDetectionModal';
  170. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  171. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  172. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  173. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  174. import { AmsBackupModal } from '../components/AmsBackupModal';
  175. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  176. import type { HeaterSensorKind } from '../api/client';
  177. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  178. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  179. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  180. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  181. import { useToast } from '../contexts/ToastContext';
  182. import { ChamberLight } from '../components/icons/ChamberLight';
  183. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  184. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  185. import { FileUploadModal } from '../components/FileUploadModal';
  186. import { PrintModal } from '../components/PrintModal';
  187. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  188. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  189. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  190. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  191. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  192. import { Collapsible } from '../components/Collapsible';
  193. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  194. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  195. // The status filter's options, and the only values it may hold. One list so a
  196. // saved filter cannot be validated against a set the dropdown has since moved
  197. // on from (#2833). Labels stay literal so they remain greppable.
  198. const STATUS_FILTER_OPTIONS = [
  199. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  200. { value: 'printing', labelKey: 'printers.status.printing' },
  201. { value: 'paused', labelKey: 'printers.status.paused' },
  202. { value: 'idle', labelKey: 'printers.status.idle' },
  203. { value: 'finished', labelKey: 'printers.status.finished' },
  204. { value: 'error', labelKey: 'printers.status.error' },
  205. { value: 'offline', labelKey: 'printers.status.offline' },
  206. ] as const;
  207. function isKnownStatusFilter(value: string | null): boolean {
  208. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  209. }
  210. export interface SpoolmanSlotAssignmentRow {
  211. printer_id: number;
  212. ams_id: number;
  213. tray_id: number;
  214. spoolman_spool_id: number;
  215. }
  216. // Color names resolve via getColorName() which reads the backend color_catalog
  217. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  218. // Format K value with 3 decimal places, default to 0.020 if null
  219. function formatKValue(k: number | null | undefined): string {
  220. const value = k ?? 0.020;
  221. return value.toFixed(3);
  222. }
  223. // K-profile value shown on the slot card itself (#2532) rather than only inside
  224. // the hover popup, the way BambuStudio shows it per slot.
  225. //
  226. // `k` arrives already gated on the slot being loaded; falsy means the printer
  227. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  228. // missing value, which is captioned inside the hover card but would read as a
  229. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  230. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  231. // reported 0 makes that expression evaluate to the number 0, and React renders
  232. // numbers, putting a bare "0" under the material name.
  233. //
  234. // `reserve` holds the row's height open on the slots without a value whenever
  235. // some other slot on the same card has one, so every fill bar stays on one line.
  236. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  237. const { t } = useTranslation();
  238. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  239. if (!k) {
  240. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  241. }
  242. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  243. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  244. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  245. // family per browser and so measured differently in Safari.
  246. return (
  247. <div className={className} title={t('ams.kFactor')}>
  248. {t('ams.kFactorShort')} {formatKValue(k)}
  249. </div>
  250. );
  251. }
  252. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  253. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  254. const { mode } = useTheme();
  255. const { t } = useTranslation();
  256. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  257. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  258. return (
  259. <span
  260. className="inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded"
  261. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  262. title={side === 'L' ? t('common.left') : t('common.right')}
  263. >
  264. {side}
  265. </span>
  266. );
  267. }
  268. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  269. // deliberately a different colour, because it means something different: this
  270. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  271. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  272. const { mode } = useTheme();
  273. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  274. return (
  275. <span
  276. className="inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded"
  277. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  278. title={title}
  279. >
  280. {FTS_INLET_SIDE[inlet]}
  281. </span>
  282. );
  283. }
  284. /**
  285. * Which side indicator, if any, belongs on an AMS card header.
  286. *
  287. * Three sources, in descending authority:
  288. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  289. * through the switch, so the inlet is the only meaningful label.
  290. * 2. A real extruder id from ams_extruder_map.
  291. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  292. * never reported a map. This one is only a guess, and it is suppressed
  293. * when a switch is installed: with an FTS every unit reports extruder
  294. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  295. * nothing but their unit numbers.
  296. */
  297. function amsSideBadge(
  298. amsId: number,
  299. amsExtruderMap: Record<string, number>,
  300. amsSwitchInlet: Record<string, 'A' | 'B'>,
  301. ftsInstalled: boolean
  302. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  303. const inlet = amsSwitchInlet[String(amsId)];
  304. if (inlet) return { kind: 'inlet', inlet };
  305. const mapped = amsExtruderMap[String(amsId)];
  306. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  307. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  308. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  309. return null;
  310. }
  311. // Expand nozzle type codes to material names
  312. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  313. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  314. function nozzleTypeName(type: string, t: (key: string) => string): string {
  315. if (!type) return '';
  316. // Full text names (from main nozzle info)
  317. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  318. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  319. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  320. // 4-char codes (e.g. "HS01"): last 2 digits = material
  321. if (type.length >= 4) {
  322. const material = type.slice(2, 4);
  323. if (material === '00') return t('printers.nozzleStainlessSteel');
  324. if (material === '01') return t('printers.nozzleHardenedSteel');
  325. if (material === '05') return t('printers.nozzleTungstenCarbide');
  326. }
  327. // 2-digit numeric codes
  328. if (type === '00') return t('printers.nozzleStainlessSteel');
  329. if (type === '01') return t('printers.nozzleHardenedSteel');
  330. if (type === '05') return t('printers.nozzleTungstenCarbide');
  331. // 2-char alpha codes: H prefix = hardened steel
  332. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  333. return type;
  334. }
  335. // Parse flow type from nozzle type code
  336. // HH = high flow, HS = standard/normal
  337. function nozzleFlowName(type: string, t: (key: string) => string): string {
  338. if (!type) return '';
  339. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  340. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  341. return '';
  342. }
  343. // Per-slot hover card for nozzle rack
  344. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  345. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  346. slot: import('../api/client').NozzleRackSlot;
  347. index: number;
  348. activeStatus?: boolean;
  349. filamentName?: string;
  350. children: React.ReactNode;
  351. }) {
  352. const { t } = useTranslation();
  353. const [isVisible, setIsVisible] = useState(false);
  354. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  355. const triggerRef = useRef<HTMLDivElement>(null);
  356. const cardRef = useRef<HTMLDivElement>(null);
  357. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  358. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  359. const isMounted = slot.stat === 1;
  360. useEffect(() => {
  361. if (isVisible && triggerRef.current && cardRef.current) {
  362. const triggerRect = triggerRef.current.getBoundingClientRect();
  363. const cardHeight = cardRef.current.offsetHeight;
  364. const headerHeight = 56;
  365. const spaceAbove = triggerRect.top - headerHeight;
  366. const spaceBelow = window.innerHeight - triggerRect.bottom;
  367. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  368. setPosition('bottom');
  369. } else {
  370. setPosition('top');
  371. }
  372. }
  373. }, [isVisible]);
  374. const handleMouseEnter = () => {
  375. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  376. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  377. };
  378. const handleMouseLeave = () => {
  379. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  380. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  381. };
  382. useEffect(() => {
  383. return () => {
  384. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  385. };
  386. }, []);
  387. const filamentCss = parseFilamentColor(slot.filament_color);
  388. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  389. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  390. return (
  391. <div
  392. ref={triggerRef}
  393. className="relative"
  394. onMouseEnter={handleMouseEnter}
  395. onMouseLeave={handleMouseLeave}
  396. >
  397. {children}
  398. {isVisible && (
  399. <div
  400. ref={cardRef}
  401. className={`
  402. absolute left-1/2 -translate-x-1/2 z-50
  403. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  404. animate-in fade-in-0 zoom-in-95 duration-150
  405. `}
  406. style={{ maxWidth: 'calc(100vw - 24px)' }}
  407. >
  408. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  409. {isEmpty ? (
  410. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  411. Slot {index + 1} — Empty
  412. </div>
  413. ) : (
  414. <div className="p-2.5 space-y-1.5">
  415. {/* Diameter */}
  416. <div className="flex items-center justify-between">
  417. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  418. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  419. </div>
  420. {/* Type */}
  421. {typeFull && (
  422. <div className="flex items-center justify-between">
  423. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  424. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  425. </div>
  426. )}
  427. {/* Flow (hide if empty) */}
  428. {flowFull && (
  429. <div className="flex items-center justify-between">
  430. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  431. <span className="text-xs text-white font-semibold">{flowFull}</span>
  432. </div>
  433. )}
  434. {/* Status badge */}
  435. <div className="flex items-center justify-between">
  436. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  437. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  438. activeStatus || isMounted
  439. ? 'bg-green-900/50 text-green-400'
  440. : 'bg-bambu-dark-tertiary text-bambu-gray'
  441. }`}>
  442. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  443. </span>
  444. </div>
  445. {/* Wear (hide if null) */}
  446. {slot.wear != null && (
  447. <div className="flex items-center justify-between">
  448. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  449. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  450. </div>
  451. )}
  452. {/* Max Temp (hide if 0) */}
  453. {slot.max_temp > 0 && (
  454. <div className="flex items-center justify-between">
  455. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  456. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  457. </div>
  458. )}
  459. {/* Serial (hide if empty) */}
  460. {slot.serial_number && (
  461. <div className="flex items-center justify-between">
  462. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  463. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  464. </div>
  465. )}
  466. {/* Filament: material type + color swatch (hide if no color) */}
  467. {(filamentCss || slot.filament_type) && (
  468. <div className="flex items-center justify-between">
  469. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  470. <div className="flex items-center gap-1">
  471. {filamentCss && (
  472. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  473. )}
  474. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  475. </div>
  476. </div>
  477. )}
  478. </div>
  479. )}
  480. </div>
  481. {/* Arrow pointer */}
  482. <div
  483. className={`
  484. absolute left-1/2 -translate-x-1/2 w-0 h-0
  485. border-l-[6px] border-l-transparent
  486. border-r-[6px] border-r-transparent
  487. ${position === 'top'
  488. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  489. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  490. `}
  491. />
  492. </div>
  493. )}
  494. </div>
  495. );
  496. }
  497. // Dual-nozzle hover card showing L and R nozzle details side by side
  498. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  499. leftSlot?: import('../api/client').NozzleRackSlot;
  500. rightSlot?: import('../api/client').NozzleRackSlot;
  501. activeNozzle: 'L' | 'R';
  502. filamentInfo?: Record<string, { name: string; k: number | null }>;
  503. children: React.ReactNode;
  504. }) {
  505. const { t } = useTranslation();
  506. const [isVisible, setIsVisible] = useState(false);
  507. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  508. const triggerRef = useRef<HTMLDivElement>(null);
  509. const cardRef = useRef<HTMLDivElement>(null);
  510. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  511. useEffect(() => {
  512. if (isVisible && triggerRef.current && cardRef.current) {
  513. const triggerRect = triggerRef.current.getBoundingClientRect();
  514. const cardHeight = cardRef.current.offsetHeight;
  515. const headerHeight = 56;
  516. const spaceAbove = triggerRect.top - headerHeight;
  517. const spaceBelow = window.innerHeight - triggerRect.bottom;
  518. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  519. setPosition('bottom');
  520. } else {
  521. setPosition('top');
  522. }
  523. }
  524. }, [isVisible]);
  525. const handleMouseEnter = () => {
  526. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  527. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  528. };
  529. const handleMouseLeave = () => {
  530. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  531. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  532. };
  533. useEffect(() => {
  534. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  535. }, []);
  536. if (!leftSlot && !rightSlot) return <>{children}</>;
  537. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  538. const isActive = activeNozzle === side;
  539. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  540. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  541. const filamentCss = parseFilamentColor(slot.filament_color);
  542. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  543. return (
  544. <div className="flex-1 space-y-1.5">
  545. <div className={`text-[length:var(--pc-t10,10px)] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-700 dark:text-amber-400' : 'text-bambu-gray'}`}>
  546. {side === 'L' ? t('common.left') : t('common.right')}
  547. </div>
  548. {slot.nozzle_diameter && (
  549. <div className="flex items-center justify-between">
  550. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  551. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  552. </div>
  553. )}
  554. {typeFull && (
  555. <div className="flex items-center justify-between">
  556. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  557. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  558. </div>
  559. )}
  560. {flowFull && (
  561. <div className="flex items-center justify-between">
  562. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  563. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  564. </div>
  565. )}
  566. <div className="flex items-center justify-between">
  567. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  568. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  569. isActive
  570. ? 'bg-green-900/50 text-green-400'
  571. : 'bg-bambu-dark-tertiary text-bambu-gray'
  572. }`}>
  573. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  574. </span>
  575. </div>
  576. {slot.wear != null && (
  577. <div className="flex items-center justify-between">
  578. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  579. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  580. </div>
  581. )}
  582. {/* Serial and max temp only available on the right (removable) nozzle */}
  583. {side === 'R' && slot.max_temp > 0 && (
  584. <div className="flex items-center justify-between">
  585. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  586. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  587. </div>
  588. )}
  589. {side === 'R' && slot.serial_number && (
  590. <div className="flex items-center justify-between">
  591. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  592. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  593. </div>
  594. )}
  595. {(filamentCss || slot.filament_type || slot.filament_id) && (
  596. <div className="flex items-center justify-between">
  597. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  598. <div className="flex items-center gap-1">
  599. {filamentCss && (
  600. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  601. )}
  602. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  603. {filamentName || slot.filament_type || slot.filament_id || ''}
  604. </span>
  605. </div>
  606. </div>
  607. )}
  608. </div>
  609. );
  610. };
  611. return (
  612. <div
  613. ref={triggerRef}
  614. className="relative flex-1"
  615. onMouseEnter={handleMouseEnter}
  616. onMouseLeave={handleMouseLeave}
  617. >
  618. {children}
  619. {isVisible && (
  620. <div
  621. ref={cardRef}
  622. className={`
  623. absolute left-1/2 -translate-x-1/2 z-50
  624. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  625. animate-in fade-in-0 zoom-in-95 duration-150
  626. `}
  627. style={{ maxWidth: 'calc(100vw - 24px)' }}
  628. >
  629. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  630. <div className="p-2.5 flex gap-3">
  631. {leftSlot && renderColumn(leftSlot, 'L')}
  632. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  633. {rightSlot && renderColumn(rightSlot, 'R')}
  634. </div>
  635. </div>
  636. {/* Arrow pointer */}
  637. <div
  638. className={`
  639. absolute left-1/2 -translate-x-1/2 w-0 h-0
  640. border-l-[6px] border-l-transparent
  641. border-r-[6px] border-r-transparent
  642. ${position === 'top'
  643. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  644. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  645. `}
  646. />
  647. </div>
  648. )}
  649. </div>
  650. );
  651. }
  652. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  653. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  654. const { t } = useTranslation();
  655. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  656. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  657. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  658. // base — computing it from min(present IDs) shifts everything left when slot 16
  659. // is the one currently mounted (#943).
  660. const rackNozzles = slots.filter(s => s.id >= 2);
  661. const RACK_SIZE = 6;
  662. const RACK_BASE_ID = 16;
  663. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  664. { length: RACK_SIZE },
  665. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  666. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  667. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  668. },
  669. );
  670. return (
  671. // Sized to its contents rather than growing: the six chips are a fixed
  672. // width at any one card size, so extra width would be dead space taken
  673. // from the temperature cards beside it — which are flex-1 with a 0 basis
  674. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  675. // stays enabled so the card still gives way on a narrow printer card
  676. // instead of overflowing.
  677. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  678. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  679. <div className="flex gap-[3px] justify-center">
  680. {rackSlots.map((slot, i) => {
  681. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  682. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  683. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  684. return (
  685. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  686. <div className="flex flex-col items-center gap-0.5">
  687. <div
  688. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  689. isEmpty
  690. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  691. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  692. }`}
  693. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  694. >
  695. <span
  696. data-rack-diameter
  697. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  698. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  699. >
  700. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  701. </span>
  702. </div>
  703. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  704. acted on without counting chips. Sits below the chip rather
  705. than inside it: the chip is barely wider than its own
  706. diameter text and already carries that over a
  707. filament-coloured background. */}
  708. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  709. {i + 1}
  710. </span>
  711. </div>
  712. </NozzleSlotHoverCard>
  713. );
  714. })}
  715. </div>
  716. </div>
  717. );
  718. }
  719. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  720. function WaterDropEmpty({ className }: { className?: string }) {
  721. return (
  722. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  723. <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"/>
  724. </svg>
  725. );
  726. }
  727. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  728. function WaterDropHalf({ className }: { className?: string }) {
  729. return (
  730. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  731. <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"/>
  732. <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"/>
  733. </svg>
  734. );
  735. }
  736. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  737. function WaterDropFull({ className }: { className?: string }) {
  738. return (
  739. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  740. <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"/>
  741. <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"/>
  742. </svg>
  743. );
  744. }
  745. // Thermometer SVG - empty outline
  746. function ThermometerEmpty({ className }: { className?: string }) {
  747. return (
  748. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  749. <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"/>
  750. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  751. </svg>
  752. );
  753. }
  754. // Thermometer SVG - half filled (gold - same as humidity fair)
  755. function ThermometerHalf({ className }: { className?: string }) {
  756. return (
  757. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  758. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  759. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  760. <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"/>
  761. </svg>
  762. );
  763. }
  764. // Thermometer SVG - fully filled (red - same as humidity bad)
  765. function ThermometerFull({ className }: { className?: string }) {
  766. return (
  767. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  768. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  769. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  770. <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"/>
  771. </svg>
  772. );
  773. }
  774. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  775. // Added for visual parity with the thermometer icons on the dual-nozzle card
  776. // that previously had no icon at all (#1115, design by @m4rtini2).
  777. function NozzleIcon({ className }: { className?: string }) {
  778. return (
  779. <svg
  780. className={className}
  781. viewBox="0 0 24 24"
  782. fill="none"
  783. xmlns="http://www.w3.org/2000/svg"
  784. stroke="currentColor"
  785. strokeWidth="1.5"
  786. strokeLinecap="round"
  787. strokeLinejoin="round"
  788. >
  789. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  790. <rect x="6" y="11.5" width="12.1" height="3.7" />
  791. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  792. </svg>
  793. );
  794. }
  795. // Heater thermometer icon - filled when heating, outline when off
  796. interface HeaterThermometerProps {
  797. className?: string;
  798. color: string; // The color class (e.g., "text-orange-400")
  799. isHeating: boolean;
  800. }
  801. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  802. // Extract the actual color from Tailwind class for SVG fill
  803. const colorMap: Record<string, string> = {
  804. 'text-orange-400': '#fb923c',
  805. 'text-blue-400': '#60a5fa',
  806. 'text-green-400': '#4ade80',
  807. };
  808. const fillColor = colorMap[color] || '#888';
  809. // Glow style when heating
  810. const glowStyle = isHeating ? {
  811. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  812. } : {};
  813. if (isHeating) {
  814. // Filled thermometer with glow - heater is ON
  815. return (
  816. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  817. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  818. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  819. <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"/>
  820. </svg>
  821. );
  822. }
  823. // Empty thermometer - heater is OFF
  824. return (
  825. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  826. <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"/>
  827. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  828. </svg>
  829. );
  830. }
  831. // AMS Filament Backup tri-state indicator + toggle.
  832. // state=true → ON, click to disable
  833. // state=false → OFF, click opens modal
  834. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  835. interface AmsBackupBadgeProps {
  836. state: boolean | null;
  837. onClick: () => void;
  838. }
  839. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  840. const { t } = useTranslation();
  841. const known = state !== null;
  842. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  843. let title: string;
  844. if (state === true) {
  845. className += known
  846. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  847. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  848. title = t('printers.amsBackup.titleOn');
  849. } else if (state === false) {
  850. className += known
  851. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  852. : 'bg-bambu-dark text-bambu-gray cursor-default';
  853. title = t('printers.amsBackup.titleOff');
  854. } else {
  855. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  856. title = t('printers.amsBackup.titleUnknown');
  857. }
  858. return (
  859. <button
  860. type="button"
  861. disabled={!known}
  862. onClick={() => known && onClick()}
  863. className={className}
  864. title={title}
  865. aria-label={title}
  866. >
  867. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  868. </button>
  869. );
  870. }
  871. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  872. // like AmsBackupBadge so the two sit together in the section header, but
  873. // pinned to the right-hand end of the rule: this is a view preference for the
  874. // row, not a property of the printer.
  875. interface ExternalSpoolToggleProps {
  876. hidden: boolean;
  877. onClick: () => void;
  878. }
  879. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  880. const { t } = useTranslation();
  881. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  882. return (
  883. <button
  884. type="button"
  885. onClick={onClick}
  886. aria-pressed={hidden}
  887. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  888. hidden
  889. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  890. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  891. }`}
  892. title={title}
  893. aria-label={title}
  894. >
  895. {hidden ? <EyeOff className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Eye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  896. </button>
  897. );
  898. }
  899. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  900. // Reference: https://github.com/theicedmango/bambu-humidity
  901. interface HumidityIndicatorProps {
  902. humidity: number | string;
  903. goodThreshold?: number; // <= this is green
  904. fairThreshold?: number; // <= this is orange, > is red
  905. onClick?: () => void;
  906. compact?: boolean; // Smaller version for grid layout
  907. }
  908. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  909. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  910. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  911. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  912. // Status thresholds (configurable via settings)
  913. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  914. let textColor: string;
  915. let statusText: string;
  916. if (isNaN(humidityValue)) {
  917. textColor = '#C3C2C1';
  918. statusText = 'Unknown';
  919. } else if (humidityValue <= good) {
  920. textColor = '#22a352'; // Green - Good
  921. statusText = 'Good';
  922. } else if (humidityValue <= fair) {
  923. textColor = '#d4a017'; // Gold - Fair
  924. statusText = 'Fair';
  925. } else {
  926. textColor = '#c62828'; // Red - Bad
  927. statusText = 'Bad';
  928. }
  929. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  930. let DropComponent: React.FC<{ className?: string }>;
  931. if (isNaN(humidityValue)) {
  932. DropComponent = WaterDropEmpty;
  933. } else if (humidityValue <= good) {
  934. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  935. } else if (humidityValue <= fair) {
  936. DropComponent = WaterDropHalf; // Fair - half filled
  937. } else {
  938. DropComponent = WaterDropFull; // Bad - full (too humid)
  939. }
  940. return (
  941. <button
  942. type="button"
  943. onClick={onClick}
  944. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  945. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  946. >
  947. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  948. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  949. </button>
  950. );
  951. }
  952. // Temperature indicator with dynamic icon and coloring
  953. interface TemperatureIndicatorProps {
  954. temp: number;
  955. goodThreshold?: number; // <= this is blue
  956. fairThreshold?: number; // <= this is orange, > is red
  957. onClick?: () => void;
  958. compact?: boolean; // Smaller version for grid layout
  959. }
  960. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  961. // Ensure thresholds are numbers
  962. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  963. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  964. let textColor: string;
  965. let statusText: string;
  966. let ThermoComponent: React.FC<{ className?: string }>;
  967. if (temp <= good) {
  968. textColor = '#22a352'; // Green - good (same as humidity)
  969. statusText = 'Good';
  970. ThermoComponent = ThermometerEmpty;
  971. } else if (temp <= fair) {
  972. textColor = '#d4a017'; // Gold - fair (same as humidity)
  973. statusText = 'Fair';
  974. ThermoComponent = ThermometerHalf;
  975. } else {
  976. textColor = '#c62828'; // Red - bad (same as humidity)
  977. statusText = 'Bad';
  978. ThermoComponent = ThermometerFull;
  979. }
  980. return (
  981. <button
  982. type="button"
  983. onClick={onClick}
  984. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  985. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  986. >
  987. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  988. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  989. </button>
  990. );
  991. }
  992. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  993. *
  994. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  995. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  996. * every empty-by-bitmask slot lands here regardless of firmware payload
  997. * shape.
  998. *
  999. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  1000. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  1001. * the user cleared with "Reset Slot" where a physical spool may still be
  1002. * loaded but unassigned.
  1003. *
  1004. * Returns null when the slot is loaded (tray_type is present).
  1005. */
  1006. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  1007. if (tray?.tray_type) return null;
  1008. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  1009. // spool the firmware can't identify is physically present (exists === true)
  1010. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  1011. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  1012. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  1013. if (tray?.exists === true) return 'reset';
  1014. if (tray?.exists === false) return 'physical';
  1015. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  1016. }
  1017. // How long to wait for an AMS to report a live drying cycle after the printer
  1018. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  1019. // within a couple of seconds; 30s covers the slowest observed push cadence
  1020. // without leaving the user waiting on a verdict.
  1021. const DRY_START_CONFIRM_MS = 30_000;
  1022. export function CoverImage({
  1023. url,
  1024. printName,
  1025. className = 'w-20 h-20',
  1026. radiusClass = 'rounded-lg',
  1027. }: {
  1028. url: string | null;
  1029. printName?: string;
  1030. className?: string;
  1031. radiusClass?: string;
  1032. }) {
  1033. const { t } = useTranslation();
  1034. const [loaded, setLoaded] = useState(false);
  1035. const [error, setError] = useState(false);
  1036. const [showOverlay, setShowOverlay] = useState(false);
  1037. const imgRef = useRef<HTMLImageElement>(null);
  1038. // Cache-bust the image URL when the print name changes so the browser
  1039. // fetches the new cover instead of serving the stale cached image.
  1040. const cacheBustedUrl = useMemo(() => {
  1041. if (!url) return null;
  1042. const sep = url.includes('?') ? '&' : '?';
  1043. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1044. }, [url, printName]);
  1045. // Re-evaluate load state when the image URL changes, and ask the element
  1046. // whether it is already showing something rather than assuming it is not.
  1047. //
  1048. // `onLoad` used to be the only thing that could set `loaded`, and this
  1049. // effect reset it to false unconditionally. That is right when the URL
  1050. // really changes, but it also runs on mount — and the two are not the same
  1051. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1052. // constant for the duration of a print, so navigating away from the
  1053. // printers page and back re-mounts with a byte-identical src that the
  1054. // browser serves from its in-memory cache. The `load` event for a cache hit
  1055. // and React's passive-effect flush are both plain tasks with no ordering
  1056. // between them, so when `load` won, this effect ran afterwards and undid
  1057. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1058. // sat there until a full reload. Nothing recovered it, because the URL
  1059. // never changes again during the print and so this effect never re-runs.
  1060. //
  1061. // Being a race, it reproduced every time for #2826's reporter and not at
  1062. // all here, which is also why the network panel showed no request: there
  1063. // was no request to show.
  1064. //
  1065. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1066. // which of the two ran first. It is also correct for the case the reporter
  1067. // proposed (a `load` that fires before React's handler is live), so the
  1068. // fix stands whichever mechanism is really at work.
  1069. useEffect(() => {
  1070. setError(false);
  1071. const el = imgRef.current;
  1072. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1073. }, [cacheBustedUrl]);
  1074. return (
  1075. <>
  1076. <div
  1077. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1078. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1079. >
  1080. {cacheBustedUrl && !error ? (
  1081. <>
  1082. <img
  1083. ref={imgRef}
  1084. src={cacheBustedUrl}
  1085. alt={t('printers.printPreview')}
  1086. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1087. onLoad={() => setLoaded(true)}
  1088. onError={() => setError(true)}
  1089. />
  1090. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1091. </>
  1092. ) : (
  1093. <Box className="w-8 h-8 text-bambu-gray" />
  1094. )}
  1095. </div>
  1096. {/* Cover Image Overlay */}
  1097. {showOverlay && cacheBustedUrl && (
  1098. <div
  1099. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1100. onClick={() => setShowOverlay(false)}
  1101. >
  1102. <div className="relative max-w-2xl max-h-full">
  1103. <img
  1104. src={cacheBustedUrl}
  1105. alt={t('printers.printPreview')}
  1106. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1107. />
  1108. {printName && (
  1109. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1110. )}
  1111. </div>
  1112. </div>
  1113. )}
  1114. </>
  1115. );
  1116. }
  1117. interface PrinterMaintenanceInfo {
  1118. due_count: number;
  1119. warning_count: number;
  1120. total_print_hours: number;
  1121. }
  1122. // Status summary bar component - uses queryClient to read cached statuses
  1123. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1124. const { t } = useTranslation();
  1125. const queryClient = useQueryClient();
  1126. // Subscribe to query cache changes to re-render when status updates
  1127. // Throttled to prevent rapid re-renders from causing tab crashes
  1128. const [cacheTick, setCacheTick] = useState(0);
  1129. useEffect(() => {
  1130. let pending = false;
  1131. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1132. if (!pending) {
  1133. pending = true;
  1134. requestAnimationFrame(() => {
  1135. setCacheTick(t => t + 1);
  1136. pending = false;
  1137. });
  1138. }
  1139. });
  1140. return () => unsubscribe();
  1141. }, [queryClient]);
  1142. const { counts, nextFinish } = useMemo(() => {
  1143. let printing = 0;
  1144. let paused = 0;
  1145. let finished = 0;
  1146. let idle = 0;
  1147. let offline = 0;
  1148. let loading = 0;
  1149. let error = 0;
  1150. let nextPrinterName: string | null = null;
  1151. let nextRemainingMin: number | null = null;
  1152. let nextProgress: number = 0;
  1153. printers?.forEach((printer) => {
  1154. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1155. if (status === undefined) {
  1156. // Status not yet loaded - don't count as offline yet
  1157. loading++;
  1158. } else if (!status.connected) {
  1159. offline++;
  1160. } else {
  1161. // Count printers with active HMS errors as problems
  1162. const knownHmsCount =
  1163. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1164. if (knownHmsCount > 0) {
  1165. error++;
  1166. }
  1167. switch (status.state) {
  1168. case 'RUNNING':
  1169. printing++;
  1170. if (status.remaining_time != null && status.remaining_time > 0) {
  1171. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1172. nextRemainingMin = status.remaining_time;
  1173. nextPrinterName = printer.name;
  1174. nextProgress = status.progress || 0;
  1175. }
  1176. }
  1177. break;
  1178. case 'PAUSE':
  1179. paused++;
  1180. break;
  1181. case 'FINISH':
  1182. finished++;
  1183. break;
  1184. case 'FAILED':
  1185. // FAILED is the printer's terminal gcode_state after a print stops —
  1186. // including user cancellations, where there's no actual fault. Only
  1187. // count it as a "problem" when an HMS error is also active; otherwise
  1188. // it's just a print that ended unsuccessfully and the plate needs
  1189. // clearing (same as FINISH from the operator's perspective).
  1190. if (knownHmsCount > 0) {
  1191. // Already counted above
  1192. } else {
  1193. finished++;
  1194. }
  1195. break;
  1196. default:
  1197. idle++;
  1198. break;
  1199. }
  1200. }
  1201. });
  1202. return {
  1203. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1204. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1205. };
  1206. // eslint-disable-next-line react-hooks/exhaustive-deps
  1207. }, [printers, queryClient, cacheTick]);
  1208. if (!printers?.length) return null;
  1209. const badges: { count: number; dot: string; label: string }[] = [
  1210. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1211. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1212. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1213. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1214. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1215. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1216. ];
  1217. return (
  1218. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1219. {badges.map(({ count, dot, label }) => count > 0 && (
  1220. <div key={label} className="flex items-center gap-1.5">
  1221. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1222. <span className="text-bambu-gray">
  1223. <span className="text-white font-medium">{count}</span> {label}
  1224. </span>
  1225. </div>
  1226. ))}
  1227. {nextFinish && (
  1228. <>
  1229. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1230. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1231. <div className="flex items-center gap-2">
  1232. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1233. <span className="text-white font-medium">{nextFinish.name}</span>
  1234. </div>
  1235. <div className="flex items-center gap-2 w-full sm:w-auto">
  1236. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1237. <div
  1238. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1239. style={{ width: `${nextFinish.progress}%` }}
  1240. />
  1241. </div>
  1242. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1243. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1244. </div>
  1245. </div>
  1246. </>
  1247. )}
  1248. </div>
  1249. );
  1250. }
  1251. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1252. type ViewMode = 'expanded' | 'compact';
  1253. type ToolbarDropdownOption<T extends string> = {
  1254. value: T;
  1255. label: string;
  1256. };
  1257. function ToolbarDropdown<T extends string>({
  1258. value,
  1259. options,
  1260. onChange,
  1261. fullWidth = false,
  1262. }: {
  1263. value: T;
  1264. options: ToolbarDropdownOption<T>[];
  1265. onChange: (value: T) => void;
  1266. fullWidth?: boolean;
  1267. }) {
  1268. const [isOpen, setIsOpen] = useState(false);
  1269. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1270. return (
  1271. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1272. <button
  1273. type="button"
  1274. onClick={() => setIsOpen(open => !open)}
  1275. 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'}`}
  1276. >
  1277. <span className="truncate">{selectedOption?.label}</span>
  1278. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1279. </button>
  1280. {isOpen && (
  1281. <>
  1282. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1283. <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">
  1284. {options.map(option => (
  1285. <button
  1286. key={option.value}
  1287. type="button"
  1288. onClick={() => {
  1289. onChange(option.value);
  1290. setIsOpen(false);
  1291. }}
  1292. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1293. option.value === value ? 'text-bambu-green' : 'text-white'
  1294. }`}
  1295. >
  1296. {option.label}
  1297. </button>
  1298. ))}
  1299. </div>
  1300. </>
  1301. )}
  1302. </div>
  1303. );
  1304. }
  1305. function ToolbarMenu({
  1306. label,
  1307. icon,
  1308. children,
  1309. }: {
  1310. label: string;
  1311. icon: React.ReactNode;
  1312. children: React.ReactNode;
  1313. }) {
  1314. const [isOpen, setIsOpen] = useState(false);
  1315. return (
  1316. <div className="relative">
  1317. <button
  1318. type="button"
  1319. onClick={() => setIsOpen(open => !open)}
  1320. 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"
  1321. aria-label={label}
  1322. title={label}
  1323. >
  1324. {icon}
  1325. </button>
  1326. {isOpen && (
  1327. <>
  1328. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1329. <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">
  1330. {children}
  1331. </div>
  1332. </>
  1333. )}
  1334. </div>
  1335. );
  1336. }
  1337. function IndicatorControlPopover({
  1338. title,
  1339. options = [],
  1340. unit,
  1341. customMin,
  1342. customMax,
  1343. customStep = 1,
  1344. widthClass = 'w-[240px]',
  1345. popoverWidth = 240,
  1346. popoverHeight = 280,
  1347. isPending,
  1348. onClose,
  1349. onSubmit,
  1350. children,
  1351. }: {
  1352. title: string;
  1353. options?: Array<{ label: string; value: number }>;
  1354. unit?: string;
  1355. customMin?: number;
  1356. customMax?: number;
  1357. customStep?: number;
  1358. widthClass?: string;
  1359. popoverWidth?: number;
  1360. popoverHeight?: number;
  1361. isPending?: boolean;
  1362. onClose: () => void;
  1363. onSubmit?: (value: number) => void;
  1364. children?: React.ReactNode;
  1365. }) {
  1366. const anchorRef = useRef<HTMLSpanElement>(null);
  1367. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1368. const [customValue, setCustomValue] = useState('');
  1369. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1370. // can position via fixed coords. Portaling to document.body escapes
  1371. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1372. // own contexts and would otherwise cover the popover even at z-[60].
  1373. useLayoutEffect(() => {
  1374. const trigger = anchorRef.current?.parentElement;
  1375. if (!trigger) return;
  1376. const measure = () => {
  1377. const rect = trigger.getBoundingClientRect();
  1378. setCoords(computePopoverPosition({
  1379. triggerRect: rect,
  1380. popoverWidth,
  1381. estimatedHeight: popoverHeight,
  1382. horizontalAlign: 'center',
  1383. }));
  1384. };
  1385. measure();
  1386. window.addEventListener('resize', measure);
  1387. window.addEventListener('scroll', measure, true);
  1388. return () => {
  1389. window.removeEventListener('resize', measure);
  1390. window.removeEventListener('scroll', measure, true);
  1391. };
  1392. }, [popoverWidth, popoverHeight]);
  1393. const showCustomInput = unit !== undefined;
  1394. const submitCustom = () => {
  1395. const value = Number(customValue);
  1396. if (!Number.isFinite(value)) return;
  1397. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1398. onSubmit?.(Math.round(bounded));
  1399. };
  1400. return (
  1401. <>
  1402. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1403. {createPortal(
  1404. <>
  1405. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1406. <div
  1407. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1408. style={{
  1409. top: coords?.top ?? -9999,
  1410. left: coords?.left ?? -9999,
  1411. visibility: coords ? 'visible' : 'hidden',
  1412. }}
  1413. onClick={e => e.stopPropagation()}
  1414. >
  1415. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1416. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1417. {options.length > 0 && (
  1418. <div className="px-3 py-2.5">
  1419. <div className="grid grid-cols-2 gap-1.5">
  1420. {options.map(option => (
  1421. <button
  1422. key={`${option.label}-${option.value}`}
  1423. type="button"
  1424. disabled={isPending}
  1425. onClick={() => onSubmit?.(option.value)}
  1426. 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"
  1427. >
  1428. {option.label}
  1429. </button>
  1430. ))}
  1431. </div>
  1432. </div>
  1433. )}
  1434. {children}
  1435. {showCustomInput && (
  1436. <>
  1437. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1438. <form
  1439. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1440. onSubmit={(e) => {
  1441. e.preventDefault();
  1442. submitCustom();
  1443. }}
  1444. >
  1445. <input
  1446. type="number"
  1447. min={customMin}
  1448. max={customMax}
  1449. step={customStep}
  1450. value={customValue}
  1451. onChange={e => setCustomValue(e.target.value)}
  1452. placeholder="Custom"
  1453. 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"
  1454. />
  1455. <button
  1456. type="submit"
  1457. disabled={isPending || customValue.trim() === ''}
  1458. 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"
  1459. >
  1460. Set
  1461. </button>
  1462. </form>
  1463. </>
  1464. )}
  1465. </div>
  1466. </>,
  1467. document.body
  1468. )}
  1469. </>
  1470. );
  1471. }
  1472. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1473. function NozzleTemperatureControlBox({
  1474. label,
  1475. current,
  1476. target,
  1477. isActive,
  1478. isPending,
  1479. onSubmit,
  1480. options = NOZZLE_TEMPERATURE_OPTIONS,
  1481. }: {
  1482. label: string;
  1483. current?: number;
  1484. target?: number;
  1485. isActive: boolean;
  1486. isPending?: boolean;
  1487. onSubmit: (value: number) => void;
  1488. options?: Array<{ label: string; value: number }>;
  1489. }) {
  1490. const [customValue, setCustomValue] = useState('');
  1491. const submitCustom = () => {
  1492. const value = Number(customValue);
  1493. if (!Number.isFinite(value)) return;
  1494. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1495. };
  1496. return (
  1497. <div className={`rounded-lg border p-2 ${isActive ? 'border-amber-500/60 dark:border-amber-400/60 bg-amber-50 dark:bg-amber-400/10' : 'border-bambu-dark-tertiary bg-bambu-dark'}`}>
  1498. <div className="mb-1.5 flex items-center justify-between gap-2">
  1499. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1500. <span className="text-[10px] text-bambu-gray">
  1501. {Math.round(current ?? 0)}°C
  1502. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1503. </span>
  1504. </div>
  1505. <div className="grid grid-cols-2 gap-1">
  1506. {options.map(option => (
  1507. <button
  1508. key={`${label}-${option.value}`}
  1509. type="button"
  1510. disabled={isPending}
  1511. onClick={() => onSubmit(option.value)}
  1512. 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"
  1513. >
  1514. {option.label}
  1515. </button>
  1516. ))}
  1517. </div>
  1518. <form
  1519. className="mt-1.5 flex gap-1"
  1520. onSubmit={(e) => {
  1521. e.preventDefault();
  1522. submitCustom();
  1523. }}
  1524. >
  1525. <input
  1526. type="number"
  1527. min={0}
  1528. max={320}
  1529. step={1}
  1530. value={customValue}
  1531. onChange={e => setCustomValue(e.target.value)}
  1532. placeholder="Custom"
  1533. 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"
  1534. />
  1535. <button
  1536. type="submit"
  1537. disabled={isPending || customValue.trim() === ''}
  1538. 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"
  1539. >
  1540. Set
  1541. </button>
  1542. </form>
  1543. </div>
  1544. );
  1545. }
  1546. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1547. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1548. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1549. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1550. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1551. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1552. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1553. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1554. };
  1555. /** Classify a printer into one of the UI status buckets. */
  1556. function classifyPrinterStatus(
  1557. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1558. ): PrinterState {
  1559. if (!status?.connected) return 'offline';
  1560. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1561. if (hmsErrors.length > 0) return 'error';
  1562. switch (status.state) {
  1563. case 'RUNNING': return 'printing';
  1564. case 'PAUSE': return 'paused';
  1565. case 'FINISH': return 'finished';
  1566. // FAILED without an active HMS error is the printer's terminal state after
  1567. // any unsuccessful end — including user-cancellations. Treat the same as
  1568. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1569. // HMS code is actually attached (handled by the early-return above).
  1570. case 'FAILED': return 'finished';
  1571. default: return 'idle';
  1572. }
  1573. }
  1574. /**
  1575. * Get human-readable status display text for a printer.
  1576. * Uses stg_cur_name for detailed calibration/preparation stages,
  1577. * otherwise formats the gcode_state nicely.
  1578. */
  1579. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1580. // If we have a specific stage name (calibration, heating, etc.), use it
  1581. if (stg_cur_name) {
  1582. return stg_cur_name;
  1583. }
  1584. // Format the gcode_state nicely
  1585. switch (state) {
  1586. case 'RUNNING':
  1587. return 'Printing';
  1588. case 'PAUSE':
  1589. return 'Paused';
  1590. case 'FINISH':
  1591. return 'Finished';
  1592. case 'FAILED':
  1593. return 'Failed';
  1594. case 'IDLE':
  1595. return 'Idle';
  1596. default:
  1597. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1598. }
  1599. }
  1600. // Bambu models that ship with an enclosure chamber fan (firmware field
  1601. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1602. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1603. // widget is hidden in fanItems instead of rendered greyed-out.
  1604. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1605. 'X1C',
  1606. 'X1',
  1607. 'X1E',
  1608. 'X2D',
  1609. 'P1S',
  1610. 'P2S',
  1611. 'H2D',
  1612. 'H2D Pro',
  1613. 'H2C',
  1614. 'H2S',
  1615. ]);
  1616. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1617. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1618. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1619. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1620. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1621. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1622. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1623. 'P2S',
  1624. 'X2D',
  1625. ]);
  1626. // Map SSDP model codes to display names
  1627. function mapModelCode(ssdpModel: string | null): string {
  1628. if (!ssdpModel) return '';
  1629. const modelMap: Record<string, string> = {
  1630. // H2 Series
  1631. 'O1D': 'H2D',
  1632. 'O1E': 'H2D Pro',
  1633. 'O2D': 'H2D Pro',
  1634. 'O1C': 'H2C',
  1635. 'O1C2': 'H2C',
  1636. 'O1S': 'H2S',
  1637. // X1 Series
  1638. 'BL-P001': 'X1C',
  1639. 'BL-P002': 'X1',
  1640. 'BL-P003': 'X1E',
  1641. // X2 Series
  1642. 'N6': 'X2D',
  1643. // A2 Series
  1644. 'N9': 'A2L',
  1645. // P Series
  1646. 'C11': 'P1S',
  1647. 'C12': 'P1P',
  1648. 'C13': 'P2S',
  1649. // A1 Series
  1650. 'N2S': 'A1',
  1651. 'N1': 'A1 Mini',
  1652. // Direct matches
  1653. 'X1C': 'X1C',
  1654. 'X1': 'X1',
  1655. 'X1E': 'X1E',
  1656. 'X2D': 'X2D',
  1657. 'P1S': 'P1S',
  1658. 'P1P': 'P1P',
  1659. 'P2S': 'P2S',
  1660. 'A1': 'A1',
  1661. 'A1 Mini': 'A1 Mini',
  1662. 'A2L': 'A2L',
  1663. 'H2D': 'H2D',
  1664. 'H2D Pro': 'H2D Pro',
  1665. 'H2C': 'H2C',
  1666. 'H2S': 'H2S',
  1667. };
  1668. return modelMap[ssdpModel] || ssdpModel;
  1669. }
  1670. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1671. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1672. // • User-defined friendly name (editable, protected by printers:update)
  1673. // • AMS serial number
  1674. // • AMS firmware version
  1675. export function AmsNameHoverCard({
  1676. ams,
  1677. printerId,
  1678. label,
  1679. amsLabels,
  1680. canEdit,
  1681. onSaved,
  1682. children,
  1683. }: {
  1684. ams: import('../api/client').AMSUnit;
  1685. printerId: number;
  1686. label: string; // auto-generated label, e.g. "AMS-A"
  1687. amsLabels?: Record<number, string>;
  1688. canEdit: boolean;
  1689. onSaved: () => void;
  1690. children: React.ReactNode;
  1691. }) {
  1692. const { t } = useTranslation();
  1693. const [isVisible, setIsVisible] = useState(false);
  1694. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1695. const [editValue, setEditValue] = useState('');
  1696. const [isSaving, setIsSaving] = useState(false);
  1697. const [saveError, setSaveError] = useState<string | null>(null);
  1698. const [isInputFocused, setIsInputFocused] = useState(false);
  1699. const triggerRef = useRef<HTMLDivElement>(null);
  1700. const cardRef = useRef<HTMLDivElement>(null);
  1701. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1702. useEffect(() => {
  1703. if (isVisible) {
  1704. setEditValue(amsLabels?.[ams.id] ?? '');
  1705. setSaveError(null);
  1706. requestAnimationFrame(() => {
  1707. if (triggerRef.current && cardRef.current) {
  1708. const rect = triggerRef.current.getBoundingClientRect();
  1709. const spaceAbove = rect.top - 56;
  1710. const spaceBelow = window.innerHeight - rect.bottom;
  1711. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1712. }
  1713. });
  1714. }
  1715. }, [isVisible, amsLabels, ams.id]);
  1716. const handleMouseEnter = () => {
  1717. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1718. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1719. };
  1720. const handleMouseLeave = () => {
  1721. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1722. if (!isInputFocused) {
  1723. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1724. }
  1725. };
  1726. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1727. const handleSave = async () => {
  1728. if (!canEdit) return;
  1729. setIsSaving(true);
  1730. setSaveError(null);
  1731. try {
  1732. const trimmed = editValue.trim();
  1733. if (trimmed) {
  1734. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1735. } else {
  1736. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1737. }
  1738. onSaved();
  1739. setIsVisible(false);
  1740. } catch (err) {
  1741. setSaveError(err instanceof Error ? err.message : String(err));
  1742. } finally {
  1743. setIsSaving(false);
  1744. }
  1745. };
  1746. const handleClear = async () => {
  1747. if (!canEdit) return;
  1748. setIsSaving(true);
  1749. setSaveError(null);
  1750. try {
  1751. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1752. onSaved();
  1753. setIsVisible(false);
  1754. } catch (err) {
  1755. setSaveError(err instanceof Error ? err.message : String(err));
  1756. } finally {
  1757. setIsSaving(false);
  1758. }
  1759. };
  1760. return (
  1761. <div
  1762. ref={triggerRef}
  1763. className="relative inline-block"
  1764. onMouseEnter={handleMouseEnter}
  1765. onMouseLeave={handleMouseLeave}
  1766. >
  1767. {children}
  1768. {isVisible && (
  1769. <div
  1770. ref={cardRef}
  1771. className={`
  1772. absolute left-0 z-50
  1773. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1774. animate-in fade-in-0 zoom-in-95 duration-150
  1775. `}
  1776. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1777. onMouseEnter={handleMouseEnter}
  1778. onMouseLeave={handleMouseLeave}
  1779. >
  1780. <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">
  1781. {/* AMS auto-label */}
  1782. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1783. {/* Serial number */}
  1784. <div className="flex items-center justify-between gap-2">
  1785. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1786. {t('printers.amsPopup.serialNumber')}
  1787. </span>
  1788. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1789. </div>
  1790. {/* Firmware version */}
  1791. <div className="flex items-center justify-between gap-2">
  1792. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1793. {t('printers.amsPopup.firmwareVersion')}
  1794. </span>
  1795. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1796. </div>
  1797. {/* Friendly name editor */}
  1798. <div className="space-y-1">
  1799. <div className="flex items-center gap-2">
  1800. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1801. {t('printers.amsPopup.friendlyName')}
  1802. </span>
  1803. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1804. </div>
  1805. <input
  1806. type="text"
  1807. value={editValue}
  1808. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1809. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1810. onFocus={() => setIsInputFocused(true)}
  1811. onBlur={() => {
  1812. setIsInputFocused(false);
  1813. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1814. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1815. }}
  1816. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1817. disabled={!canEdit}
  1818. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1819. 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"
  1820. maxLength={100}
  1821. />
  1822. {canEdit && (
  1823. <div className="space-y-1">
  1824. {saveError && (
  1825. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1826. )}
  1827. <div className="flex gap-1 justify-end">
  1828. <button
  1829. onClick={handleSave}
  1830. disabled={isSaving}
  1831. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1832. >
  1833. {t('printers.amsPopup.save')}
  1834. </button>
  1835. {amsLabels?.[ams.id] && (
  1836. <button
  1837. onClick={handleClear}
  1838. disabled={isSaving}
  1839. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1840. >
  1841. {t('printers.amsPopup.clear')}
  1842. </button>
  1843. )}
  1844. </div>
  1845. </div>
  1846. )}
  1847. </div>
  1848. </div>
  1849. </div>
  1850. )}
  1851. </div>
  1852. );
  1853. }
  1854. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1855. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1856. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1857. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1858. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1859. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1860. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1861. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1862. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1863. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1864. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1865. };
  1866. // How much the printer card's body type and icons grow at each card size
  1867. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1868. // 1.0 and an existing install looks identical until the user picks L or XL --
  1869. // the same control the request asked to have this follow.
  1870. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1871. // The scaled sizes, handed to the card subtree as custom properties. Every
  1872. // converted class names its old fixed value as the fallback, so anything that
  1873. // renders outside a card root -- the portalled temperature popover -- keeps
  1874. // exactly the size it has today.
  1875. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1876. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1877. // Rounded to a tenth so the values stay readable in devtools.
  1878. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1879. return {
  1880. '--pc-t8': px(8),
  1881. '--pc-t9': px(9),
  1882. '--pc-t10': px(10),
  1883. '--pc-t11': px(11),
  1884. '--pc-i2': px(8),
  1885. '--pc-i25': px(10),
  1886. '--pc-i3': px(12),
  1887. '--pc-i35': px(14),
  1888. '--pc-i4': px(16),
  1889. '--pc-i5': px(20),
  1890. '--pc-i7': px(28),
  1891. } as React.CSSProperties;
  1892. }
  1893. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1894. const { t } = useTranslation();
  1895. const queryClient = useQueryClient();
  1896. const { showToast } = useToast();
  1897. // One fleet-wide query shared by every card, not one per card: the list is
  1898. // nearly always empty and a 20-printer fleet would otherwise make 20
  1899. // requests every 30s. React Query dedupes on the key.
  1900. const { data: scheduled = [] } = useQuery({
  1901. queryKey: SCHEDULED_DRYINGS_KEY,
  1902. queryFn: () => api.listScheduledDryings(),
  1903. refetchInterval: 30_000,
  1904. });
  1905. // The live AMS status reports a starting cycle well before the next poll;
  1906. // refetch so a just-dispatched schedule doesn't linger as pending.
  1907. useEffect(() => {
  1908. if (dryingActive) {
  1909. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1910. }
  1911. }, [dryingActive, queryClient]);
  1912. const cancelMutation = useMutation({
  1913. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1914. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1915. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1916. });
  1917. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1918. // old firmware on a printer that was offline at schedule time), and without
  1919. // this the run just vanishes with only the backend log saying why.
  1920. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1921. if (rows.length === 0) return null;
  1922. return (
  1923. <div className="mt-2 space-y-1">
  1924. {rows.map(s => {
  1925. const failed = s.status === 'failed';
  1926. const reasonKey = waitingReasonKey(s.waiting_reason);
  1927. const failedKey = failedReasonKey(s.error_code);
  1928. return (
  1929. <div
  1930. key={s.id}
  1931. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1932. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1933. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1934. }`}
  1935. >
  1936. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1937. {failed ? (
  1938. t('printers.drying.scheduleFailedReason', {
  1939. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1940. })
  1941. ) : (
  1942. <>
  1943. {s.start_after
  1944. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1945. : t('printers.drying.scheduledAsap')}
  1946. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1947. </>
  1948. )}
  1949. </span>
  1950. <button
  1951. onClick={() => cancelMutation.mutate(s.id)}
  1952. disabled={cancelMutation.isPending}
  1953. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1954. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1955. >
  1956. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1957. </button>
  1958. </div>
  1959. );
  1960. })}
  1961. </div>
  1962. );
  1963. }
  1964. function PrinterCard({
  1965. printer,
  1966. hideIfDisconnected,
  1967. maintenanceInfo,
  1968. viewMode = 'expanded',
  1969. cardSize = 2,
  1970. amsThresholds,
  1971. spoolmanEnabled = false,
  1972. linkedSpools,
  1973. spoolmanUrl,
  1974. spoolmanSyncMode,
  1975. onGetAssignment,
  1976. onUnassignSpool,
  1977. spoolmanSpools,
  1978. spoolmanSlotAssignments,
  1979. spoolmanLoading = false,
  1980. onUnassignSpoolmanSpool,
  1981. timeFormat = 'system',
  1982. cameraViewMode = 'window',
  1983. onOpenEmbeddedCamera,
  1984. onSelectCameraViewMode,
  1985. checkPrinterFirmware = true,
  1986. dryingPresets = DRYING_PRESETS,
  1987. requirePlateClear = false,
  1988. selectionMode = false,
  1989. isSelected = false,
  1990. onToggleSelect,
  1991. onOpenCompactCard,
  1992. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1993. bedTempPresets = BED_TEMP_DEFAULTS,
  1994. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1995. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1996. aiDetectionEnabled = false,
  1997. aiDetection,
  1998. aiLastError = null,
  1999. }: {
  2000. printer: Printer;
  2001. hideIfDisconnected?: boolean;
  2002. maintenanceInfo?: PrinterMaintenanceInfo;
  2003. viewMode?: ViewMode;
  2004. cardSize?: number;
  2005. amsThresholds?: {
  2006. humidityGood: number;
  2007. humidityFair: number;
  2008. tempGood: number;
  2009. tempFair: number;
  2010. };
  2011. spoolmanEnabled?: boolean;
  2012. hasUnlinkedSpools?: boolean;
  2013. linkedSpools?: Record<string, LinkedSpoolInfo>;
  2014. spoolmanUrl?: string | null;
  2015. spoolmanSyncMode?: string | null;
  2016. spoolAssignments?: SpoolAssignment[];
  2017. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  2018. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  2019. spoolmanSpools?: InventorySpool[];
  2020. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  2021. spoolmanLoading?: boolean;
  2022. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  2023. timeFormat?: 'system' | '12h' | '24h';
  2024. cameraViewMode?: CameraViewMode;
  2025. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  2026. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  2027. checkPrinterFirmware?: boolean;
  2028. dryingPresets?: Record<string, DryingPreset>;
  2029. requirePlateClear?: boolean;
  2030. selectionMode?: boolean;
  2031. isSelected?: boolean;
  2032. onToggleSelect?: (id: number) => void;
  2033. onOpenCompactCard?: (id: number) => void;
  2034. nozzleTempPresets?: readonly [number, number, number];
  2035. bedTempPresets?: readonly [number, number, number];
  2036. chamberTempPresets?: readonly [number, number, number];
  2037. fanSpeedPresets?: readonly [number, number, number];
  2038. aiDetectionEnabled?: boolean;
  2039. aiDetection?: AiDetection;
  2040. aiLastError?: string | null;
  2041. }) {
  2042. const { t } = useTranslation();
  2043. const queryClient = useQueryClient();
  2044. const navigate = useNavigate();
  2045. const { showToast } = useToast();
  2046. const { hasPermission, canModify } = useAuth();
  2047. const [showMenu, setShowMenu] = useState(false);
  2048. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  2049. const [deleteArchives, setDeleteArchives] = useState(true);
  2050. const [showEditModal, setShowEditModal] = useState(false);
  2051. const [showFileManager, setShowFileManager] = useState(false);
  2052. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  2053. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  2054. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  2055. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  2056. const [showHMSModal, setShowHMSModal] = useState(false);
  2057. // #1546: AI failure detection modal — opens from the AI badge.
  2058. const [showAiModal, setShowAiModal] = useState(false);
  2059. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  2060. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  2061. // External spool visibility (#1782) — browser-local, per printer. Read once
  2062. // per card; the toggle that writes it is the only thing that changes it.
  2063. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2064. isExternalSpoolHidden(printer.id),
  2065. );
  2066. const toggleExternalSpool = useCallback(() => {
  2067. setExternalSpoolHidden((prev) => {
  2068. const next = !prev;
  2069. persistExternalSpoolHidden(printer.id, next);
  2070. return next;
  2071. });
  2072. }, [printer.id]);
  2073. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2074. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2075. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2076. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2077. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2078. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2079. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2080. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2081. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2082. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2083. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2084. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2085. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2086. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2087. // AMS drying popover state: which AMS unit has the popover open
  2088. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2089. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2090. const [dryingFilament, setDryingFilament] = useState('PLA');
  2091. const [dryingTemp, setDryingTemp] = useState(50);
  2092. const [dryingDuration, setDryingDuration] = useState(4);
  2093. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2094. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2095. // go through scheduleDryingMutation.
  2096. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2097. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2098. const [dryingStartAt, setDryingStartAt] = useState('');
  2099. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2100. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2101. // Reset every field the popover owns, including the start mode. Leaving the
  2102. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2103. // the next open, by then in the past, and the POST rejected it.
  2104. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2105. const firstTray = ams.tray.find(t => t.tray_type);
  2106. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2107. // Only reachable if a custom preset set dropped PLA itself.
  2108. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2109. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2110. setDryingFilament(filType);
  2111. setDryingTemp(preset[moduleType] || preset.n3f);
  2112. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2113. setDryingRotateTray(false);
  2114. setDryingStartMode('now');
  2115. setDryingDelayMinutes(120);
  2116. setDryingStartAt('');
  2117. setDryingPopoverModuleType(ams.module_type);
  2118. setDryingPopoverAmsId(ams.id);
  2119. setDryingPopoverAnchor(trigger);
  2120. }, [dryingPresets]);
  2121. // Re-measure on resize/scroll so the popover and its arrow track the
  2122. // flame button, like IndicatorControlPopover.
  2123. useLayoutEffect(() => {
  2124. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2125. const measure = () => {
  2126. setDryingPopoverPos(computePopoverPosition({
  2127. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2128. popoverWidth: DRYING_POPOVER_WIDTH,
  2129. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2130. horizontalAlign: 'center',
  2131. }));
  2132. };
  2133. measure();
  2134. window.addEventListener('resize', measure);
  2135. window.addEventListener('scroll', measure, true);
  2136. return () => {
  2137. window.removeEventListener('resize', measure);
  2138. window.removeEventListener('scroll', measure, true);
  2139. };
  2140. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2141. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2142. // Whether the click hitting the backdrop is the one that dismissed the
  2143. // native datetime picker (see the backdrop's onMouseDown).
  2144. const dryingBackdropSkipCloseRef = useRef(false);
  2145. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2146. // an object rather than a bare id so restarting drying on the SAME unit produces
  2147. // a new identity and rearms the timeout below.
  2148. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2149. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2150. const [isDropUploading, setIsDropUploading] = useState(false);
  2151. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2152. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2153. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2154. // inside the card would have to open upward into the card body; anchored to
  2155. // the viewport it escapes the card and the grid's scroll container both.
  2156. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2157. const dragCounterRef = useRef(0);
  2158. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2159. amsId: number;
  2160. amsLabel: string;
  2161. mode: 'humidity' | 'temperature';
  2162. } | null>(null);
  2163. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2164. initialKind: HeaterSensorKind;
  2165. availableKinds: HeaterSensorKind[];
  2166. } | null>(null);
  2167. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2168. tagUid: string;
  2169. trayUuid: string;
  2170. printerId: number;
  2171. amsId: number;
  2172. trayId: number;
  2173. } | null>(null);
  2174. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2175. printerId: number;
  2176. amsId: number;
  2177. trayId: number;
  2178. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2179. } | null>(null);
  2180. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2181. amsId: number;
  2182. trayId: number;
  2183. trayCount: number;
  2184. trayType?: string;
  2185. trayColor?: string;
  2186. traySubBrands?: string;
  2187. trayInfoIdx?: string;
  2188. extruderId?: number;
  2189. caliIdx?: number | null;
  2190. savedPresetId?: string;
  2191. } | null>(null);
  2192. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2193. const [plateCheckResult, setPlateCheckResult] = useState<{
  2194. is_empty: boolean;
  2195. confidence: number;
  2196. difference_percent: number;
  2197. message: string;
  2198. debug_image_url?: string;
  2199. needs_calibration: boolean;
  2200. light_warning?: boolean;
  2201. reference_count?: number;
  2202. max_references?: number;
  2203. roi?: { x: number; y: number; w: number; h: number };
  2204. } | null>(null);
  2205. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2206. const [isCalibrating, setIsCalibrating] = useState(false);
  2207. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2208. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2209. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2210. const { data: status } = useQuery({
  2211. queryKey: ['printerStatus', printer.id],
  2212. queryFn: () => api.getPrinterStatus(printer.id),
  2213. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2214. });
  2215. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2216. const { data: firmwareInfo } = useQuery({
  2217. queryKey: ['firmwareUpdate', printer.id],
  2218. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2219. staleTime: 5 * 60 * 1000,
  2220. refetchInterval: 5 * 60 * 1000,
  2221. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2222. });
  2223. // Collect unique tray_info_idx values for cloud filament info lookup
  2224. const trayInfoIds = useMemo(() => {
  2225. const ids = new Set<string>();
  2226. if (status?.ams) {
  2227. for (const ams of status.ams) {
  2228. for (const tray of ams.tray || []) {
  2229. if (tray.tray_info_idx) {
  2230. ids.add(tray.tray_info_idx);
  2231. }
  2232. }
  2233. }
  2234. }
  2235. for (const vt of status?.vt_tray ?? []) {
  2236. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2237. }
  2238. if (status?.nozzle_rack) {
  2239. for (const slot of status.nozzle_rack) {
  2240. if (slot.filament_id) {
  2241. ids.add(slot.filament_id);
  2242. }
  2243. }
  2244. }
  2245. return Array.from(ids);
  2246. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2247. // Collect loaded filament types for queue widget filtering
  2248. const loadedFilamentTypes = useMemo(() => {
  2249. const types = new Set<string>();
  2250. if (status?.ams) {
  2251. for (const ams of status.ams) {
  2252. for (const tray of ams.tray || []) {
  2253. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2254. }
  2255. }
  2256. }
  2257. for (const vt of status?.vt_tray ?? []) {
  2258. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2259. }
  2260. return types;
  2261. }, [status?.ams, status?.vt_tray]);
  2262. // Collect loaded filament type+color pairs for queue widget override matching
  2263. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2264. const loadedFilaments = useMemo(() => {
  2265. const filaments = new Set<string>();
  2266. if (status?.ams) {
  2267. for (const ams of status.ams) {
  2268. for (const tray of ams.tray || []) {
  2269. if (tray.tray_type && tray.tray_color) {
  2270. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2271. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2272. }
  2273. }
  2274. }
  2275. }
  2276. for (const vt of status?.vt_tray ?? []) {
  2277. if (vt.tray_type && vt.tray_color) {
  2278. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2279. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2280. }
  2281. }
  2282. return filaments;
  2283. }, [status?.ams, status?.vt_tray]);
  2284. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2285. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2286. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2287. const loadedVariants = useMemo(() => {
  2288. const variants = new Set<string>();
  2289. if (status?.ams) {
  2290. for (const ams of status.ams) {
  2291. for (const tray of ams.tray || []) {
  2292. if (tray.tray_type && tray.tray_color) {
  2293. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2294. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2295. }
  2296. }
  2297. }
  2298. }
  2299. for (const vt of status?.vt_tray ?? []) {
  2300. if (vt.tray_type && vt.tray_color) {
  2301. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2302. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2303. }
  2304. }
  2305. return variants;
  2306. }, [status?.ams, status?.vt_tray]);
  2307. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2308. const { data: filamentInfo } = useQuery({
  2309. queryKey: ['filamentInfo', trayInfoIds],
  2310. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2311. enabled: trayInfoIds.length > 0,
  2312. staleTime: 5 * 60 * 1000, // 5 minutes
  2313. });
  2314. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2315. const { data: slotPresets } = useQuery({
  2316. queryKey: ['slotPresets', printer.id],
  2317. queryFn: () => api.getSlotPresets(printer.id),
  2318. staleTime: 2 * 60 * 1000, // 2 minutes
  2319. });
  2320. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2321. // Only queried when there's a running print backed by an archive; shared
  2322. // React Query cache with the Queue / Archives pages keeps it cheap.
  2323. const activeArchiveId =
  2324. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2325. const { data: activeArchivePlates } = useQuery({
  2326. queryKey: ['archive-plates', activeArchiveId],
  2327. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2328. enabled: activeArchiveId != null,
  2329. staleTime: 5 * 60 * 1000,
  2330. });
  2331. const activePlateLabel = (() => {
  2332. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2333. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2334. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2335. })();
  2336. // Fetch user-defined AMS friendly names from the database
  2337. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2338. queryKey: ['amsLabels', printer.id],
  2339. queryFn: () => api.getAmsLabels(printer.id),
  2340. staleTime: 5 * 60 * 1000, // 5 minutes
  2341. });
  2342. // Cache WiFi signal to prevent it disappearing on updates
  2343. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2344. useEffect(() => {
  2345. if (status?.wifi_signal != null) {
  2346. setCachedWifiSignal(status.wifi_signal);
  2347. }
  2348. }, [status?.wifi_signal]);
  2349. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2350. // Cache connected state to prevent flicker when status briefly becomes undefined
  2351. const cachedConnected = useRef<boolean | undefined>(undefined);
  2352. useEffect(() => {
  2353. if (status?.connected !== undefined) {
  2354. cachedConnected.current = status.connected;
  2355. }
  2356. }, [status?.connected]);
  2357. const isConnected = status?.connected ?? cachedConnected.current;
  2358. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2359. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2360. useEffect(() => {
  2361. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2362. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2363. }
  2364. }, [status?.ams_extruder_map]);
  2365. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2366. ? status.ams_extruder_map
  2367. : cachedAmsExtruderMap.current;
  2368. // Same caching for the Filament Track Switch inlet bindings, for the same
  2369. // reason: a partial MQTT frame briefly empties the map and the badges would
  2370. // otherwise blink out.
  2371. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2372. useEffect(() => {
  2373. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2374. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2375. }
  2376. }, [status?.ams_switch_inlet]);
  2377. const ftsInstalled = status?.fila_switch?.installed === true;
  2378. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2379. ? status.ams_switch_inlet
  2380. : cachedAmsSwitchInlet.current;
  2381. // Cache AMS data to prevent it disappearing on idle/offline printers
  2382. const cachedAmsData = useRef<AMSUnit[]>([]);
  2383. useEffect(() => {
  2384. if (status?.ams && status.ams.length > 0) {
  2385. cachedAmsData.current = status.ams;
  2386. }
  2387. }, [status?.ams]);
  2388. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2389. // #2532: the K-profile line only exists on slots the printer has actually
  2390. // calibrated. The AMS units and the external-spool group are flex siblings in
  2391. // one row, so on a card that shows a value anywhere, the slots without one
  2392. // reserve the same height -- otherwise their fill bars sit a line above their
  2393. // neighbours'. A card with no calibrated slot at all is unaffected.
  2394. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2395. || (status?.vt_tray ?? []).some(tray => tray.k);
  2396. // Confirm a drying cycle actually started (#2533). Firmware answers
  2397. // ams_filament_drying with result=success even when it then silently declines,
  2398. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2399. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2400. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2401. // means the printer took the command and dropped it.
  2402. useEffect(() => {
  2403. if (!dryStartWatch) return;
  2404. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2405. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2406. }, [dryStartWatch, amsData]);
  2407. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2408. // otherwise rearm the timeout on every frame, so it would never elapse.
  2409. useEffect(() => {
  2410. if (!dryStartWatch) return;
  2411. const timer = setTimeout(() => {
  2412. setDryStartWatch(null);
  2413. showToast(t('printers.drying.toastNotStarted'), 'error');
  2414. }, DRY_START_CONFIRM_MS);
  2415. return () => clearTimeout(timer);
  2416. }, [dryStartWatch, showToast, t]);
  2417. // Cache tray_now to prevent flickering when undefined values come in
  2418. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2419. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2420. const cachedTrayNow = useRef<number | undefined>(undefined);
  2421. const currentTrayNow = status?.tray_now;
  2422. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2423. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2424. cachedTrayNow.current = currentTrayNow;
  2425. } else if (currentTrayNow === 255) {
  2426. cachedTrayNow.current = undefined;
  2427. }
  2428. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2429. ? currentTrayNow
  2430. : cachedTrayNow.current;
  2431. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2432. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2433. // expectedTray = the slot the firmware now expects filament in
  2434. // previousTray = the slot that ran out
  2435. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2436. // so these are often different — the graphic highlights the expected one.
  2437. const expectedTray = status?.expected_tray ?? null;
  2438. const previousTray = status?.previous_tray ?? null;
  2439. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2440. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2441. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2442. if (globalId === null) return null;
  2443. if (globalId === 254) return t('printers.expectedSlot.external');
  2444. if (globalId >= 128 && globalId <= 135) {
  2445. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2446. }
  2447. const amsId = Math.floor(globalId / 4);
  2448. const slot = globalId % 4;
  2449. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2450. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2451. };
  2452. const runoutGuidance = status?.state === 'PAUSE'
  2453. ? {
  2454. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2455. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2456. }
  2457. : null;
  2458. // Fetch smart plug for this printer
  2459. const { data: smartPlug } = useQuery({
  2460. queryKey: ['smartPlugByPrinter', printer.id],
  2461. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2462. });
  2463. // Fetch script plugs for this printer (for multi-device control)
  2464. const { data: scriptPlugs } = useQuery({
  2465. queryKey: ['scriptPlugsByPrinter', printer.id],
  2466. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2467. });
  2468. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2469. const { data: plugStatus } = useQuery({
  2470. queryKey: ['smartPlugStatus', smartPlug?.id],
  2471. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2472. enabled: !!smartPlug,
  2473. refetchInterval: 10000, // 10 seconds for real-time power display
  2474. });
  2475. // Fetch queue count for this printer
  2476. const { data: queueItems } = useQuery({
  2477. queryKey: ['queue', printer.id, 'pending'],
  2478. queryFn: () => api.getQueue(printer.id, 'pending'),
  2479. });
  2480. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2481. // so the badge only shows on printers that can actually run the queued jobs.
  2482. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2483. const queueCount = useMemo(() => {
  2484. if (!queueItems?.length) return 0;
  2485. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2486. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2487. // Fetch currently printing queue item to show who started it (Issue #206)
  2488. const { data: printingQueueItems } = useQuery({
  2489. queryKey: ['queue', printer.id, 'printing'],
  2490. queryFn: () => api.getQueue(printer.id, 'printing'),
  2491. enabled: status?.state === 'RUNNING',
  2492. });
  2493. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2494. const { data: reprintUser } = useQuery({
  2495. queryKey: ['currentPrintUser', printer.id],
  2496. queryFn: () => api.getCurrentPrintUser(printer.id),
  2497. enabled: status?.state === 'RUNNING',
  2498. });
  2499. // Combine both sources: queue item user takes precedence, then reprint user
  2500. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2501. // Fetch last completed print for this printer
  2502. const { data: lastPrints } = useQuery({
  2503. queryKey: ['archives', printer.id, 'last'],
  2504. queryFn: () => api.getArchives(printer.id, 1, 0),
  2505. enabled: status?.connected && status?.state !== 'RUNNING',
  2506. });
  2507. const lastPrint = lastPrints?.[0];
  2508. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2509. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2510. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2511. // gate is up and the just-finished print asked for a verdict, offer
  2512. // Good/Reject right where the operator releases the plate. Releasing the
  2513. // plate without answering stays possible — the two are orthogonal (though
  2514. // the confirm_default_good_on_plate_clear setting can couple them).
  2515. // Only offered to whoever may record it: the PATCH checks archives:update
  2516. // against the archive's owner, so for anyone else the pair could only fail.
  2517. const pendingConfirmArchive =
  2518. lastPrint &&
  2519. lastPrint.status === 'completed' &&
  2520. lastPrint.confirm_requested &&
  2521. lastPrint.user_verdict == null &&
  2522. canModify('archives', 'update', lastPrint.created_by_id)
  2523. ? lastPrint
  2524. : null;
  2525. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2526. // Auto Power Off the printer is powered down exactly when the operator clears the
  2527. // plate. Hiding the control there left no way to release the gate (#2864).
  2528. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2529. const activePrintName = status?.current_print && isPrintingOrPaused
  2530. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2531. : null;
  2532. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2533. useEffect(() => {
  2534. if (activePrintName) {
  2535. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2536. } else if (!needsPlateClear) {
  2537. setRetainedPrintJob(null);
  2538. }
  2539. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2540. const plateStatus = (() => {
  2541. // Connected-only because the pill's only render site sits inside the live-status
  2542. // panel. For a powered-down printer the plate-clear button itself carries the
  2543. // state — see the standalone slot below the status block (#2864).
  2544. if (!requirePlateClear || !status?.connected) return null;
  2545. if (isPrintingOrPaused) {
  2546. return {
  2547. label: t('printers.plateStatus.inUse'),
  2548. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2549. };
  2550. }
  2551. if (status.awaiting_plate_clear) {
  2552. return {
  2553. label: t('printers.plateStatus.notCleared'),
  2554. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2555. };
  2556. }
  2557. return {
  2558. label: t('printers.plateStatus.cleared'),
  2559. className: 'bg-status-ok/20 text-status-ok',
  2560. };
  2561. })();
  2562. const plateStatusPill = plateStatus ? (
  2563. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[length:var(--pc-t10,10px)] font-medium ${plateStatus.className}`}>
  2564. {plateStatus.label}
  2565. </span>
  2566. ) : null;
  2567. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2568. const shouldHide = hideIfDisconnected && isConnected === false;
  2569. const deleteMutation = useMutation({
  2570. mutationFn: (options: { deleteArchives: boolean }) =>
  2571. api.deletePrinter(printer.id, options.deleteArchives),
  2572. onSuccess: () => {
  2573. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2574. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2575. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2576. },
  2577. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2578. });
  2579. const connectMutation = useMutation({
  2580. mutationFn: () => api.connectPrinter(printer.id),
  2581. onSuccess: () => {
  2582. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2583. },
  2584. });
  2585. const forceRefreshMutation = useMutation({
  2586. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2587. onSuccess: () => {
  2588. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2589. showToast(t('printers.forceRefreshSuccess'), 'success');
  2590. },
  2591. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2592. });
  2593. const unlinkSpoolMutation = useMutation({
  2594. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2595. onSuccess: (result) => {
  2596. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2597. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2598. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2599. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2600. },
  2601. onError: (error: Error) => {
  2602. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2603. },
  2604. });
  2605. // AMS drying mutations
  2606. const startDryingMutation = useMutation({
  2607. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2608. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2609. onSuccess: (_data, { amsId }) => {
  2610. setDryingPopoverAmsId(null);
  2611. setDryStartWatch({ amsId });
  2612. // "Command sent", not "drying started" — at this point the printer has only
  2613. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2614. // the cycle is genuinely live; the watcher below covers the case where it
  2615. // never appears.
  2616. showToast(t('printers.drying.toastCommandSent'), 'success');
  2617. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2618. },
  2619. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2620. });
  2621. // Scheduled (delayed / at-time) drying runs (#2638)
  2622. const scheduleDryingMutation = useMutation({
  2623. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2624. api.createScheduledDrying({
  2625. printer_id: printer.id,
  2626. ams_id: params.amsId,
  2627. temp: params.temp,
  2628. duration_hours: params.duration,
  2629. filament: params.filament,
  2630. rotate_tray: params.rotateTray,
  2631. start_after: params.startAfter,
  2632. }),
  2633. onSuccess: () => {
  2634. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2635. setDryingPopoverAmsId(null);
  2636. },
  2637. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2638. });
  2639. const stopDryingMutation = useMutation({
  2640. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2641. onSuccess: () => {
  2642. setDryStartWatch(null);
  2643. showToast(t('printers.drying.toastStopped'), 'success');
  2644. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2645. },
  2646. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2647. });
  2648. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2649. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2650. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2651. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2652. // showing the old backup state until the user reopens it.
  2653. const setAmsBackupMutation = useMutation({
  2654. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2655. onSuccess: (_data, enabled) => {
  2656. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2657. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2658. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2659. },
  2660. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2661. });
  2662. // Smart plug control mutations
  2663. const powerControlMutation = useMutation({
  2664. mutationFn: (action: 'on' | 'off') =>
  2665. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2666. onSuccess: () => {
  2667. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2668. },
  2669. });
  2670. const toggleAutoOffMutation = useMutation({
  2671. mutationFn: (enabled: boolean) =>
  2672. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2673. onSuccess: () => {
  2674. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2675. // Also invalidate the smart-plugs list to keep Settings page in sync
  2676. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2677. },
  2678. });
  2679. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2680. const runScriptMutation = useMutation({
  2681. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2682. onSuccess: () => {
  2683. showToast(t('printers.toast.scriptTriggered'));
  2684. },
  2685. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2686. });
  2687. // Print control mutations
  2688. const stopPrintMutation = useMutation({
  2689. mutationFn: () => api.stopPrint(printer.id),
  2690. onSuccess: () => {
  2691. showToast(t('printers.toast.printStopped'));
  2692. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2693. },
  2694. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2695. });
  2696. const pausePrintMutation = useMutation({
  2697. mutationFn: () => api.pausePrint(printer.id),
  2698. onSuccess: () => {
  2699. showToast(t('printers.toast.printPaused'));
  2700. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2701. },
  2702. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2703. });
  2704. const resumePrintMutation = useMutation({
  2705. mutationFn: () => api.resumePrint(printer.id),
  2706. onSuccess: () => {
  2707. showToast(t('printers.toast.printResumed'));
  2708. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2709. },
  2710. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2711. });
  2712. const clearPlateMutation = useMutation({
  2713. mutationFn: () => api.clearPlate(printer.id),
  2714. onSuccess: () => {
  2715. showToast(t('queue.clearPlateSuccess'));
  2716. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2717. old ? { ...old, awaiting_plate_clear: false } : old
  2718. );
  2719. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2720. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2721. },
  2722. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2723. });
  2724. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2725. // reject goes through the dialog for the optional reason + reprint.
  2726. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2727. // Only "good" is answered on the card. A reject wants a reason and possibly
  2728. // a reprint, so that button opens the dialog instead — and the parameter
  2729. // says as much, rather than accepting a verdict this path cannot send and
  2730. // then reporting it as good.
  2731. const cardVerdictMutation = useMutation({
  2732. mutationFn: (verdict: 'good') =>
  2733. api.updateArchive(pendingConfirmArchive!.id, {
  2734. user_verdict: verdict,
  2735. user_verdict_source: 'printer_card',
  2736. }),
  2737. onSuccess: () => {
  2738. showToast(t('confirmOutcome.savedGood'), 'success');
  2739. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2740. },
  2741. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2742. });
  2743. // Rendered from two places: inside the live-status block for a connected printer,
  2744. // and standalone below it for a powered-down one, whose status block isn't rendered
  2745. // at all (#2864). Shared so the two can't drift apart.
  2746. const expandedClearPlateButton = (
  2747. <>
  2748. {pendingConfirmArchive && (
  2749. <div className="mt-2 flex items-center gap-1.5">
  2750. <span
  2751. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2752. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2753. >
  2754. {t('confirmOutcome.cardPrompt')}
  2755. </span>
  2756. <button
  2757. type="button"
  2758. onClick={() => setShowConfirmOutcome(true)}
  2759. disabled={cardVerdictMutation.isPending}
  2760. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2761. title={t('confirmOutcome.reject')}
  2762. >
  2763. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2764. </button>
  2765. <button
  2766. type="button"
  2767. onClick={() => cardVerdictMutation.mutate('good')}
  2768. disabled={cardVerdictMutation.isPending}
  2769. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2770. title={t('confirmOutcome.good')}
  2771. >
  2772. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2773. </button>
  2774. </div>
  2775. )}
  2776. <button
  2777. type="button"
  2778. onClick={() => clearPlateMutation.mutate()}
  2779. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2780. className="mt-2 w-full inline-flex items-center justify-center gap-2 px-3 py-1.5 rounded-lg bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-300 dark:border-yellow-400/40 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs font-medium disabled:opacity-50"
  2781. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2782. >
  2783. {clearPlateMutation.isPending ? (
  2784. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2785. ) : (
  2786. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2787. )}
  2788. {t('printers.plateStatus.markCleared')}
  2789. </button>
  2790. {showConfirmOutcome && pendingConfirmArchive && (
  2791. <ConfirmOutcomeDialog
  2792. archiveId={pendingConfirmArchive.id}
  2793. onClose={() => setShowConfirmOutcome(false)}
  2794. />
  2795. )}
  2796. </>
  2797. );
  2798. const nozzleTemperatureMutation = useMutation({
  2799. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2800. api.setNozzleTemperature(printer.id, target, nozzle),
  2801. onSuccess: (result) => {
  2802. setStatusControlMenu(null);
  2803. showToast(result.message);
  2804. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2805. },
  2806. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2807. });
  2808. const bedTemperatureMutation = useMutation({
  2809. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2810. onSuccess: (result) => {
  2811. setStatusControlMenu(null);
  2812. showToast(result.message);
  2813. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2814. },
  2815. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2816. });
  2817. const chamberTemperatureMutation = useMutation({
  2818. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2819. onSuccess: (result) => {
  2820. setStatusControlMenu(null);
  2821. showToast(result.message);
  2822. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2823. },
  2824. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2825. });
  2826. const fanSpeedMutation = useMutation({
  2827. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2828. api.setFanSpeed(printer.id, fan, speed),
  2829. onMutate: async ({ fan, speed }) => {
  2830. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2831. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2832. const fanField = {
  2833. part: 'cooling_fan_speed',
  2834. aux: 'big_fan1_speed',
  2835. aux2: 'left_aux_fan_speed',
  2836. chamber: 'big_fan2_speed',
  2837. }[fan];
  2838. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2839. old ? { ...old, [fanField]: speed } : old
  2840. );
  2841. return { previousStatus };
  2842. },
  2843. onSuccess: (result) => {
  2844. setStatusControlMenu(null);
  2845. showToast(result.message);
  2846. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2847. },
  2848. onError: (error: Error, _variables, context) => {
  2849. if (context?.previousStatus) {
  2850. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2851. }
  2852. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2853. },
  2854. });
  2855. const selectExtruderMutation = useMutation({
  2856. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2857. onMutate: async (extruder) => {
  2858. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2859. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2860. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2861. old ? { ...old, active_extruder: extruder } : old
  2862. );
  2863. return { previousStatus };
  2864. },
  2865. onSuccess: (result) => {
  2866. setStatusControlMenu(null);
  2867. showToast(result.message);
  2868. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2869. },
  2870. onError: (error: Error, _extruder, context) => {
  2871. if (context?.previousStatus) {
  2872. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2873. }
  2874. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2875. },
  2876. });
  2877. // Chamber light mutation with optimistic update
  2878. const chamberLightMutation = useMutation({
  2879. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2880. onMutate: async (on) => {
  2881. // Cancel any outgoing refetches
  2882. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2883. // Snapshot the previous value
  2884. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2885. // Optimistically update
  2886. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2887. ...old,
  2888. chamber_light: on,
  2889. }));
  2890. return { previousStatus };
  2891. },
  2892. onSuccess: (_, on) => {
  2893. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2894. },
  2895. onError: (error: Error, _, context) => {
  2896. // Rollback on error
  2897. if (context?.previousStatus) {
  2898. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2899. }
  2900. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2901. },
  2902. });
  2903. // Print speed mutation with optimistic update
  2904. const printSpeedMutation = useMutation({
  2905. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2906. onMutate: async (mode) => {
  2907. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2908. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2909. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2910. ...old,
  2911. speed_level: mode,
  2912. }));
  2913. return { previousStatus };
  2914. },
  2915. onError: (error: Error, _, context) => {
  2916. if (context?.previousStatus) {
  2917. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2918. }
  2919. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2920. },
  2921. });
  2922. const airductMutation = useMutation({
  2923. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2924. onMutate: async (mode) => {
  2925. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2926. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2927. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2928. ...old,
  2929. airduct_mode: mode === 'cooling' ? 0 : 1,
  2930. }));
  2931. return { previousStatus };
  2932. },
  2933. onError: (error: Error, _, context) => {
  2934. if (context?.previousStatus) {
  2935. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2936. }
  2937. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2938. },
  2939. });
  2940. const bedJogMutation = useMutation({
  2941. mutationFn: ({ distance }: { distance: number }) =>
  2942. api.bedJog(printer.id, distance),
  2943. onError: (error: Error) =>
  2944. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2945. });
  2946. const xyJogMutation = useMutation({
  2947. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2948. api.xyJog(printer.id, x, y),
  2949. onError: (error: Error) =>
  2950. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2951. });
  2952. const extruderJogMutation = useMutation({
  2953. mutationFn: (distance: number) =>
  2954. api.extruderJog(printer.id, distance),
  2955. onError: (error: Error) =>
  2956. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2957. });
  2958. const homeAxesMutation = useMutation({
  2959. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2960. onSuccess: () => {
  2961. showToast(t('printers.bedJog.homingStarted'));
  2962. },
  2963. onError: (error: Error) =>
  2964. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2965. });
  2966. // Plate detection setting mutation
  2967. const plateDetectionMutation = useMutation({
  2968. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2969. onSuccess: () => {
  2970. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2971. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2972. },
  2973. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2974. });
  2975. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2976. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2977. // metrics, and the print picker — so flipping this flag puts the printer
  2978. // out of service across every consumer in one place. Used from the
  2979. // overflow menu and EditPrinterModal.
  2980. const maintenanceMutation = useMutation({
  2981. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2982. onSuccess: (_data, isActive) => {
  2983. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2984. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2985. showToast(
  2986. isActive
  2987. ? t('printers.maintenance.toastExited', { name: printer.name })
  2988. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2989. 'success',
  2990. );
  2991. },
  2992. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2993. });
  2994. // Confirm before entering maintenance on a printing printer (entering mode
  2995. // disconnects MQTT, which stops progress tracking + completion notifications
  2996. // for the in-flight job).
  2997. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2998. const handleEnterMaintenance = () => {
  2999. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  3000. setConfirmMaintenanceEnter(true);
  3001. } else {
  3002. maintenanceMutation.mutate(false);
  3003. }
  3004. };
  3005. // Query for printable objects (for skip functionality)
  3006. // Fetch when printing with 2+ objects OR when modal is open
  3007. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  3008. const { data: objectsData } = useQuery({
  3009. queryKey: ['printableObjects', printer.id],
  3010. queryFn: () => api.getPrintableObjects(printer.id),
  3011. enabled: showSkipObjectsModal || isPrintingWithObjects,
  3012. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  3013. });
  3014. // State for tracking which AMS slot is being refreshed
  3015. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  3016. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  3017. const seenBusyStateRef = useRef<boolean>(false);
  3018. // Fallback timeout ref
  3019. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3020. // Minimum display time passed
  3021. const minTimePassedRef = useRef<boolean>(false);
  3022. // AMS slot refresh mutation
  3023. const refreshAmsSlotMutation = useMutation({
  3024. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  3025. api.refreshAmsSlot(printer.id, amsId, slotId),
  3026. onMutate: ({ amsId, slotId }) => {
  3027. // Clear any existing timeout
  3028. if (refreshTimeoutRef.current) {
  3029. clearTimeout(refreshTimeoutRef.current);
  3030. }
  3031. // Reset state
  3032. seenBusyStateRef.current = false;
  3033. minTimePassedRef.current = false;
  3034. setRefreshingSlot({ amsId, slotId });
  3035. // Minimum display time (2 seconds)
  3036. setTimeout(() => {
  3037. minTimePassedRef.current = true;
  3038. }, 2000);
  3039. // Fallback timeout (30 seconds max)
  3040. refreshTimeoutRef.current = setTimeout(() => {
  3041. setRefreshingSlot(null);
  3042. }, 30000);
  3043. },
  3044. onSuccess: (data) => {
  3045. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  3046. },
  3047. onError: (error: Error) => {
  3048. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  3049. if (refreshTimeoutRef.current) {
  3050. clearTimeout(refreshTimeoutRef.current);
  3051. }
  3052. setRefreshingSlot(null);
  3053. },
  3054. });
  3055. // AMS load/unload mutations (#891)
  3056. const loadAmsTrayMutation = useMutation({
  3057. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  3058. api.loadAmsTray(printer.id, trayId, extruderId),
  3059. onSuccess: (data) => {
  3060. setFeedDirectionRequest(null);
  3061. showToast(data.message || t('printers.toast.loadInitiated'));
  3062. },
  3063. onError: (error: Error) => {
  3064. setFeedDirectionRequest(null);
  3065. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  3066. },
  3067. });
  3068. const unloadAmsMutation = useMutation({
  3069. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3070. onSuccess: (data) => {
  3071. showToast(data.message || t('printers.toast.unloadInitiated'));
  3072. },
  3073. onError: (error: Error) => {
  3074. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3075. },
  3076. });
  3077. // Pending "which hotend?" question, non-null only while the dialog is open.
  3078. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3079. // load command has to name one — see FeedDirectionModal.
  3080. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3081. trayId: number;
  3082. amsId: number;
  3083. slotId: number;
  3084. slotLabel: string;
  3085. } | null>(null);
  3086. // Whether a load from this printer has to ask which hotend to feed.
  3087. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3088. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3089. // The external holder needs no question: its two tray ids name the side
  3090. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3091. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3092. // external spool, because it would occupy an extruder channel permanently.
  3093. //
  3094. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3095. // carries does not address an HT unit, so the load is refused whatever the
  3096. // answer. Asking first would only put a dialog in front of the same error.
  3097. const isExternal = amsId === 255;
  3098. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3099. loadAmsTrayMutation.mutate({ trayId });
  3100. return;
  3101. }
  3102. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3103. // front rather than sending a command the firmware will drop. BambuStudio
  3104. // shows the same message and returns without publishing anything.
  3105. if (!status?.fila_switch?.ready) {
  3106. showToast(t('printers.ams.switchNotReady'), 'warning');
  3107. return;
  3108. }
  3109. setFeedDirectionRequest({
  3110. trayId,
  3111. amsId,
  3112. slotId,
  3113. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3114. });
  3115. };
  3116. // Plate references state
  3117. const [plateReferences, setPlateReferences] = useState<{
  3118. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3119. max_references: number;
  3120. } | null>(null);
  3121. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3122. // Fetch plate references
  3123. const fetchPlateReferences = async () => {
  3124. try {
  3125. const data = await api.getPlateReferences(printer.id);
  3126. setPlateReferences(data);
  3127. } catch {
  3128. // Ignore errors - references will show as empty
  3129. }
  3130. };
  3131. // Toggle plate detection enabled/disabled
  3132. const handleTogglePlateDetection = () => {
  3133. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3134. };
  3135. // Open plate detection management modal (for calibration/references)
  3136. const handleOpenPlateManagement = async () => {
  3137. setIsCheckingPlate(true);
  3138. setPlateCheckResult(null);
  3139. // Auto-turn on light if it's off
  3140. const lightWasOff = status?.chamber_light === false;
  3141. setPlateCheckLightWasOff(lightWasOff);
  3142. if (lightWasOff) {
  3143. await api.setChamberLight(printer.id, true);
  3144. // Wait for light to physically turn on and camera to adjust exposure
  3145. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3146. await new Promise(resolve => setTimeout(resolve, 2500));
  3147. }
  3148. try {
  3149. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3150. setPlateCheckResult(result);
  3151. fetchPlateReferences();
  3152. } catch (error) {
  3153. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3154. // Restore light if check failed
  3155. if (lightWasOff) {
  3156. await api.setChamberLight(printer.id, false);
  3157. setPlateCheckLightWasOff(false);
  3158. }
  3159. } finally {
  3160. setIsCheckingPlate(false);
  3161. }
  3162. };
  3163. // Close plate check modal and restore light state
  3164. const closePlateCheckModal = useCallback(async () => {
  3165. setPlateCheckResult(null);
  3166. // Restore light to original state if we turned it on
  3167. if (plateCheckLightWasOff) {
  3168. await api.setChamberLight(printer.id, false);
  3169. setPlateCheckLightWasOff(false);
  3170. }
  3171. }, [plateCheckLightWasOff, printer.id]);
  3172. // Calibrate plate detection handler
  3173. const handleCalibratePlate = async (label?: string) => {
  3174. setIsCalibrating(true);
  3175. try {
  3176. const result = await api.calibratePlateDetection(printer.id, { label });
  3177. if (result.success) {
  3178. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3179. // Refresh references and re-check
  3180. fetchPlateReferences();
  3181. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3182. setPlateCheckResult(checkResult);
  3183. } else {
  3184. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3185. }
  3186. } catch (error) {
  3187. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3188. } finally {
  3189. setIsCalibrating(false);
  3190. }
  3191. };
  3192. // Update reference label
  3193. const handleUpdateRefLabel = async (index: number, label: string) => {
  3194. try {
  3195. await api.updatePlateReferenceLabel(printer.id, index, label);
  3196. setEditingRefLabel(null);
  3197. fetchPlateReferences();
  3198. } catch (error) {
  3199. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3200. }
  3201. };
  3202. // Delete reference
  3203. const handleDeleteRef = async (index: number) => {
  3204. try {
  3205. await api.deletePlateReference(printer.id, index);
  3206. showToast(t('printers.toast.referenceDeleted'), 'success');
  3207. fetchPlateReferences();
  3208. // Re-check to update counts
  3209. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3210. setPlateCheckResult(checkResult);
  3211. } catch (error) {
  3212. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3213. }
  3214. };
  3215. // Save ROI settings
  3216. const handleSaveRoi = async () => {
  3217. if (!editingRoi) return;
  3218. setIsSavingRoi(true);
  3219. try {
  3220. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3221. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3222. setEditingRoi(null);
  3223. // Re-check to see new ROI in action
  3224. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3225. setPlateCheckResult(checkResult);
  3226. } catch (error) {
  3227. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3228. } finally {
  3229. setIsSavingRoi(false);
  3230. }
  3231. };
  3232. // Close plate check modal on Escape key
  3233. useEffect(() => {
  3234. const handleEscape = (e: KeyboardEvent) => {
  3235. if (e.key === 'Escape' && plateCheckResult) {
  3236. closePlateCheckModal();
  3237. }
  3238. };
  3239. window.addEventListener('keydown', handleEscape);
  3240. return () => window.removeEventListener('keydown', handleEscape);
  3241. }, [plateCheckResult, closePlateCheckModal]);
  3242. // Watch ams_status_main to detect when RFID read completes
  3243. // ams_status_main: 0=idle, 2=rfid_identifying
  3244. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3245. useEffect(() => {
  3246. if (!refreshingSlot) return;
  3247. const amsStatus = status?.ams_status_main ?? 0;
  3248. // Track when we see non-idle state (printer is working)
  3249. if (amsStatus !== 0) {
  3250. seenBusyStateRef.current = true;
  3251. // Cancel any deferred clear since we're back to busy
  3252. if (deferredClearRef.current) {
  3253. clearTimeout(deferredClearRef.current);
  3254. deferredClearRef.current = null;
  3255. }
  3256. }
  3257. // When we've seen busy and now idle, clear (with min time check)
  3258. if (seenBusyStateRef.current && amsStatus === 0) {
  3259. if (minTimePassedRef.current) {
  3260. // Min time passed - clear now
  3261. if (refreshTimeoutRef.current) {
  3262. clearTimeout(refreshTimeoutRef.current);
  3263. }
  3264. setRefreshingSlot(null);
  3265. } else {
  3266. // Schedule clear after min time (2 seconds from start)
  3267. if (!deferredClearRef.current) {
  3268. deferredClearRef.current = setTimeout(() => {
  3269. if (refreshTimeoutRef.current) {
  3270. clearTimeout(refreshTimeoutRef.current);
  3271. }
  3272. setRefreshingSlot(null);
  3273. }, 2000);
  3274. }
  3275. }
  3276. }
  3277. return () => {
  3278. if (deferredClearRef.current) {
  3279. clearTimeout(deferredClearRef.current);
  3280. }
  3281. };
  3282. }, [status?.ams_status_main, refreshingSlot]);
  3283. useEffect(() => {
  3284. if (!showMenu) return;
  3285. const handleClickOutside = (event: MouseEvent) => {
  3286. const target = event.target as Node;
  3287. if (!printerActionsMenuRef.current?.contains(target)) {
  3288. setShowMenu(false);
  3289. }
  3290. };
  3291. document.addEventListener('mousedown', handleClickOutside);
  3292. return () => document.removeEventListener('mousedown', handleClickOutside);
  3293. }, [showMenu]);
  3294. if (shouldHide) {
  3295. return null;
  3296. }
  3297. // Size-based styling helpers
  3298. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3299. // width, its thumbnail and the printer name, but every label inside the
  3300. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3301. // S one -- the disparity was worst exactly where someone asking for more
  3302. // room ends up. These custom properties carry the scaled sizes into the
  3303. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3304. // unless they reach for a size that is already asking for more space.
  3305. // Plain computation rather than useMemo: this sits after the card's early
  3306. // returns, where a hook would break the rules-of-hooks ordering, and
  3307. // building ten strings per render costs nothing.
  3308. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3309. const getImageSize = () => {
  3310. switch (cardSize) {
  3311. case 1: return 'w-10 h-10';
  3312. case 2: return 'w-14 h-14';
  3313. case 3: return 'w-16 h-16';
  3314. case 4: return 'w-20 h-20';
  3315. default: return 'w-14 h-14';
  3316. }
  3317. };
  3318. const getTitleSize = () => {
  3319. switch (cardSize) {
  3320. case 1: return 'text-base truncate';
  3321. case 2: return 'text-lg';
  3322. case 3: return 'text-xl';
  3323. case 4: return 'text-2xl';
  3324. default: return 'text-lg';
  3325. }
  3326. };
  3327. const getSpacing = () => {
  3328. switch (cardSize) {
  3329. case 1: return 'mb-2';
  3330. case 2: return 'mb-4';
  3331. case 3: return 'mb-5';
  3332. case 4: return 'mb-6';
  3333. default: return 'mb-4';
  3334. }
  3335. };
  3336. // A dropped file always becomes a queue item, so a printer that is busy,
  3337. // offline or mid-drying is no reason to refuse the drop — it only means the
  3338. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3339. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3340. // what this would have done for them.
  3341. //
  3342. // What remains is what the flow actually performs: upload the file, then
  3343. // create a queue item. It never touches printers:control, which is what this
  3344. // used to check — so someone holding that but neither of these had the file
  3345. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3346. // button below has always checked this pair.
  3347. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3348. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3349. // and the modal's own "will start later" toast cannot disagree.
  3350. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3351. const handleCardDragEnter = (e: React.DragEvent) => {
  3352. e.preventDefault();
  3353. dragCounterRef.current++;
  3354. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3355. };
  3356. const handleCardDragOver = (e: React.DragEvent) => {
  3357. e.preventDefault();
  3358. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3359. };
  3360. const handleCardDragLeave = (e: React.DragEvent) => {
  3361. e.preventDefault();
  3362. dragCounterRef.current--;
  3363. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3364. };
  3365. const handleCardDrop = async (e: React.DragEvent) => {
  3366. e.preventDefault();
  3367. dragCounterRef.current = 0;
  3368. setIsDraggingFile(false);
  3369. if (!canDrop) return;
  3370. const droppedFiles = Array.from(e.dataTransfer.files);
  3371. const file = droppedFiles[0];
  3372. if (!file) return;
  3373. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3374. const lower = file.name.toLowerCase();
  3375. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3376. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3377. return;
  3378. }
  3379. setIsDropUploading(true);
  3380. try {
  3381. const result = await api.uploadLibraryFile(file, null);
  3382. // Check printer compatibility if sliced_for_model is available in metadata
  3383. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3384. const printerModel = mapModelCode(printer.model);
  3385. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3386. await api.deleteLibraryFile(result.id).catch(() => {});
  3387. showToast(
  3388. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3389. 'error'
  3390. );
  3391. return;
  3392. }
  3393. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3394. } catch {
  3395. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3396. } finally {
  3397. setIsDropUploading(false);
  3398. }
  3399. };
  3400. const handleCardClick = (e: React.MouseEvent) => {
  3401. if (viewMode !== 'compact' || selectionMode) return;
  3402. const target = e.target as HTMLElement;
  3403. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3404. onOpenCompactCard?.(printer.id);
  3405. };
  3406. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3407. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3408. // Opening a camera in a given mode, without touching which mode is remembered
  3409. // -- the split button's two halves want the same action but disagree about
  3410. // whether the choice was deliberate enough to keep.
  3411. const openCameraIn = (mode: CameraViewMode) => {
  3412. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3413. onOpenEmbeddedCamera(printer.id, printer.name);
  3414. } else {
  3415. openCameraWindow(printer.id);
  3416. }
  3417. };
  3418. // Picking a mode both opens the camera that way and makes it the mode the
  3419. // plain icon uses from now on. A menu that only changed a preference would
  3420. // leave the user with a second click to do the thing they already asked for.
  3421. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3422. [
  3423. {
  3424. mode: 'window' as const,
  3425. icon: <ExternalLink className="w-4 h-4" />,
  3426. label: t('settings.newWindow'),
  3427. title: t('settings.cameraWindowDescription'),
  3428. },
  3429. {
  3430. mode: 'embedded' as const,
  3431. icon: <PictureInPicture2 className="w-4 h-4" />,
  3432. label: t('settings.embeddedOverlay'),
  3433. title: t('settings.cameraOverlayDescription'),
  3434. },
  3435. ]
  3436. ).map(({ mode, icon, label, title }) => ({
  3437. icon,
  3438. // The remembered mode is marked in the label itself: the icon slot already
  3439. // carries the mode's own icon, and a separate tick column would push both
  3440. // entries out of line with every other card menu.
  3441. label: mode === cameraViewMode ? `${label} ✓` : label,
  3442. title,
  3443. onClick: () => {
  3444. onSelectCameraViewMode?.(mode);
  3445. openCameraIn(mode);
  3446. },
  3447. }));
  3448. const renderAmsSlotActions = ({
  3449. amsId,
  3450. slotId,
  3451. loadTrayId,
  3452. isRefreshing,
  3453. includeRfid = true,
  3454. }: {
  3455. amsId: number;
  3456. slotId: number;
  3457. loadTrayId: number;
  3458. isRefreshing?: boolean;
  3459. includeRfid?: boolean;
  3460. }) => {
  3461. const printerBusy = status?.state === 'RUNNING';
  3462. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3463. // ams*4+slot, so the id this menu carries does not name it to the load and
  3464. // unload endpoints — they reject it. Sending no slot falls back to the
  3465. // printer-wide unload, which is what this menu did for every slot before
  3466. // the per-slot form existed. Load has never worked on an HT slot for the
  3467. // same addressing reason; fixing that is a separate change.
  3468. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3469. return (
  3470. <>
  3471. {includeRfid && (
  3472. <button
  3473. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3474. hasPermission('printers:ams_rfid')
  3475. ? 'text-white hover:bg-bambu-dark-tertiary'
  3476. : 'text-bambu-gray/50 cursor-not-allowed'
  3477. }`}
  3478. onClick={(e) => {
  3479. e.stopPropagation();
  3480. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3481. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3482. }}
  3483. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3484. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3485. >
  3486. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3487. {t('printers.rfid.reread')}
  3488. </button>
  3489. )}
  3490. <button
  3491. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3492. hasPermission('printers:control')
  3493. ? 'text-white hover:bg-bambu-dark-tertiary'
  3494. : 'text-bambu-gray/50 cursor-not-allowed'
  3495. }`}
  3496. onClick={(e) => {
  3497. e.stopPropagation();
  3498. if (printerBusy || !hasPermission('printers:control')) return;
  3499. startAmsLoad(amsId, slotId, loadTrayId);
  3500. }}
  3501. disabled={printerBusy || !hasPermission('printers:control')}
  3502. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3503. >
  3504. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3505. {t('printers.ams.load')}
  3506. </button>
  3507. <button
  3508. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3509. hasPermission('printers:control')
  3510. ? 'text-white hover:bg-bambu-dark-tertiary'
  3511. : 'text-bambu-gray/50 cursor-not-allowed'
  3512. }`}
  3513. onClick={(e) => {
  3514. e.stopPropagation();
  3515. if (printerBusy || !hasPermission('printers:control')) return;
  3516. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3517. }}
  3518. disabled={printerBusy || !hasPermission('printers:control')}
  3519. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3520. >
  3521. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3522. {t('printers.ams.unload')}
  3523. </button>
  3524. </>
  3525. );
  3526. };
  3527. const printerActionsMenu = (
  3528. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3529. <Button
  3530. variant="secondary"
  3531. size="sm"
  3532. onClick={() => setShowMenu(!showMenu)}
  3533. title={t('common.more', 'More')}
  3534. className={footerIconButtonClass}
  3535. >
  3536. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3537. </Button>
  3538. {showMenu && (
  3539. <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">
  3540. <button
  3541. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3542. hasPermission('printers:update')
  3543. ? 'hover:bg-bambu-dark-tertiary'
  3544. : 'opacity-50 cursor-not-allowed'
  3545. }`}
  3546. onClick={() => {
  3547. if (!hasPermission('printers:update')) return;
  3548. setShowEditModal(true);
  3549. setShowMenu(false);
  3550. }}
  3551. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3552. >
  3553. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3554. {t('common.edit')}
  3555. </button>
  3556. <button
  3557. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3558. onClick={() => {
  3559. setShowPrinterInfo(true);
  3560. setShowMenu(false);
  3561. }}
  3562. >
  3563. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3564. {t('printers.printerInformation')}
  3565. </button>
  3566. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3567. <button
  3568. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3569. hasPermission('printers:update')
  3570. ? 'hover:bg-bambu-dark-tertiary'
  3571. : 'opacity-50 cursor-not-allowed'
  3572. }`}
  3573. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3574. onClick={() => {
  3575. if (!hasPermission('printers:update')) return;
  3576. setShowMenu(false);
  3577. if (printer.is_active !== false) {
  3578. handleEnterMaintenance();
  3579. } else {
  3580. maintenanceMutation.mutate(true);
  3581. }
  3582. }}
  3583. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3584. >
  3585. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3586. {printer.is_active !== false
  3587. ? t('printers.maintenance.menuEnter')
  3588. : t('printers.maintenance.menuExit')}
  3589. </button>
  3590. <button
  3591. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3592. onClick={() => {
  3593. connectMutation.mutate();
  3594. setShowMenu(false);
  3595. }}
  3596. >
  3597. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3598. {t('printers.reconnect')}
  3599. </button>
  3600. <button
  3601. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3602. disabled={forceRefreshMutation.isPending}
  3603. onClick={() => {
  3604. forceRefreshMutation.mutate();
  3605. setShowMenu(false);
  3606. }}
  3607. >
  3608. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3609. {t('printers.forceRefresh')}
  3610. </button>
  3611. <button
  3612. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3613. onClick={() => {
  3614. setShowMQTTDebug(true);
  3615. setShowMenu(false);
  3616. }}
  3617. >
  3618. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3619. {t('printers.mqttDebug')}
  3620. </button>
  3621. <button
  3622. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3623. onClick={() => {
  3624. setShowDiagnostic(true);
  3625. setShowMenu(false);
  3626. }}
  3627. >
  3628. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3629. {t('diagnostic.runButton')}
  3630. </button>
  3631. <button
  3632. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3633. hasPermission('printers:delete')
  3634. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3635. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3636. }`}
  3637. onClick={() => {
  3638. if (!hasPermission('printers:delete')) return;
  3639. setShowDeleteConfirm(true);
  3640. setShowMenu(false);
  3641. }}
  3642. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3643. >
  3644. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3645. {t('common.delete')}
  3646. </button>
  3647. </div>
  3648. )}
  3649. </div>
  3650. );
  3651. return (
  3652. <Card
  3653. id={`printer-card-${printer.id}`}
  3654. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3655. style={cardScaleStyle}
  3656. onClick={handleCardClick}
  3657. onDragEnter={handleCardDragEnter}
  3658. onDragOver={handleCardDragOver}
  3659. onDragLeave={handleCardDragLeave}
  3660. onDrop={handleCardDrop}
  3661. >
  3662. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3663. {selectionMode && (
  3664. <div
  3665. className="absolute inset-0 z-20 flex items-start p-2"
  3666. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3667. >
  3668. {isSelected ? (
  3669. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3670. ) : (
  3671. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3672. )}
  3673. </div>
  3674. )}
  3675. {/* Drop zone overlay */}
  3676. {(isDraggingFile || isDropUploading) && (
  3677. <div
  3678. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3679. isDropUploading
  3680. ? 'bg-bambu-green/10 border-bambu-green/50'
  3681. : canDrop
  3682. ? 'bg-bambu-green/10 border-bambu-green'
  3683. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3684. }`}
  3685. >
  3686. <div className="text-center">
  3687. {isDropUploading ? (
  3688. <>
  3689. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3690. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3691. </>
  3692. ) : canDrop ? (
  3693. <>
  3694. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3695. <p className="text-sm font-medium text-bambu-green">
  3696. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3697. </p>
  3698. </>
  3699. ) : (
  3700. <>
  3701. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3702. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3703. {!hasPermission('library:upload')
  3704. ? t('fileManager.noPermissionUpload')
  3705. : t('fileManager.noPermissionAddToQueue')}
  3706. </p>
  3707. </>
  3708. )}
  3709. </div>
  3710. </div>
  3711. )}
  3712. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3713. {/* Header */}
  3714. <div className={getSpacing()}>
  3715. {/* Top row: Image, Name, Menu */}
  3716. <div className="flex items-start justify-between gap-2">
  3717. <div className="flex items-center gap-3 min-w-0 flex-1">
  3718. {/* Printer Model Image */}
  3719. <img
  3720. src={getPrinterImage(printer.model)}
  3721. alt={printer.model || t('common.printer')}
  3722. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3723. />
  3724. <div className="min-w-0 flex-1">
  3725. <div className="flex items-center justify-between gap-2">
  3726. <div className="flex min-w-0 items-center gap-2">
  3727. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3728. {/* Connection indicator dot for compact mode */}
  3729. {viewMode === 'compact' && (() => {
  3730. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3731. const hasSevere = hmsErrors.some(isSevereHMSError);
  3732. const hasWarning = hmsErrors.length > 0;
  3733. const pipColor = !status?.connected
  3734. ? 'bg-status-error'
  3735. : hasSevere
  3736. ? 'bg-status-error'
  3737. : hasWarning
  3738. ? 'bg-status-warning'
  3739. : 'bg-status-ok';
  3740. const pipTitle = !status?.connected
  3741. ? t('printers.connection.offline')
  3742. : hasWarning
  3743. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3744. : t('printers.connection.connected');
  3745. return (
  3746. <div
  3747. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3748. title={pipTitle}
  3749. />
  3750. );
  3751. })()}
  3752. </div>
  3753. {viewMode === 'compact' && showClearPlateButton && (
  3754. <button
  3755. type="button"
  3756. onClick={() => clearPlateMutation.mutate()}
  3757. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3758. aria-label={t('printers.plateStatus.markCleared')}
  3759. className="inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-md bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-300 dark:border-yellow-400/40 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30 transition-colors disabled:opacity-50"
  3760. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3761. >
  3762. {clearPlateMutation.isPending ? (
  3763. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3764. ) : (
  3765. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3766. )}
  3767. </button>
  3768. )}
  3769. </div>
  3770. <p className="text-sm text-bambu-gray">
  3771. {printer.model || 'Unknown Model'}
  3772. {/* Nozzle Info - only in expanded. Every fitted size, not
  3773. just nozzles[0]: the array is indexed by extruder, so on a
  3774. dual-nozzle machine with two sizes fitted showing the
  3775. first entry alone named one hotend and implied it was the
  3776. whole printer. Deduplicated, so the usual matching pair
  3777. still reads as a single "0.4mm". */}
  3778. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3779. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3780. • {installedNozzleDiameters(status).join(' / ')}mm
  3781. </span>
  3782. )}
  3783. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3784. <span className="ml-2 text-bambu-gray">
  3785. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3786. {Math.round(maintenanceInfo.total_print_hours)}h
  3787. </span>
  3788. )}
  3789. </p>
  3790. </div>
  3791. </div>
  3792. </div>
  3793. {/* Badges row - only in expanded mode */}
  3794. {viewMode === 'expanded' && (
  3795. <div className="mt-2">
  3796. <div className="flex flex-wrap items-center gap-2">
  3797. {/* Connection status badge (or Maintenance pill when out of service).
  3798. Defensive: only swap when is_active is EXPLICITLY false. An
  3799. undefined / missing field defaults to "active" so the regular
  3800. pill renders — matches the backend default and prevents test
  3801. fixtures (or stale clients) from accidentally tripping the
  3802. maintenance UI. */}
  3803. {printer.is_active === false ? (
  3804. <span
  3805. className="flex items-center gap-1.5 px-2 py-1 rounded-full text-xs bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400"
  3806. title={t('printers.maintenance.subtitle')}
  3807. >
  3808. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3809. {t('printers.maintenance.pillLabel')}
  3810. </span>
  3811. ) : (
  3812. <span
  3813. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3814. status?.connected
  3815. ? 'bg-status-ok/20 text-status-ok'
  3816. : 'bg-status-error/20 text-status-error'
  3817. }`}
  3818. >
  3819. {status?.connected ? (
  3820. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3821. ) : (
  3822. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3823. )}
  3824. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3825. </span>
  3826. )}
  3827. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3828. {printer.is_active !== false && !status?.connected && (
  3829. <button
  3830. onClick={() => setShowDiagnostic(true)}
  3831. 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"
  3832. title={t('diagnostic.runButton')}
  3833. >
  3834. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3835. {t('diagnostic.runButton')}
  3836. </button>
  3837. )}
  3838. {/* Network connection indicator */}
  3839. {status?.connected && status?.wired_network && (
  3840. <span
  3841. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3842. title={t('printers.connection.ethernet', 'Ethernet')}
  3843. >
  3844. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3845. {t('printers.connection.ethernet', 'Ethernet')}
  3846. </span>
  3847. )}
  3848. {/* WiFi signal indicator */}
  3849. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3850. <span
  3851. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3852. wifiSignal >= -50
  3853. ? 'bg-status-ok/20 text-status-ok'
  3854. : wifiSignal >= -60
  3855. ? 'bg-status-ok/20 text-status-ok'
  3856. : wifiSignal >= -70
  3857. ? 'bg-status-warning/20 text-status-warning'
  3858. : wifiSignal >= -80
  3859. ? 'bg-orange-500/20 text-orange-600'
  3860. : 'bg-status-error/20 text-status-error'
  3861. }`}
  3862. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3863. >
  3864. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3865. {wifiSignal}dBm
  3866. </span>
  3867. )}
  3868. {/* HMS Status Indicator */}
  3869. {status?.connected && (() => {
  3870. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3871. return (
  3872. <button
  3873. onClick={() => setShowHMSModal(true)}
  3874. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3875. knownErrors.length > 0
  3876. ? knownErrors.some(isSevereHMSError)
  3877. ? 'bg-status-error/20 text-status-error'
  3878. : 'bg-status-warning/20 text-status-warning'
  3879. : 'bg-status-ok/20 text-status-ok'
  3880. }`}
  3881. title={t('printers.clickToViewHmsErrors')}
  3882. >
  3883. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3884. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3885. </button>
  3886. );
  3887. })()}
  3888. {/* AI failure detection badge (#1546) — always shown while detection
  3889. is enabled for this printer, like the other health badges. Gray
  3890. "Idle" outside a monitored print, class-colored during one. */}
  3891. {aiDetectionEnabled && (() => {
  3892. const cls = aiDetectionClass(aiDetection);
  3893. const colorClass =
  3894. cls === 'failure'
  3895. ? 'bg-status-error/20 text-status-error'
  3896. : cls === 'warning'
  3897. ? 'bg-status-warning/20 text-status-warning'
  3898. : cls === 'safe'
  3899. ? 'bg-status-ok/20 text-status-ok'
  3900. : cls === 'error'
  3901. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3902. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3903. // 'error' and 'unknown' have no score to quote — saying
  3904. // "Safe (0.000)" for a print nothing is looking at is the
  3905. // whole of #2952.
  3906. const title =
  3907. cls === 'error'
  3908. ? t('printers.aiDetection.tooltipError', {
  3909. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3910. })
  3911. : cls === 'unknown'
  3912. ? t('printers.aiDetection.tooltipUnknown')
  3913. : aiDetection
  3914. ? t('printers.aiDetection.tooltip', {
  3915. status: t(`printers.aiDetection.${cls}`),
  3916. score: aiDetection.score.toFixed(3),
  3917. })
  3918. : t('printers.aiDetection.tooltipIdle');
  3919. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3920. return (
  3921. <button
  3922. onClick={() => setShowAiModal(true)}
  3923. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3924. title={title}
  3925. >
  3926. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3927. {t(`printers.aiDetection.${cls}`)}
  3928. </button>
  3929. );
  3930. })()}
  3931. {/* Maintenance Status Indicator */}
  3932. {maintenanceInfo && (
  3933. <button
  3934. onClick={() => navigate('/maintenance')}
  3935. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3936. maintenanceInfo.due_count > 0
  3937. ? 'bg-status-error/20 text-status-error'
  3938. : maintenanceInfo.warning_count > 0
  3939. ? 'bg-status-warning/20 text-status-warning'
  3940. : 'bg-status-ok/20 text-status-ok'
  3941. }`}
  3942. title={
  3943. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3944. ? `${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`
  3945. : t('printers.maintenanceUpToDate')
  3946. }
  3947. >
  3948. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3949. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3950. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3951. : 'OK'}
  3952. </button>
  3953. )}
  3954. {/* Queue Count Badge */}
  3955. {queueCount > 0 && (
  3956. <button
  3957. onClick={() => navigate('/queue')}
  3958. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-indigo-100 dark:bg-indigo-500/20 text-indigo-700 dark:text-indigo-400 hover:opacity-80 transition-opacity"
  3959. title={t('printers.queue.inQueue', { count: queueCount })}
  3960. >
  3961. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3962. {queueCount}
  3963. </button>
  3964. )}
  3965. {/* Firmware Version Badge */}
  3966. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3967. <button
  3968. onClick={() => setShowFirmwareModal(true)}
  3969. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3970. firmwareInfo.update_available
  3971. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3972. : 'bg-status-ok/20 text-status-ok'
  3973. }`}
  3974. title={
  3975. firmwareInfo.update_available
  3976. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3977. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3978. }
  3979. >
  3980. {firmwareInfo.update_available ? <Download className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <CheckCircle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  3981. {firmwareInfo.current_version}
  3982. </button>
  3983. ) : status?.firmware_version ? (
  3984. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3985. {status.firmware_version}
  3986. </span>
  3987. ) : null}
  3988. {/* Enclosure Door Badge — models with an actual door sensor.
  3989. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3990. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3991. <span
  3992. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3993. status.door_open
  3994. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3995. : 'bg-status-ok/20 text-status-ok'
  3996. }`}
  3997. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3998. >
  3999. {status.door_open ? <DoorOpen className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <DoorClosed className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4000. </span>
  4001. )}
  4002. </div>
  4003. </div>
  4004. )}
  4005. </div>
  4006. {/* Delete Confirmation */}
  4007. {showDeleteConfirm && (
  4008. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  4009. <Card className="w-full max-w-md mx-4">
  4010. <CardContent>
  4011. <div className="flex items-start gap-3 mb-4">
  4012. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  4013. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  4014. </div>
  4015. <div>
  4016. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  4017. <p className="text-sm text-bambu-gray mt-1">
  4018. {t('printers.confirm.deleteMessage', { name: printer.name })}
  4019. </p>
  4020. </div>
  4021. </div>
  4022. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  4023. <label className="flex items-start gap-3 cursor-pointer">
  4024. <input
  4025. type="checkbox"
  4026. checked={deleteArchives}
  4027. onChange={(e) => setDeleteArchives(e.target.checked)}
  4028. className="mt-0.5 w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  4029. />
  4030. <div>
  4031. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  4032. <p className="text-xs text-bambu-gray mt-0.5">
  4033. {deleteArchives
  4034. ? t('printers.confirm.deleteArchivesNote')
  4035. : t('printers.confirm.keepArchivesNote')}
  4036. </p>
  4037. </div>
  4038. </label>
  4039. </div>
  4040. <div className="flex justify-end gap-2">
  4041. <Button
  4042. variant="secondary"
  4043. onClick={() => {
  4044. setShowDeleteConfirm(false);
  4045. setDeleteArchives(true);
  4046. }}
  4047. >
  4048. {t('common.cancel')}
  4049. </Button>
  4050. <Button
  4051. variant="danger"
  4052. onClick={() => {
  4053. deleteMutation.mutate({ deleteArchives });
  4054. setShowDeleteConfirm(false);
  4055. setDeleteArchives(true);
  4056. }}
  4057. >
  4058. Delete
  4059. </Button>
  4060. </div>
  4061. </CardContent>
  4062. </Card>
  4063. </div>
  4064. )}
  4065. {/* Status — see the equivalent defensive `=== false` check on the
  4066. header pill above for why this is not `!printer.is_active`. */}
  4067. {printer.is_active === false ? (
  4068. // Maintenance mode (#1476) — replaces the cover/progress container
  4069. // so the card keeps the same height. Renders for both compact and
  4070. // expanded view modes so the printer stays visible but plainly
  4071. // out-of-service.
  4072. <>
  4073. {viewMode === 'compact' ? (
  4074. <div className="mt-2 flex items-center gap-2 px-2 py-1.5 rounded-full bg-amber-50 dark:bg-amber-500/15 border border-amber-300 dark:border-amber-500/30">
  4075. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4076. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4077. {t('printers.maintenance.pillLabel')}
  4078. </span>
  4079. </div>
  4080. ) : (
  4081. <>
  4082. <div className="flex items-center gap-2 mb-2">
  4083. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4084. {t('printers.status.title', 'Status')}
  4085. </span>
  4086. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4087. </div>
  4088. <div className="p-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 rounded-[10px] flex items-center gap-3">
  4089. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4090. <div className="flex-1 min-w-0">
  4091. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4092. {t('printers.maintenance.title')}
  4093. </p>
  4094. <p className="text-xs text-bambu-gray mt-0.5">
  4095. {t('printers.maintenance.subtitle')}
  4096. </p>
  4097. </div>
  4098. <Button
  4099. variant="secondary"
  4100. size="sm"
  4101. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4102. onClick={() => maintenanceMutation.mutate(true)}
  4103. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4104. >
  4105. {t('printers.maintenance.exitButton')}
  4106. </Button>
  4107. </div>
  4108. </>
  4109. )}
  4110. </>
  4111. ) : status?.connected && (
  4112. <>
  4113. {/* Compact: Simple status bar */}
  4114. {viewMode === 'compact' ? (
  4115. (() => {
  4116. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4117. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4118. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4119. ? Math.max(0, Math.min(100, status.progress || 0))
  4120. : showClearPlateButton
  4121. ? 100
  4122. : hasProblem
  4123. ? 100
  4124. : 0;
  4125. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4126. const compactProgressClass = hasProblem
  4127. ? 'bg-status-error'
  4128. : status.state === 'PAUSE'
  4129. ? 'bg-status-warning'
  4130. : 'bg-bambu-green';
  4131. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4132. const hasCompactLayers =
  4133. isActiveCompactPrint &&
  4134. status.layer_num != null &&
  4135. status.total_layers != null &&
  4136. status.total_layers > 0;
  4137. return (
  4138. <>
  4139. <div className="relative mt-2 flex items-center gap-2">
  4140. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4141. <div
  4142. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4143. style={{ width: `${compactProgress}%` }}
  4144. />
  4145. </div>
  4146. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4147. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4148. </span>
  4149. </div>
  4150. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4151. enough to answer "which printer finishes first", which is what a
  4152. wall-mounted fleet view is for. One line of the metrics the
  4153. expanded card already renders, using the same formatters and the
  4154. same ETA styling so S and M read alike. The row keeps its height
  4155. when idle so cards don't shift as prints start and stop. */}
  4156. <div className="mt-1 flex min-h-[14px] items-center gap-2 overflow-hidden text-[length:var(--pc-t11,11px)] leading-none text-bambu-gray">
  4157. {hasCompactEta && (
  4158. <>
  4159. <span className="flex shrink-0 items-center gap-1">
  4160. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4161. {formatDuration(status.remaining_time! * 60)}
  4162. </span>
  4163. <span
  4164. className="shrink-0 font-medium text-bambu-green"
  4165. title={t('printers.estimatedCompletion')}
  4166. >
  4167. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4168. </span>
  4169. </>
  4170. )}
  4171. {hasCompactLayers && (
  4172. <span className="flex min-w-0 items-center gap-1 truncate">
  4173. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4174. {status.layer_num}/{status.total_layers}
  4175. </span>
  4176. )}
  4177. </div>
  4178. </>
  4179. );
  4180. })()
  4181. ) : (
  4182. /* Expanded: Full status section */
  4183. <>
  4184. <div className="flex items-center gap-2 mb-2">
  4185. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4186. {t('printers.status.title', 'Status')}
  4187. </span>
  4188. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4189. </div>
  4190. {/* Current Print or Idle Placeholder */}
  4191. {(() => {
  4192. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4193. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4194. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4195. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4196. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4197. // A running print always has at least one object, so a count of
  4198. // zero means "not loaded", not "nothing to skip" — after a
  4199. // restart mid-print the list is empty until something rebuilds
  4200. // it. Treating that as nothing-to-skip disabled the only
  4201. // control that opens the modal, and the modal's own fetch is
  4202. // what rebuilds the list, so the print could never get it back.
  4203. // Exactly one object is the real nothing-to-skip case.
  4204. const objectCount = status.printable_objects_count ?? 0;
  4205. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4206. return (
  4207. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4208. <button
  4209. onClick={() => setShowSkipObjectsModal(true)}
  4210. disabled={!canSkipObjects}
  4211. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4212. canSkipObjects
  4213. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4214. : 'text-bambu-gray/30 cursor-not-allowed'
  4215. }`}
  4216. title={
  4217. !hasPermission('printers:control')
  4218. ? t('printers.permission.noControl')
  4219. : !isActivePrint
  4220. ? t('printers.skipObjects.onlyWhilePrinting')
  4221. : objectCount === 1
  4222. ? t('printers.skipObjects.requiresMultiple')
  4223. : t('printers.skipObjects.tooltip')
  4224. }
  4225. >
  4226. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4227. {objectsData && objectsData.skipped_count > 0 && (
  4228. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[length:var(--pc-t10,10px)] font-bold bg-red-500 text-white rounded-full">
  4229. {objectsData.skipped_count}
  4230. </span>
  4231. )}
  4232. </button>
  4233. <div className="flex items-stretch gap-2">
  4234. <CoverImage
  4235. url={coverUrl}
  4236. printName={printName || undefined}
  4237. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4238. />
  4239. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4240. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4241. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4242. {plateStatusPill}
  4243. </div>
  4244. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4245. {printName || t('printers.noActiveJob', 'No active job')}
  4246. </p>
  4247. <div className="flex h-3 items-center gap-2 text-sm">
  4248. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4249. <div
  4250. 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`}
  4251. style={{ width: `${progress}%` }}
  4252. />
  4253. </div>
  4254. <span className={`w-9 shrink-0 pr-1 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  4255. </div>
  4256. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4257. {isActivePrint ? (
  4258. <>
  4259. {status.remaining_time != null && status.remaining_time > 0 && (
  4260. <>
  4261. <span className="flex items-center gap-1">
  4262. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4263. {formatDuration(status.remaining_time * 60)}
  4264. </span>
  4265. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4266. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4267. </span>
  4268. </>
  4269. )}
  4270. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4271. <span className="flex items-center gap-1">
  4272. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4273. {status.layer_num}/{status.total_layers}
  4274. </span>
  4275. )}
  4276. {currentPrintUser && (
  4277. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4278. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4279. {currentPrintUser}
  4280. </span>
  4281. )}
  4282. </>
  4283. ) : lastPrint ? (
  4284. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4285. Last: {lastPrint.print_name || lastPrint.filename}
  4286. {lastPrint.completed_at && (
  4287. <span className="ml-1 text-bambu-gray/60">
  4288. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4289. </span>
  4290. )}
  4291. </p>
  4292. ) : (
  4293. <span>{t('printers.readyToPrint')}</span>
  4294. )}
  4295. </div>
  4296. </div>
  4297. </div>
  4298. <PrinterQueueWidget
  4299. printerId={printer.id}
  4300. printerModel={printer.model}
  4301. loadedFilamentTypes={loadedFilamentTypes}
  4302. loadedFilaments={loadedFilaments}
  4303. loadedVariants={loadedVariants}
  4304. variant="panelExtension"
  4305. />
  4306. </div>
  4307. );
  4308. })()}
  4309. </>
  4310. )}
  4311. {/* Temperatures */}
  4312. {status.temperatures && viewMode === 'expanded' && (() => {
  4313. // Use actual heater states from MQTT stream
  4314. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4315. const bedHeating = status.temperatures.bed_heating || false;
  4316. const chamberHeating = status.temperatures.chamber_heating || false;
  4317. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4318. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4319. const kinds: HeaterSensorKind[] = ['nozzle'];
  4320. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4321. kinds.push('bed');
  4322. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4323. return kinds;
  4324. })();
  4325. // active_extruder: 0=right, 1=left
  4326. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4327. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4328. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4329. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4330. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4331. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4332. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4333. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4334. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4335. 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 ${
  4336. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4337. }`;
  4338. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4339. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4340. // the widget there is at best dead UI and at worst suggests a
  4341. // control that does nothing. Mirrors the enclosure-door badge
  4342. // gate above.
  4343. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4344. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4345. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4346. // show it only when the printer actually reports it (airduct part id 3,
  4347. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4348. // have a built-in chamber fan that's always present, so they keep the
  4349. // existing model-list gate and the "Chamber Fan" label.
  4350. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4351. const chamberFanLabel = isExhaustModel
  4352. ? t('printers.fans.exhaust')
  4353. : t('printers.fans.chamber');
  4354. // Composed rather than either/or so both lists stay live for
  4355. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4356. // where that fan is an add-on kit — actually report it. Written
  4357. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4358. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4359. // which reads as if removing them were safe.
  4360. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4361. const fanItems: {
  4362. key: string;
  4363. label: string;
  4364. value: number;
  4365. Icon: typeof Fan;
  4366. activeClass: string;
  4367. }[] = [
  4368. {
  4369. key: 'part',
  4370. label: t('printers.fans.partCooling'),
  4371. value: status.cooling_fan_speed ?? 0,
  4372. Icon: Fan,
  4373. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4374. },
  4375. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4376. // Only reported (non-null) when the firmware lists airduct part
  4377. // id 10, i.e. when the fan is physically installed. Placed
  4378. // before the right-hand auxiliary fan so the two aux badges read
  4379. // left-to-right in the same order as the physical hardware.
  4380. ...(status.left_aux_fan_speed != null
  4381. ? [
  4382. {
  4383. key: 'aux2',
  4384. label: t('printers.fans.leftAuxiliary'),
  4385. value: status.left_aux_fan_speed,
  4386. Icon: Wind,
  4387. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4388. },
  4389. ]
  4390. : []),
  4391. {
  4392. key: 'aux',
  4393. label: t('printers.fans.auxiliary'),
  4394. value: status.big_fan1_speed ?? 0,
  4395. Icon: Wind,
  4396. activeClass: 'text-blue-600 dark:text-blue-400',
  4397. },
  4398. ...(showChamberFan
  4399. ? [
  4400. {
  4401. key: 'chamber',
  4402. label: chamberFanLabel,
  4403. value: status.big_fan2_speed ?? 0,
  4404. Icon: AirVent,
  4405. activeClass: 'text-green-600 dark:text-green-400',
  4406. },
  4407. ]
  4408. : []),
  4409. ];
  4410. return (
  4411. <>
  4412. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4413. {/* Nozzle temp - combined for dual nozzle */}
  4414. <div
  4415. className={statusControlClass}
  4416. title={statusControlTitle}
  4417. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4418. >
  4419. <button
  4420. type="button"
  4421. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4422. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4423. onClick={(e) => {
  4424. e.stopPropagation();
  4425. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4426. }}
  4427. >
  4428. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4429. </button>
  4430. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4431. {status.temperatures.nozzle_2 !== undefined ? (
  4432. <>
  4433. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4434. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4435. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4436. </p>
  4437. </>
  4438. ) : singleNozzleSlot ? (
  4439. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4440. <div className="cursor-default">
  4441. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4442. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4443. {Math.round(status.temperatures.nozzle || 0)}°C
  4444. </p>
  4445. </div>
  4446. </NozzleSlotHoverCard>
  4447. ) : (
  4448. <>
  4449. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4450. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4451. {Math.round(status.temperatures.nozzle || 0)}°C
  4452. </p>
  4453. </>
  4454. )}
  4455. {statusControlMenu === 'nozzle-temp' && (
  4456. isDualNozzle ? (
  4457. <IndicatorControlPopover
  4458. title="Set Nozzle Temperatures"
  4459. widthClass="w-[300px]"
  4460. popoverWidth={300}
  4461. popoverHeight={260}
  4462. isPending={nozzleTemperatureMutation.isPending}
  4463. onClose={() => setStatusControlMenu(null)}
  4464. >
  4465. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4466. <NozzleTemperatureControlBox
  4467. label="Left Temp"
  4468. current={status.temperatures.nozzle}
  4469. target={status.temperatures.nozzle_target}
  4470. isActive={activeNozzle === 'L'}
  4471. isPending={nozzleTemperatureMutation.isPending}
  4472. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4473. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4474. />
  4475. <NozzleTemperatureControlBox
  4476. label="Right Temp"
  4477. current={status.temperatures.nozzle_2}
  4478. target={status.temperatures.nozzle_2_target}
  4479. isActive={activeNozzle === 'R'}
  4480. isPending={nozzleTemperatureMutation.isPending}
  4481. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4482. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4483. />
  4484. </div>
  4485. </IndicatorControlPopover>
  4486. ) : (
  4487. <IndicatorControlPopover
  4488. title="Set Nozzle Temperature"
  4489. unit="°C"
  4490. customMin={0}
  4491. customMax={320}
  4492. isPending={nozzleTemperatureMutation.isPending}
  4493. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4494. onClose={() => setStatusControlMenu(null)}
  4495. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4496. />
  4497. )
  4498. )}
  4499. </div>
  4500. <div
  4501. className={statusControlClass}
  4502. title={statusControlTitle}
  4503. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4504. >
  4505. <button
  4506. type="button"
  4507. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4508. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4509. onClick={(e) => {
  4510. e.stopPropagation();
  4511. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4512. }}
  4513. >
  4514. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4515. </button>
  4516. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4517. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4518. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4519. {Math.round(status.temperatures.bed || 0)}°C
  4520. </p>
  4521. {statusControlMenu === 'bed-temp' && (
  4522. <IndicatorControlPopover
  4523. title="Set Bed Temperature"
  4524. unit="°C"
  4525. customMin={0}
  4526. customMax={140}
  4527. isPending={bedTemperatureMutation.isPending}
  4528. options={buildPresetOptions(bedTempPresets, 'C')}
  4529. onClose={() => setStatusControlMenu(null)}
  4530. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4531. />
  4532. )}
  4533. </div>
  4534. {status.temperatures.chamber !== undefined && (() => {
  4535. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4536. // but can't act on M141, so we keep the card read-only there.
  4537. const hasChamberHeater = status.supports_chamber_heater === true;
  4538. return (
  4539. <div
  4540. className={hasChamberHeater
  4541. ? statusControlClass
  4542. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4543. title={hasChamberHeater ? statusControlTitle : undefined}
  4544. onClick={hasChamberHeater
  4545. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4546. : undefined}
  4547. >
  4548. <button
  4549. type="button"
  4550. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4551. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4552. onClick={(e) => {
  4553. e.stopPropagation();
  4554. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4555. }}
  4556. >
  4557. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4558. </button>
  4559. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4560. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4561. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4562. {Math.round(status.temperatures.chamber || 0)}°C
  4563. </p>
  4564. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4565. <IndicatorControlPopover
  4566. title="Set Chamber Temperature"
  4567. unit="°C"
  4568. customMin={0}
  4569. customMax={MAX_CHAMBER_TEMP_C}
  4570. isPending={chamberTemperatureMutation.isPending}
  4571. options={buildPresetOptions(chamberTempPresets, 'C')}
  4572. onClose={() => setStatusControlMenu(null)}
  4573. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4574. />
  4575. )}
  4576. </div>
  4577. );
  4578. })()}
  4579. {/* Active nozzle indicator for dual-nozzle printers */}
  4580. {isDualNozzle && (
  4581. <DualNozzleHoverCard
  4582. leftSlot={leftNozzleSlot}
  4583. rightSlot={rightNozzleSlot}
  4584. activeNozzle={activeNozzle}
  4585. filamentInfo={filamentInfo}
  4586. >
  4587. <div
  4588. 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 ${
  4589. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4590. }`}
  4591. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4592. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4593. >
  4594. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4595. <div className="flex items-center gap-2">
  4596. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4597. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4598. </span>
  4599. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4600. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4601. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4602. </span>
  4603. </div>
  4604. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4605. {statusControlMenu === 'nozzle-select' && (
  4606. <IndicatorControlPopover
  4607. title="Set Nozzle Selection"
  4608. widthClass="w-[300px]"
  4609. popoverWidth={300}
  4610. popoverHeight={140}
  4611. isPending={selectExtruderMutation.isPending}
  4612. options={[
  4613. { label: 'Left', value: 1 },
  4614. { label: 'Right', value: 0 },
  4615. ]}
  4616. onClose={() => setStatusControlMenu(null)}
  4617. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4618. />
  4619. )}
  4620. </div>
  4621. </DualNozzleHoverCard>
  4622. )}
  4623. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4624. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4625. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4626. )}
  4627. </div>
  4628. <div className="mt-2 flex items-center gap-1.5">
  4629. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4630. const active = value > 0;
  4631. return (
  4632. <div
  4633. key={key}
  4634. 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 ${
  4635. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4636. }`}
  4637. title={canUseStatusControls ? label : statusControlTitle}
  4638. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4639. >
  4640. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4641. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4642. {value}%
  4643. </span>
  4644. {statusControlMenu === `fan-${key}` && (
  4645. <IndicatorControlPopover
  4646. title={`Set ${label} Speed`}
  4647. unit="%"
  4648. customMin={0}
  4649. customMax={100}
  4650. isPending={fanSpeedMutation.isPending}
  4651. options={buildPresetOptions(fanSpeedPresets, '%')}
  4652. onClose={() => setStatusControlMenu(null)}
  4653. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4654. />
  4655. )}
  4656. </div>
  4657. );
  4658. })}
  4659. </div>
  4660. </>
  4661. );
  4662. })()}
  4663. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4664. {/* Controls */}
  4665. {viewMode === 'expanded' && (() => {
  4666. // Determine print state for control buttons
  4667. const isRunning = status.state === 'RUNNING';
  4668. const isPaused = status.state === 'PAUSE';
  4669. const isPrinting = isRunning || isPaused;
  4670. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4671. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4672. 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';
  4673. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4674. return (
  4675. <div className="mt-3">
  4676. {/* Section Header */}
  4677. <div className="flex items-center gap-2 mb-2">
  4678. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4679. {t('printers.controls')}
  4680. </span>
  4681. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4682. </div>
  4683. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4684. {/* Left: Secondary controls */}
  4685. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4686. <button
  4687. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4688. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4689. className={`${iconControlClass} ${
  4690. status.chamber_light
  4691. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4692. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4693. }`}
  4694. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4695. >
  4696. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4697. </button>
  4698. {/* Airduct Mode (P2S / X2D / H2*) */}
  4699. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4700. const isHeating = status.airduct_mode === 1;
  4701. const Icon = isHeating ? Flame : Snowflake;
  4702. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4703. const bg = isHeating ? 'bg-orange-50 dark:bg-orange-500/10 text-orange-700 dark:text-orange-400 hover:bg-orange-500/20' : 'bg-sky-50 dark:bg-sky-500/10 text-sky-700 dark:text-sky-400 hover:bg-sky-500/20';
  4704. return (
  4705. <div className="relative">
  4706. <button
  4707. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4708. disabled={!hasPermission('printers:control')}
  4709. className={`${iconControlClass} ${bg}`}
  4710. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4711. >
  4712. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4713. </button>
  4714. {showAirductMenu === printer.id && (
  4715. <>
  4716. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4717. <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]">
  4718. {([
  4719. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4720. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4721. ] as const).map(({ mode, label, modeId }) => (
  4722. <button
  4723. key={mode}
  4724. onClick={() => {
  4725. airductMutation.mutate(mode);
  4726. setShowAirductMenu(null);
  4727. }}
  4728. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4729. status.airduct_mode === modeId
  4730. ? 'text-bambu-green bg-bambu-green/10'
  4731. : 'text-white hover:bg-bambu-dark-tertiary'
  4732. }`}
  4733. >
  4734. {mode === 'heating' ? <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Snowflake className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4735. {label}
  4736. </button>
  4737. ))}
  4738. </div>
  4739. </>
  4740. )}
  4741. </div>
  4742. );
  4743. })()}
  4744. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4745. {(() => {
  4746. const canControl = hasPermission('printers:control');
  4747. const disabled = isPrinting || !canControl;
  4748. const jogButtonClass = 'flex h-8 w-8 items-center justify-center rounded bg-indigo-100 dark:bg-indigo-500/15 text-indigo-700 dark:text-indigo-300 transition-colors hover:bg-indigo-200 dark:hover:bg-indigo-500/30 disabled:cursor-not-allowed disabled:opacity-50';
  4749. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4750. // nozzle-bed gap that means the same thing on every printer, so the
  4751. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4752. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4753. // plate toward the nozzle and closes it.
  4754. const zMovesToolhead = isBedSlinger(printer.model);
  4755. const requestZJog = (arrow: 'up' | 'down') => {
  4756. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4757. // No not-homed gate here, and no endstop bypass to gate either:
  4758. // since #2579 the jog is a bare move that never touches M211. That
  4759. // does not make it clamped — the firmware ignores soft endstops on
  4760. // MQTT G-code entirely, which is what the banner above warns about.
  4761. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4762. };
  4763. const requestXyJog = (x: number, y: number) => {
  4764. xyJogMutation.mutate({ x, y });
  4765. };
  4766. const requestExtruderJog = (distance: number) => {
  4767. extruderJogMutation.mutate(distance);
  4768. };
  4769. return (
  4770. <div className="relative">
  4771. <button
  4772. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4773. disabled={disabled}
  4774. className={`${iconControlClass} ${
  4775. disabled
  4776. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4777. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4778. }`}
  4779. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4780. >
  4781. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4782. </button>
  4783. {showBedJogMenu === printer.id && (
  4784. <>
  4785. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4786. <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">
  4787. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4788. {t('printers.bedJog.title')}
  4789. </div>
  4790. <div className="h-px bg-bambu-dark-tertiary" />
  4791. {/* #2579: Bambu firmware does not enforce soft endstops on
  4792. G-code sent over MQTT, so manual moves can drive past the
  4793. travel limits and cause a collision. Not fixable from our
  4794. side — warn prominently. */}
  4795. <div className="flex items-start gap-1.5 bg-yellow-500/10 px-3 py-2 text-[length:var(--pc-t11,11px)] leading-snug text-yellow-700 dark:text-yellow-400">
  4796. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4797. <span>{t('printers.bedJog.limitWarning')}</span>
  4798. </div>
  4799. <div className="h-px bg-bambu-dark-tertiary" />
  4800. <div className="flex justify-center px-3 py-2.5">
  4801. <div className="flex items-center justify-center gap-3">
  4802. <div className="grid grid-cols-3 gap-1">
  4803. <div />
  4804. <button
  4805. onClick={() => requestXyJog(0, bedJogStep)}
  4806. disabled={xyJogMutation.isPending}
  4807. className={jogButtonClass}
  4808. aria-label="Move Y forward"
  4809. >
  4810. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4811. </button>
  4812. <div />
  4813. <button
  4814. onClick={() => requestXyJog(-bedJogStep, 0)}
  4815. disabled={xyJogMutation.isPending}
  4816. className={jogButtonClass}
  4817. aria-label="Move X left"
  4818. >
  4819. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4820. </button>
  4821. <button
  4822. onClick={() => {
  4823. setShowBedJogMenu(null);
  4824. homeAxesMutation.mutate('all');
  4825. }}
  4826. disabled={homeAxesMutation.isPending}
  4827. className={jogButtonClass}
  4828. aria-label={t('printers.bedJog.homeZ')}
  4829. >
  4830. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4831. </button>
  4832. <button
  4833. onClick={() => requestXyJog(bedJogStep, 0)}
  4834. disabled={xyJogMutation.isPending}
  4835. className={jogButtonClass}
  4836. aria-label="Move X right"
  4837. >
  4838. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4839. </button>
  4840. <div />
  4841. <button
  4842. onClick={() => requestXyJog(0, -bedJogStep)}
  4843. disabled={xyJogMutation.isPending}
  4844. className={jogButtonClass}
  4845. aria-label="Move Y back"
  4846. >
  4847. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4848. </button>
  4849. <div />
  4850. </div>
  4851. <div className="flex flex-col items-center gap-1">
  4852. <button
  4853. onClick={() => requestZJog('up')}
  4854. disabled={bedJogMutation.isPending}
  4855. className={jogButtonClass}
  4856. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4857. >
  4858. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4859. </button>
  4860. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4861. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4862. </div>
  4863. <button
  4864. onClick={() => requestZJog('down')}
  4865. disabled={bedJogMutation.isPending}
  4866. className={jogButtonClass}
  4867. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4868. >
  4869. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4870. </button>
  4871. </div>
  4872. <div className="flex flex-col items-center gap-1">
  4873. <button
  4874. onClick={() => requestExtruderJog(-bedJogStep)}
  4875. disabled={extruderJogMutation.isPending}
  4876. className={jogButtonClass}
  4877. aria-label="Retract filament"
  4878. >
  4879. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4880. </button>
  4881. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4882. <span className="text-sm font-semibold leading-none">E</span>
  4883. </div>
  4884. <button
  4885. onClick={() => requestExtruderJog(bedJogStep)}
  4886. disabled={extruderJogMutation.isPending}
  4887. className={jogButtonClass}
  4888. aria-label="Extrude filament"
  4889. >
  4890. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4891. </button>
  4892. </div>
  4893. </div>
  4894. </div>
  4895. <div className="h-px bg-bambu-dark-tertiary" />
  4896. <div className="px-3 pt-2.5 pb-3">
  4897. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4898. {t('printers.bedJog.step')}
  4899. </div>
  4900. <div className="flex gap-1">
  4901. {[1, 10, 50].map((step) => (
  4902. <button
  4903. key={step}
  4904. onClick={() => setBedJogStep(step)}
  4905. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4906. bedJogStep === step
  4907. ? 'bg-bambu-green/20 text-bambu-green'
  4908. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4909. }`}
  4910. >
  4911. {step}
  4912. </button>
  4913. ))}
  4914. </div>
  4915. </div>
  4916. </div>
  4917. </>
  4918. )}
  4919. </div>
  4920. );
  4921. })()}
  4922. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4923. <button
  4924. onClick={handleTogglePlateDetection}
  4925. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4926. className={`${iconControlClass} rounded-r-none ${
  4927. printer.plate_detection_enabled
  4928. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4929. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4930. }`}
  4931. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4932. >
  4933. {plateDetectionMutation.isPending ? (
  4934. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4935. ) : (
  4936. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4937. )}
  4938. </button>
  4939. <button
  4940. onClick={handleOpenPlateManagement}
  4941. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4942. 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 ${
  4943. printer.plate_detection_enabled
  4944. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4945. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4946. }`}
  4947. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4948. >
  4949. {isCheckingPlate ? (
  4950. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4951. ) : (
  4952. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4953. )}
  4954. </button>
  4955. </div>
  4956. {/* Print Speed */}
  4957. {(() => (
  4958. <div className="relative">
  4959. <button
  4960. data-testid="speed-control"
  4961. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4962. disabled={!isPrinting || !hasPermission('printers:control')}
  4963. className={`${iconControlClass} ${
  4964. isPrinting
  4965. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4966. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4967. }`}
  4968. title={isPrinting ? t('printers.speed.title') : undefined}
  4969. >
  4970. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4971. </button>
  4972. {showSpeedMenu === printer.id && (
  4973. <>
  4974. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4975. <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]">
  4976. {([
  4977. { mode: 1, label: t('printers.speed.silent') },
  4978. { mode: 2, label: t('printers.speed.standard') },
  4979. { mode: 3, label: t('printers.speed.sport') },
  4980. { mode: 4, label: t('printers.speed.ludicrous') },
  4981. ] as const).map(({ mode, label }) => (
  4982. <button
  4983. key={mode}
  4984. onClick={() => {
  4985. printSpeedMutation.mutate(mode);
  4986. setShowSpeedMenu(null);
  4987. }}
  4988. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4989. status.speed_level === mode
  4990. ? 'text-bambu-green bg-bambu-green/10'
  4991. : 'text-white hover:bg-bambu-dark-tertiary'
  4992. }`}
  4993. >
  4994. {label}
  4995. </button>
  4996. ))}
  4997. </div>
  4998. </>
  4999. )}
  5000. </div>
  5001. ))()}
  5002. </div>
  5003. {/* Right: Print Control Buttons */}
  5004. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  5005. {/* Pause/Resume button */}
  5006. {(() => {
  5007. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  5008. return (
  5009. <button
  5010. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  5011. disabled={pauseUnavailable}
  5012. className={`
  5013. ${printControlClass}
  5014. ${pauseUnavailable
  5015. ? unavailablePrintActionClass
  5016. : isPaused
  5017. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5018. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  5019. }
  5020. `}
  5021. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  5022. >
  5023. {isPaused ? <Play className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Pause className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  5024. {isPaused ? t('printers.resume') : t('printers.pause')}
  5025. </button>
  5026. );
  5027. })()}
  5028. {/* Stop button */}
  5029. {(() => {
  5030. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  5031. return (
  5032. <button
  5033. onClick={() => setShowStopConfirm(true)}
  5034. disabled={stopUnavailable}
  5035. className={`
  5036. ${printControlClass}
  5037. ${stopUnavailable
  5038. ? unavailablePrintActionClass
  5039. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  5040. }
  5041. `}
  5042. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  5043. >
  5044. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5045. {t('printers.stop')}
  5046. </button>
  5047. );
  5048. })()}
  5049. </div>
  5050. </div>
  5051. </div>
  5052. );
  5053. })()}
  5054. {/* AMS Units - 2-Column Grid Layout */}
  5055. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  5056. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  5057. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  5058. const htAms = amsData.filter(ams => ams.tray.length === 1);
  5059. // The external spool can only be hidden while some AMS remains to
  5060. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  5061. // filament section, so the toggle is not offered there and a stored
  5062. // preference from a printer that later lost its AMS cannot blank the
  5063. // row either — both read through canHideExternalSpool.
  5064. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  5065. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  5066. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5067. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5068. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5069. // floating point, and that lands verbatim in the DOM.
  5070. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5071. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5072. // already grow to fill the row, so the 3.5rem is a floor they sit
  5073. // well above in practice -- raising it just costs a unit its place
  5074. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5075. // its line, and flex-grow stretches its single slot across the whole
  5076. // card. The AMS-HT's own width does scale, below, because its
  5077. // readings sit beside the slot rather than under it.
  5078. const slotMinWidth = '3.5rem';
  5079. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5080. // The AMS-HT holds a single spool, and its slot is the only thing
  5081. // on that row able to grow -- so it swallowed every spare pixel and
  5082. // shoved the temperature and humidity hard against the card's edge.
  5083. // Capping it at roughly two ordinary slots keeps the readings clear
  5084. // of the edge; the cap scales because the text inside the slot does.
  5085. const htSlotStyle: React.CSSProperties = {
  5086. minWidth: slotMinWidth,
  5087. maxWidth: scaledRem(7.25),
  5088. };
  5089. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5090. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5091. });
  5092. // #1762 (comment 2): while a print is running/paused, overlay a small
  5093. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5094. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5095. // staged to a printer with mismatched filament: the wrong-slot pill
  5096. // is visible the instant printing starts.
  5097. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5098. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5099. ? status.ams_mapping
  5100. : [];
  5101. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5102. const boundedSlotCount = Math.max(1, slotCount);
  5103. const gapCount = Math.max(0, boundedSlotCount - 1);
  5104. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5105. return {
  5106. flex: `1 1 ${minWidth}`,
  5107. minWidth,
  5108. };
  5109. };
  5110. return (
  5111. <div className="mt-3">
  5112. {/* Section Header */}
  5113. <div className="flex items-center gap-2 mb-2">
  5114. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5115. {t('printers.filaments')}
  5116. </span>
  5117. <AmsBackupBadge
  5118. state={status.ams_filament_backup}
  5119. onClick={() => setAmsBackupModalOpen(true)}
  5120. />
  5121. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5122. {/* Offered only when an AMS is present: on a printer that
  5123. feeds from the external spool alone, hiding it would
  5124. empty the row entirely (#1782). */}
  5125. {canHideExternalSpool && (
  5126. <>
  5127. <ExternalSpoolToggle
  5128. hidden={externalSpoolHidden}
  5129. onClick={toggleExternalSpool}
  5130. />
  5131. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5132. </>
  5133. )}
  5134. </div>
  5135. {/* AMS Content */}
  5136. <div className="flex flex-wrap gap-2">
  5137. {/* Regular AMS units */}
  5138. {regularAms.map((ams) => {
  5139. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5140. return (
  5141. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5142. {/* Header: Label + Stats (no icon) */}
  5143. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5144. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5145. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5146. <AmsNameHoverCard
  5147. ams={ams}
  5148. printerId={printer.id}
  5149. label={getAmsLabel(ams.id, ams.tray.length)}
  5150. amsLabels={amsLabels}
  5151. canEdit={hasPermission('printers:update')}
  5152. onSaved={refetchAmsLabels}
  5153. >
  5154. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5155. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5156. </span>
  5157. </AmsNameHoverCard>
  5158. {sideBadge?.kind === 'inlet' ? (
  5159. <InletBadge
  5160. inlet={sideBadge.inlet}
  5161. title={t('printers.amsSwitchInletTooltip', {
  5162. inlet: sideBadge.inlet,
  5163. side: FTS_INLET_SIDE[sideBadge.inlet],
  5164. })}
  5165. />
  5166. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5167. <NozzleBadge side={sideBadge.side} />
  5168. ) : null}
  5169. </div>
  5170. {(ams.humidity != null || ams.temp != null) && (
  5171. <div className="flex shrink-0 items-center gap-1.5">
  5172. {ams.humidity != null && (
  5173. <HumidityIndicator
  5174. humidity={ams.humidity}
  5175. goodThreshold={amsThresholds?.humidityGood}
  5176. fairThreshold={amsThresholds?.humidityFair}
  5177. onClick={() => setAmsHistoryModal({
  5178. amsId: ams.id,
  5179. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5180. mode: 'humidity',
  5181. })}
  5182. compact
  5183. />
  5184. )}
  5185. {ams.temp != null && (
  5186. <div className="mr-1">
  5187. <TemperatureIndicator
  5188. temp={ams.temp}
  5189. goodThreshold={amsThresholds?.tempGood}
  5190. fairThreshold={amsThresholds?.tempFair}
  5191. onClick={() => setAmsHistoryModal({
  5192. amsId: ams.id,
  5193. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5194. mode: 'temperature',
  5195. })}
  5196. compact
  5197. />
  5198. </div>
  5199. )}
  5200. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5201. Screen-only models (P1 series) keep the control but can't
  5202. be commanded: it stays disabled and says why (#2533). */}
  5203. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5204. <button
  5205. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5206. onClick={(e) => {
  5207. if (ams.dry_time > 0) {
  5208. stopDryingMutation.mutate(ams.id);
  5209. } else if (dryingPopoverAmsId === ams.id) {
  5210. setDryingPopoverAmsId(null);
  5211. } else {
  5212. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5213. }
  5214. }}
  5215. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5216. ams.dry_time > 0
  5217. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5218. : status.drying_screen_only || ams.dry_sf_reason?.length
  5219. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5220. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5221. }`}
  5222. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t(dryingBlockedKey(ams.dry_sf_reason)) : t('printers.drying.start')}
  5223. >
  5224. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5225. </button>
  5226. )}
  5227. </div>
  5228. )}
  5229. </div>
  5230. {/* Drying status bar. A dry_time whose countdown is not
  5231. ticking, with no active drying phase (a parked command —
  5232. e.g. an H2D mid-print already powering other drying — or
  5233. a paused cycle), is shown as "not running", not as an
  5234. active cycle: the amber badge claiming a running dry
  5235. that the AMS never began is how this was found. */}
  5236. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5237. <div className="flex items-center gap-2 rounded-lg bg-slate-100 dark:bg-slate-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]" title={t('printers.drying.notRunningHint')}>
  5238. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5239. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5240. {ams.dry_filament && (
  5241. <span className="text-slate-500/90 dark:text-slate-400/80">
  5242. {ams.dry_target_temp != null
  5243. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5244. : ams.dry_filament}
  5245. </span>
  5246. )}
  5247. {!status.drying_screen_only && (
  5248. <button
  5249. onClick={() => stopDryingMutation.mutate(ams.id)}
  5250. disabled={stopDryingMutation.isPending}
  5251. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5252. title={t('printers.drying.stop')}
  5253. >
  5254. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5255. </button>
  5256. )}
  5257. </div>
  5258. )}
  5259. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5260. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
  5261. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5262. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5263. {/* The temperature is only ever known from the target we
  5264. cached when sending the command — the filament can also
  5265. be read off a uniformly loaded unit, so it can outlive
  5266. the temperature (#2759). */}
  5267. {ams.dry_filament && (
  5268. <span className="text-amber-700/80 dark:text-amber-300/70">
  5269. {ams.dry_target_temp != null
  5270. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5271. : ams.dry_filament}
  5272. </span>
  5273. )}
  5274. <span className="text-amber-700/80 dark:text-amber-300/70">
  5275. {t('printers.drying.timeRemaining', {
  5276. time: ams.dry_time >= 60
  5277. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5278. : `${ams.dry_time}m`
  5279. })}
  5280. </span>
  5281. {/* A cycle on a screen-only model was started at the printer
  5282. and can only be stopped there (#2533). */}
  5283. {!status.drying_screen_only && (
  5284. <button
  5285. onClick={() => stopDryingMutation.mutate(ams.id)}
  5286. disabled={stopDryingMutation.isPending}
  5287. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5288. title={t('printers.drying.stop')}
  5289. >
  5290. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5291. </button>
  5292. )}
  5293. </div>
  5294. )}
  5295. {/* Slots grid: 4 columns - always render 4 slots */}
  5296. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5297. {[0, 1, 2, 3].map((slotIdx) => {
  5298. // Find tray data for this slot (may be undefined if data incomplete)
  5299. // Use array index if available, as tray.id may not always be set
  5300. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5301. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5302. const isEmpty = !tray?.tray_type;
  5303. const emptyKind = getEmptySlotKind(tray);
  5304. // Check if this is the currently loaded tray
  5305. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5306. const globalTrayId = ams.id * 4 + slotIdx;
  5307. const isActive = effectiveTrayNow === globalTrayId;
  5308. // Runout guidance (#2587): the slot the paused print now
  5309. // expects filament in, and the slot that ran out.
  5310. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5311. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5312. // Get cloud preset info if available
  5313. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5314. // Get saved slot preset mapping (for user-configured slots)
  5315. const slotPreset = slotPresets?.[globalTrayId];
  5316. // Only trusted while it still describes what the printer reports in the
  5317. // slot: the row survives a spool swap, and the display chain below puts
  5318. // it ahead of the live filament id (see slotPresetDescribesTray).
  5319. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5320. ? slotPreset?.preset_name
  5321. : undefined;
  5322. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5323. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5324. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5325. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5326. // Slot-assigned-only spool fill (no tag link required)
  5327. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5328. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5329. : undefined;
  5330. const slotSpoolForFill = slotAssignmentForFill
  5331. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5332. : undefined;
  5333. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5334. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5335. : null;
  5336. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5337. const inventoryFill = (() => {
  5338. const sp = inventoryAssignment?.spool;
  5339. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5340. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5341. }
  5342. return null;
  5343. })();
  5344. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5345. // (inventory weight_used may be stale or over-counted — #676)
  5346. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5347. ? null : inventoryFill;
  5348. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5349. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5350. : resolvedInventoryFill !== null ? 'inventory' as const
  5351. : hasFillLevel ? 'ams' as const
  5352. : undefined;
  5353. // Build filament data for hover card
  5354. const filamentData = tray?.tray_type ? {
  5355. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5356. // Spoolman spool name wins over cloud lookup so a slot bound to
  5357. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5358. // Design PLA") instead of whatever the printer's filament_id
  5359. // resolves to in the cloud catalog (often "Generic PLA" for
  5360. // P-prefix local presets). Spoolman's filament.name is just the
  5361. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5362. // the hover card shows "Devil Design PLA Basic" rather than the
  5363. // vendor-less form. Strip the "@<printer>..." suffix that
  5364. // BambuStudio appends to user-preset names.
  5365. profile: slotPresetName || (slotSpoolForFill ? [slotSpoolForFill.brand, slotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || slotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || inventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  5366. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5367. colorHex: tray.tray_color || null,
  5368. kFactor: formatKValue(tray.k),
  5369. fillLevel: effectiveFill,
  5370. trayUuid: tray.tray_uuid || null,
  5371. tagUid: tray.tag_uid || null,
  5372. fillSource,
  5373. } : null;
  5374. // Check if this specific slot is being refreshed
  5375. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5376. refreshingSlot?.slotId === slotIdx;
  5377. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5378. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5379. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5380. ? `P${activePrintSlotIdx + 1}`
  5381. : null;
  5382. // Slot visual content (goes inside hover card)
  5383. const slotVisual = (
  5384. <div
  5385. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5386. isExpectedSlot
  5387. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5388. : isRanOutSlot
  5389. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5390. : isActive
  5391. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5392. : ''
  5393. }`}
  5394. >
  5395. {isExpectedSlot && (
  5396. <span
  5397. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5398. title={t('printers.expectedSlot.title')}
  5399. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  5400. >
  5401. ↓
  5402. </span>
  5403. )}
  5404. {activePrintSlotLabel && (
  5405. <span
  5406. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5407. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5408. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  5409. >
  5410. {activePrintSlotLabel}
  5411. </span>
  5412. )}
  5413. {/* Filament color circle with 1-based slot number centered inside */}
  5414. <FilamentSlotCircle
  5415. trayColor={tray?.tray_color}
  5416. trayType={tray?.tray_type}
  5417. isEmpty={isEmpty}
  5418. emptyKind={emptyKind}
  5419. slotNumber={slotIdx + 1}
  5420. />
  5421. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5422. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5423. </div>
  5424. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5425. {/* Fill bar */}
  5426. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5427. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5428. <div
  5429. className="h-full rounded-full transition-all"
  5430. style={{
  5431. width: `${effectiveFill}%`,
  5432. backgroundColor: getFillBarColor(effectiveFill),
  5433. }}
  5434. />
  5435. )}
  5436. </div>
  5437. </div>
  5438. );
  5439. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5440. return (
  5441. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5442. {/* Loading overlay during RFID re-read */}
  5443. {isRefreshing && (
  5444. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5445. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5446. </div>
  5447. )}
  5448. {/* Hover card wraps only the visual content */}
  5449. {filamentData ? (
  5450. <FilamentHoverCard
  5451. data={filamentData}
  5452. actions={renderAmsSlotActions({
  5453. amsId: ams.id,
  5454. slotId: slotIdx,
  5455. loadTrayId: ams.id * 4 + slotIdx,
  5456. isRefreshing,
  5457. })}
  5458. spoolman={{
  5459. enabled: spoolmanEnabled,
  5460. // #1457: slot assignment is the user's most explicit action — it must
  5461. // outrank the tag-link, which can be stale when a non-RFID slot's
  5462. // fallback tag is still attached to a previous spool in Spoolman.
  5463. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5464. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5465. spoolmanUrl,
  5466. syncMode: spoolmanSyncMode,
  5467. // Suppress Link button when slot is already occupied by ANY assignment
  5468. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5469. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5470. // still appearing on slots with a local Devil Design PLA assigned.
  5471. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5472. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5473. setLinkSpoolModal({
  5474. tagUid: filamentData.tagUid || linkTag,
  5475. trayUuid: filamentData.trayUuid || '',
  5476. printerId: printer.id,
  5477. amsId: ams.id,
  5478. trayId: slotIdx,
  5479. });
  5480. } : undefined,
  5481. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5482. }}
  5483. inventory={(() => {
  5484. if (spoolmanEnabled) {
  5485. if (spoolmanLoading) return undefined;
  5486. const slotAssignment = slotAssignmentForFill;
  5487. const spoolmanSpool = slotSpoolForFill;
  5488. return {
  5489. assignedSpool: spoolmanSpool ? {
  5490. id: spoolmanSpool.id,
  5491. material: spoolmanSpool.material,
  5492. subtype: spoolmanSpool.subtype,
  5493. brand: spoolmanSpool.brand ?? null,
  5494. color_name: spoolmanSpool.color_name ?? null,
  5495. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5496. // The spool's own swatch (#2967). Spoolman carries the
  5497. // extra stops but has no effect field at all, so those
  5498. // rolls gradient and never shimmer.
  5499. rgba: spoolmanSpool.rgba ?? null,
  5500. extra_colors: spoolmanSpool.extra_colors ?? null,
  5501. effect_type: spoolmanSpool.effect_type ?? null,
  5502. remainingWeightGrams: spoolmanSpool.label_weight
  5503. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5504. : undefined,
  5505. } : null,
  5506. onAssignSpool: () => setAssignSpoolModal({
  5507. printerId: printer.id,
  5508. amsId: ams.id,
  5509. trayId: slotIdx,
  5510. trayInfo: {
  5511. type: tray?.tray_type || filamentData.profile,
  5512. material: tray?.tray_type ?? undefined,
  5513. profile: filamentData.profile,
  5514. color: filamentData.colorHex || '',
  5515. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5516. },
  5517. }),
  5518. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5519. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5520. };
  5521. }
  5522. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5523. return {
  5524. assignedSpool: assignment?.spool ? {
  5525. id: assignment.spool.id,
  5526. material: assignment.spool.material,
  5527. subtype: assignment.spool.subtype,
  5528. brand: assignment.spool.brand,
  5529. color_name: assignment.spool.color_name,
  5530. // The spool's own swatch (#2967).
  5531. rgba: assignment.spool.rgba ?? null,
  5532. extra_colors: assignment.spool.extra_colors ?? null,
  5533. effect_type: assignment.spool.effect_type ?? null,
  5534. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5535. } : null,
  5536. onAssignSpool: () => setAssignSpoolModal({
  5537. printerId: printer.id,
  5538. amsId: ams.id,
  5539. trayId: slotIdx,
  5540. trayInfo: {
  5541. type: tray?.tray_type || filamentData.profile,
  5542. material: tray?.tray_type ?? undefined,
  5543. profile: filamentData.profile,
  5544. color: filamentData.colorHex || '',
  5545. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5546. },
  5547. }),
  5548. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5549. isAssigned: !!assignment || isBambuLabSpool(tray),
  5550. };
  5551. })()}
  5552. configureSlot={{
  5553. enabled: hasPermission('printers:control'),
  5554. onConfigure: () => setConfigureSlotModal({
  5555. amsId: ams.id,
  5556. trayId: slotIdx,
  5557. trayCount: ams.tray.length,
  5558. trayType: tray?.tray_type || undefined,
  5559. trayColor: tray?.tray_color || undefined,
  5560. traySubBrands: tray?.tray_sub_brands || undefined,
  5561. trayInfoIdx: tray?.tray_info_idx || undefined,
  5562. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5563. caliIdx: tray?.cali_idx,
  5564. savedPresetId: slotPreset?.preset_id,
  5565. }),
  5566. }}
  5567. >
  5568. {slotVisual}
  5569. </FilamentHoverCard>
  5570. ) : (
  5571. <EmptySlotHoverCard
  5572. kind={emptyKind ?? undefined}
  5573. actions={renderAmsSlotActions({
  5574. amsId: ams.id,
  5575. slotId: slotIdx,
  5576. loadTrayId: ams.id * 4 + slotIdx,
  5577. isRefreshing,
  5578. })}
  5579. configureSlot={{
  5580. enabled: hasPermission('printers:control'),
  5581. onConfigure: () => setConfigureSlotModal({
  5582. amsId: ams.id,
  5583. trayId: slotIdx,
  5584. trayCount: ams.tray.length,
  5585. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5586. }),
  5587. }}
  5588. onAssignSpool={() => setAssignSpoolModal({
  5589. printerId: printer.id,
  5590. amsId: ams.id,
  5591. trayId: slotIdx,
  5592. trayInfo: {
  5593. type: '',
  5594. material: undefined,
  5595. profile: '',
  5596. color: '',
  5597. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5598. },
  5599. })}
  5600. >
  5601. {slotVisual}
  5602. </EmptySlotHoverCard>
  5603. )}
  5604. </div>
  5605. );
  5606. })}
  5607. </div>
  5608. </div>
  5609. );
  5610. })}
  5611. {/* HT AMS units */}
  5612. {htAms.map((ams) => {
  5613. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5614. const tray = ams.tray[0];
  5615. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5616. const isEmpty = !tray?.tray_type;
  5617. const emptyKind = getEmptySlotKind(tray);
  5618. // Check if this is the currently loaded tray
  5619. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5620. const isActive = effectiveTrayNow === globalTrayId;
  5621. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5622. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5623. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5624. // Get cloud preset info if available
  5625. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5626. // Get saved slot preset mapping (for user-configured slots)
  5627. const slotPreset = slotPresets?.[globalTrayId];
  5628. // Only trusted while it still describes what the printer reports in the
  5629. // slot: the row survives a spool swap, and the display chain below puts
  5630. // it ahead of the live filament id (see slotPresetDescribesTray).
  5631. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5632. ? slotPreset?.preset_name
  5633. : undefined;
  5634. const htSlotId = tray?.id ?? 0;
  5635. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5636. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5637. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5638. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5639. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5640. const htInventoryFill = (() => {
  5641. const sp = htInventoryAssignment?.spool;
  5642. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5643. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5644. }
  5645. return null;
  5646. })();
  5647. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5648. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5649. ? null : htInventoryFill;
  5650. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5651. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5652. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5653. : undefined;
  5654. const htSlotSpoolForFill = htSlotAssignmentForFill
  5655. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5656. : undefined;
  5657. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5658. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5659. : null;
  5660. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5661. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5662. : htResolvedInventoryFill !== null ? 'inventory' as const
  5663. : hasFillLevel ? 'ams' as const
  5664. : undefined;
  5665. // Build filament data for hover card
  5666. const filamentData = tray?.tray_type ? {
  5667. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5668. profile: slotPresetName || (htSlotSpoolForFill ? [htSlotSpoolForFill.brand, htSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || htSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || htInventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  5669. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5670. colorHex: tray.tray_color || null,
  5671. kFactor: formatKValue(tray.k),
  5672. fillLevel: htEffectiveFill,
  5673. trayUuid: tray.tray_uuid || null,
  5674. tagUid: tray.tag_uid || null,
  5675. fillSource: htFillSource,
  5676. } : null;
  5677. // Check if this specific slot is being refreshed
  5678. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5679. refreshingSlot?.slotId === htSlotId;
  5680. // #1762 (comment 2): active print-slot index for this HT slot.
  5681. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5682. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5683. ? `P${htActivePrintSlotIdx + 1}`
  5684. : null;
  5685. // Slot visual content (goes inside hover card)
  5686. const slotVisual = (
  5687. <div
  5688. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5689. isExpectedSlot
  5690. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5691. : isRanOutSlot
  5692. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5693. : isActive
  5694. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5695. : ''
  5696. }`}
  5697. >
  5698. {isExpectedSlot && (
  5699. <span
  5700. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5701. title={t('printers.expectedSlot.title')}
  5702. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  5703. >
  5704. ↓
  5705. </span>
  5706. )}
  5707. {htActivePrintSlotLabel && (
  5708. <span
  5709. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5710. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5711. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  5712. >
  5713. {htActivePrintSlotLabel}
  5714. </span>
  5715. )}
  5716. {/* Filament color circle with 1-based slot number centered inside */}
  5717. <FilamentSlotCircle
  5718. trayColor={tray?.tray_color}
  5719. trayType={tray?.tray_type}
  5720. isEmpty={isEmpty}
  5721. emptyKind={emptyKind}
  5722. slotNumber={1}
  5723. />
  5724. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5725. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5726. </div>
  5727. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5728. {/* Fill bar */}
  5729. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5730. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5731. <div
  5732. className="h-full rounded-full transition-all"
  5733. style={{
  5734. width: `${htEffectiveFill}%`,
  5735. backgroundColor: getFillBarColor(htEffectiveFill),
  5736. }}
  5737. />
  5738. )}
  5739. </div>
  5740. </div>
  5741. );
  5742. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5743. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5744. // Without this override, the L view squishes HT into a sliver next to the
  5745. // 4-slot AMS neighbors.
  5746. // 11rem holds one slot plus the temperature/humidity
  5747. // column beside it; both grow with the body scale.
  5748. const htCardWidth = scaledRem(11);
  5749. const htCardStyle: React.CSSProperties = {
  5750. flex: `1 1 ${htCardWidth}`,
  5751. minWidth: htCardWidth,
  5752. // An AMS-HT is never wider than a full AMS. Without a
  5753. // ceiling, a unit that wraps onto a line of its own is
  5754. // the only flex item there and grow stretches its single
  5755. // slot across the entire card, leaving the readings
  5756. // stranded at the far edge.
  5757. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5758. };
  5759. return (
  5760. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5761. {/* Row 1: Label + Nozzle + Drying */}
  5762. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5763. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5764. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5765. <AmsNameHoverCard
  5766. ams={ams}
  5767. printerId={printer.id}
  5768. label={getAmsLabel(ams.id, ams.tray.length)}
  5769. amsLabels={amsLabels}
  5770. canEdit={hasPermission('printers:update')}
  5771. onSaved={refetchAmsLabels}
  5772. >
  5773. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5774. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5775. </span>
  5776. </AmsNameHoverCard>
  5777. {sideBadge?.kind === 'inlet' ? (
  5778. <InletBadge
  5779. inlet={sideBadge.inlet}
  5780. title={t('printers.amsSwitchInletTooltip', {
  5781. inlet: sideBadge.inlet,
  5782. side: FTS_INLET_SIDE[sideBadge.inlet],
  5783. })}
  5784. />
  5785. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5786. <NozzleBadge side={sideBadge.side} />
  5787. ) : null}
  5788. </div>
  5789. {/* Drying button for HT AMS */}
  5790. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5791. <div className="relative ml-auto">
  5792. <button
  5793. disabled={status.drying_screen_only}
  5794. onClick={(e) => {
  5795. if (ams.dry_time > 0) {
  5796. stopDryingMutation.mutate(ams.id);
  5797. } else if (dryingPopoverAmsId === ams.id) {
  5798. setDryingPopoverAmsId(null);
  5799. } else {
  5800. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5801. }
  5802. }}
  5803. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5804. ams.dry_time > 0
  5805. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5806. : status.drying_screen_only
  5807. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5808. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5809. }`}
  5810. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5811. >
  5812. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5813. </button>
  5814. </div>
  5815. )}
  5816. </div>
  5817. {/* HT AMS drying status bar. Same not-running split as the
  5818. standard-AMS bar above: a frozen countdown is not a
  5819. running cycle. */}
  5820. {ams.dry_time > 0 && (
  5821. <div className={`flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg px-2 py-1 text-[length:var(--pc-t9,9px)] ${ams.dry_countdown_stalled ? 'bg-slate-100 dark:bg-slate-500/10' : 'bg-amber-50 dark:bg-amber-500/10'}`} title={ams.dry_countdown_stalled ? t('printers.drying.notRunningHint') : undefined}>
  5822. {ams.dry_countdown_stalled
  5823. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5824. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5825. {ams.dry_countdown_stalled && (
  5826. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5827. )}
  5828. {ams.dry_filament && (
  5829. <span className={`${ams.dry_countdown_stalled ? 'text-slate-500/90 dark:text-slate-400/80' : 'text-amber-700/80 dark:text-amber-300/70'} text-[length:var(--pc-t8,8px)] truncate`}>
  5830. {ams.dry_target_temp != null
  5831. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5832. : ams.dry_filament}
  5833. </span>
  5834. )}
  5835. {!ams.dry_countdown_stalled && (
  5836. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5837. {ams.dry_time >= 60
  5838. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5839. : `${ams.dry_time}m`}
  5840. </span>
  5841. )}
  5842. {!status.drying_screen_only && (
  5843. <button
  5844. onClick={() => stopDryingMutation.mutate(ams.id)}
  5845. disabled={stopDryingMutation.isPending}
  5846. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0"
  5847. title={t('printers.drying.stop')}
  5848. >
  5849. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5850. </button>
  5851. )}
  5852. </div>
  5853. )}
  5854. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5855. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5856. {/* Slot wrapper with loading overlay */}
  5857. <div className="relative group flex-1" style={htSlotStyle}>
  5858. {/* Loading overlay during RFID re-read */}
  5859. {isHtRefreshing && (
  5860. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5861. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5862. </div>
  5863. )}
  5864. {/* Hover card wraps only the visual content */}
  5865. {filamentData ? (
  5866. <FilamentHoverCard
  5867. data={filamentData}
  5868. actions={renderAmsSlotActions({
  5869. amsId: ams.id,
  5870. slotId: htSlotId,
  5871. loadTrayId: ams.id * 4 + htSlotId,
  5872. isRefreshing: isHtRefreshing,
  5873. })}
  5874. spoolman={{
  5875. enabled: spoolmanEnabled,
  5876. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5877. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5878. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5879. spoolmanUrl,
  5880. syncMode: spoolmanSyncMode,
  5881. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5882. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5883. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5884. setLinkSpoolModal({
  5885. tagUid: filamentData.tagUid || linkTag,
  5886. trayUuid: filamentData.trayUuid || '',
  5887. printerId: printer.id,
  5888. amsId: ams.id,
  5889. trayId: htSlotId,
  5890. });
  5891. } : undefined,
  5892. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5893. }}
  5894. inventory={(() => {
  5895. if (spoolmanEnabled) {
  5896. if (spoolmanLoading) return undefined;
  5897. const slotAssignment = htSlotAssignmentForFill;
  5898. const spoolmanSpool = htSlotSpoolForFill;
  5899. return {
  5900. assignedSpool: spoolmanSpool ? {
  5901. id: spoolmanSpool.id,
  5902. material: spoolmanSpool.material,
  5903. subtype: spoolmanSpool.subtype,
  5904. brand: spoolmanSpool.brand ?? null,
  5905. color_name: spoolmanSpool.color_name ?? null,
  5906. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5907. // The spool's own swatch (#2967). Spoolman carries the
  5908. // extra stops but has no effect field at all, so those
  5909. // rolls gradient and never shimmer.
  5910. rgba: spoolmanSpool.rgba ?? null,
  5911. extra_colors: spoolmanSpool.extra_colors ?? null,
  5912. effect_type: spoolmanSpool.effect_type ?? null,
  5913. remainingWeightGrams: spoolmanSpool.label_weight
  5914. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5915. : undefined,
  5916. } : null,
  5917. onAssignSpool: () => setAssignSpoolModal({
  5918. printerId: printer.id,
  5919. amsId: ams.id,
  5920. trayId: htSlotId,
  5921. trayInfo: {
  5922. type: tray?.tray_type || filamentData.profile,
  5923. material: tray?.tray_type ?? undefined,
  5924. profile: filamentData.profile,
  5925. color: filamentData.colorHex || '',
  5926. location: getAmsLabel(ams.id, ams.tray.length),
  5927. },
  5928. }),
  5929. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5930. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5931. };
  5932. }
  5933. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5934. return {
  5935. assignedSpool: assignment?.spool ? {
  5936. id: assignment.spool.id,
  5937. material: assignment.spool.material,
  5938. subtype: assignment.spool.subtype,
  5939. brand: assignment.spool.brand,
  5940. color_name: assignment.spool.color_name,
  5941. // The spool's own swatch (#2967).
  5942. rgba: assignment.spool.rgba ?? null,
  5943. extra_colors: assignment.spool.extra_colors ?? null,
  5944. effect_type: assignment.spool.effect_type ?? null,
  5945. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5946. } : null,
  5947. onAssignSpool: () => setAssignSpoolModal({
  5948. printerId: printer.id,
  5949. amsId: ams.id,
  5950. trayId: htSlotId,
  5951. trayInfo: {
  5952. type: tray?.tray_type || filamentData.profile,
  5953. material: tray?.tray_type ?? undefined,
  5954. profile: filamentData.profile,
  5955. color: filamentData.colorHex || '',
  5956. location: getAmsLabel(ams.id, ams.tray.length),
  5957. },
  5958. }),
  5959. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5960. isAssigned: !!assignment || isBambuLabSpool(tray),
  5961. };
  5962. })()}
  5963. configureSlot={{
  5964. enabled: hasPermission('printers:control'),
  5965. onConfigure: () => setConfigureSlotModal({
  5966. amsId: ams.id,
  5967. trayId: htSlotId,
  5968. trayCount: ams.tray.length,
  5969. trayType: tray?.tray_type || undefined,
  5970. trayColor: tray?.tray_color || undefined,
  5971. traySubBrands: tray?.tray_sub_brands || undefined,
  5972. trayInfoIdx: tray?.tray_info_idx || undefined,
  5973. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5974. caliIdx: tray?.cali_idx,
  5975. savedPresetId: slotPreset?.preset_id,
  5976. }),
  5977. }}
  5978. >
  5979. {slotVisual}
  5980. </FilamentHoverCard>
  5981. ) : (
  5982. <EmptySlotHoverCard
  5983. kind={emptyKind ?? undefined}
  5984. actions={renderAmsSlotActions({
  5985. amsId: ams.id,
  5986. slotId: htSlotId,
  5987. loadTrayId: ams.id * 4 + htSlotId,
  5988. isRefreshing: isHtRefreshing,
  5989. })}
  5990. configureSlot={{
  5991. enabled: hasPermission('printers:control'),
  5992. onConfigure: () => setConfigureSlotModal({
  5993. amsId: ams.id,
  5994. trayId: htSlotId,
  5995. trayCount: ams.tray.length,
  5996. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5997. }),
  5998. }}
  5999. onAssignSpool={() => setAssignSpoolModal({
  6000. printerId: printer.id,
  6001. amsId: ams.id,
  6002. trayId: htSlotId,
  6003. trayInfo: {
  6004. type: '',
  6005. material: undefined,
  6006. profile: '',
  6007. color: '',
  6008. location: getAmsLabel(ams.id, ams.tray.length),
  6009. },
  6010. })}
  6011. >
  6012. {slotVisual}
  6013. </EmptySlotHoverCard>
  6014. )}
  6015. </div>
  6016. {/* Stats stacked vertically: Temp on top, Humidity below */}
  6017. {(ams.humidity != null || ams.temp != null) && (
  6018. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  6019. {ams.temp != null && (
  6020. <TemperatureIndicator
  6021. temp={ams.temp}
  6022. goodThreshold={amsThresholds?.tempGood}
  6023. fairThreshold={amsThresholds?.tempFair}
  6024. onClick={() => setAmsHistoryModal({
  6025. amsId: ams.id,
  6026. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  6027. mode: 'temperature',
  6028. })}
  6029. compact
  6030. />
  6031. )}
  6032. {ams.humidity != null && (
  6033. <HumidityIndicator
  6034. humidity={ams.humidity}
  6035. goodThreshold={amsThresholds?.humidityGood}
  6036. fairThreshold={amsThresholds?.humidityFair}
  6037. onClick={() => setAmsHistoryModal({
  6038. amsId: ams.id,
  6039. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  6040. mode: 'humidity',
  6041. })}
  6042. compact
  6043. />
  6044. )}
  6045. </div>
  6046. )}
  6047. </div>
  6048. </div>
  6049. );
  6050. })}
  6051. {/* External spool(s) - grouped in one card like regular AMS */}
  6052. {status.vt_tray.length > 0 && showExternalSpool && (
  6053. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  6054. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  6055. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  6056. </div>
  6057. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  6058. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  6059. const extTrayId = extTray.id ?? 254;
  6060. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  6061. // generically — use active_extruder to determine L vs R:
  6062. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  6063. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  6064. ? (extTrayId === 254 && status.active_extruder === 1) ||
  6065. (extTrayId === 255 && status.active_extruder === 0)
  6066. : effectiveTrayNow === extTrayId;
  6067. const slotTrayId = extTrayId - 254; // 0 or 1
  6068. const extLabel = isDualNozzle
  6069. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6070. : '';
  6071. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6072. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6073. // Only trusted while it still describes what the printer reports in the
  6074. // slot: the row survives a spool swap, and the display chain below puts
  6075. // it ahead of the live filament id (see slotPresetDescribesTray).
  6076. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx)
  6077. ? extSlotPreset?.preset_name
  6078. : undefined;
  6079. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6080. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6081. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6082. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6083. const extInventoryFill = (() => {
  6084. const sp = extInventoryAssignment?.spool;
  6085. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6086. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6087. }
  6088. return null;
  6089. })();
  6090. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6091. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6092. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6093. ? null : extInventoryFill;
  6094. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6095. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6096. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6097. : undefined;
  6098. const extSlotSpoolForFill = extSlotAssignmentForFill
  6099. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6100. : undefined;
  6101. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6102. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6103. : null;
  6104. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6105. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6106. : extResolvedInventoryFill !== null ? 'inventory' as const
  6107. : extHasFillLevel ? 'ams' as const
  6108. : undefined;
  6109. const extFilamentData = {
  6110. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6111. profile: extSlotPresetName || (extSlotSpoolForFill ? [extSlotSpoolForFill.brand, extSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || extSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || extInventoryAssignment?.spool?.slicer_filament_name || extCloudInfo?.name || extTray.tray_sub_brands || extTray.tray_type || 'Unknown',
  6112. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6113. colorHex: extTray.tray_color || null,
  6114. kFactor: formatKValue(extTray.k),
  6115. fillLevel: extEffectiveFill,
  6116. trayUuid: extTray.tray_uuid || null,
  6117. tagUid: extTray.tag_uid || null,
  6118. fillSource: extFillSource,
  6119. };
  6120. const isEmpty = !extTray.tray_type;
  6121. const emptyKind = getEmptySlotKind(extTray);
  6122. const extSlotContent = (
  6123. <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' : ''}`}>
  6124. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6125. the separate Ext-L/Ext-R caption that made the row taller than
  6126. regular AMS slots), 1-based slot number on single-nozzle. */}
  6127. <FilamentSlotCircle
  6128. trayColor={extTray.tray_color}
  6129. trayType={extTray.tray_type}
  6130. isEmpty={isEmpty}
  6131. emptyKind={emptyKind}
  6132. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6133. />
  6134. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6135. {extTray.tray_type || t('ams.slotEmpty')}
  6136. </div>
  6137. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6138. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6139. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6140. <div
  6141. className="h-full rounded-full transition-all"
  6142. style={{
  6143. width: `${extEffectiveFill}%`,
  6144. backgroundColor: getFillBarColor(extEffectiveFill),
  6145. }}
  6146. />
  6147. )}
  6148. </div>
  6149. </div>
  6150. );
  6151. return (
  6152. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6153. {!isEmpty ? (
  6154. <FilamentHoverCard
  6155. data={extFilamentData}
  6156. actions={renderAmsSlotActions({
  6157. amsId: 255,
  6158. slotId: slotTrayId,
  6159. loadTrayId: extTrayId,
  6160. includeRfid: false,
  6161. })}
  6162. spoolman={{
  6163. enabled: spoolmanEnabled,
  6164. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6165. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6166. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6167. spoolmanUrl,
  6168. syncMode: spoolmanSyncMode,
  6169. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6170. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6171. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6172. setLinkSpoolModal({
  6173. tagUid: extFilamentData.tagUid || linkTag,
  6174. trayUuid: extFilamentData.trayUuid || '',
  6175. printerId: printer.id,
  6176. amsId: 255,
  6177. trayId: slotTrayId,
  6178. });
  6179. } : undefined,
  6180. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6181. }}
  6182. inventory={(() => {
  6183. if (spoolmanEnabled) {
  6184. if (spoolmanLoading) return undefined;
  6185. const slotAssignment = extSlotAssignmentForFill;
  6186. const spoolmanSpool = extSlotSpoolForFill;
  6187. return {
  6188. assignedSpool: spoolmanSpool ? {
  6189. id: spoolmanSpool.id,
  6190. material: spoolmanSpool.material,
  6191. subtype: spoolmanSpool.subtype,
  6192. brand: spoolmanSpool.brand ?? null,
  6193. color_name: spoolmanSpool.color_name ?? null,
  6194. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6195. // The spool's own swatch (#2967). Spoolman carries the
  6196. // extra stops but has no effect field at all, so those
  6197. // rolls gradient and never shimmer.
  6198. rgba: spoolmanSpool.rgba ?? null,
  6199. extra_colors: spoolmanSpool.extra_colors ?? null,
  6200. effect_type: spoolmanSpool.effect_type ?? null,
  6201. remainingWeightGrams: spoolmanSpool.label_weight
  6202. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6203. : undefined,
  6204. } : null,
  6205. onAssignSpool: () => setAssignSpoolModal({
  6206. printerId: printer.id,
  6207. amsId: 255,
  6208. trayId: slotTrayId,
  6209. trayInfo: {
  6210. type: extTray.tray_type || extFilamentData.profile,
  6211. material: extTray.tray_type ?? undefined,
  6212. profile: extFilamentData.profile,
  6213. color: extFilamentData.colorHex || '',
  6214. location: extLabel || t('printers.external'),
  6215. },
  6216. }),
  6217. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6218. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6219. };
  6220. }
  6221. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6222. return {
  6223. assignedSpool: assignment?.spool ? {
  6224. id: assignment.spool.id,
  6225. material: assignment.spool.material,
  6226. subtype: assignment.spool.subtype,
  6227. brand: assignment.spool.brand,
  6228. color_name: assignment.spool.color_name,
  6229. // The spool's own swatch (#2967).
  6230. rgba: assignment.spool.rgba ?? null,
  6231. extra_colors: assignment.spool.extra_colors ?? null,
  6232. effect_type: assignment.spool.effect_type ?? null,
  6233. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6234. } : null,
  6235. onAssignSpool: () => setAssignSpoolModal({
  6236. printerId: printer.id,
  6237. amsId: 255,
  6238. trayId: slotTrayId,
  6239. trayInfo: {
  6240. type: extTray.tray_type || extFilamentData.profile,
  6241. material: extTray.tray_type ?? undefined,
  6242. profile: extFilamentData.profile,
  6243. color: extFilamentData.colorHex || '',
  6244. location: extLabel || t('printers.external'),
  6245. },
  6246. }),
  6247. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6248. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6249. };
  6250. })()}
  6251. configureSlot={{
  6252. enabled: hasPermission('printers:control'),
  6253. onConfigure: () => setConfigureSlotModal({
  6254. amsId: 255,
  6255. trayId: slotTrayId,
  6256. trayCount: 1,
  6257. trayType: extTray.tray_type || undefined,
  6258. trayColor: extTray.tray_color || undefined,
  6259. traySubBrands: extTray.tray_sub_brands || undefined,
  6260. trayInfoIdx: extTray.tray_info_idx || undefined,
  6261. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6262. caliIdx: extTray.cali_idx,
  6263. savedPresetId: extSlotPreset?.preset_id,
  6264. }),
  6265. }}
  6266. >
  6267. {extSlotContent}
  6268. </FilamentHoverCard>
  6269. ) : (
  6270. <EmptySlotHoverCard
  6271. kind={emptyKind ?? undefined}
  6272. actions={renderAmsSlotActions({
  6273. amsId: 255,
  6274. slotId: slotTrayId,
  6275. loadTrayId: extTrayId,
  6276. includeRfid: false,
  6277. })}
  6278. configureSlot={{
  6279. enabled: hasPermission('printers:control'),
  6280. onConfigure: () => setConfigureSlotModal({
  6281. amsId: 255,
  6282. trayId: slotTrayId,
  6283. trayCount: 1,
  6284. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6285. }),
  6286. }}
  6287. onAssignSpool={() => setAssignSpoolModal({
  6288. printerId: printer.id,
  6289. amsId: 255,
  6290. trayId: slotTrayId,
  6291. trayInfo: {
  6292. type: '',
  6293. material: undefined,
  6294. profile: '',
  6295. color: '',
  6296. location: `External Slot ${slotTrayId + 1}`,
  6297. },
  6298. })}
  6299. >
  6300. {extSlotContent}
  6301. </EmptySlotHoverCard>
  6302. )}
  6303. </div>
  6304. );
  6305. })}
  6306. </div>
  6307. </div>
  6308. )}
  6309. </div>
  6310. </div>
  6311. );
  6312. })()}
  6313. </>
  6314. )}
  6315. {/* Powered-down printer with a dirty plate: the status block above renders
  6316. nothing without a live connection, so the plate-clear control gets its own
  6317. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6318. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6319. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6320. expandedClearPlateButton
  6321. )}
  6322. {/* Bottom block (power row + action bar). Wrapped together so the
  6323. power row hugs the action bar at the card bottom instead of
  6324. floating up when there's less filament content above. */}
  6325. {viewMode === 'expanded' && (
  6326. <div className="mt-auto">
  6327. {smartPlug && (
  6328. <div className="pt-3">
  6329. <div className="flex items-center gap-2 mb-2">
  6330. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6331. {t('printers.power', 'Power')}
  6332. </span>
  6333. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6334. </div>
  6335. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6336. {/* Plug name + current power */}
  6337. <div className="flex items-center gap-2 min-w-0 pl-1">
  6338. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6339. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6340. <span
  6341. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[length:var(--pc-t10,10px)] font-medium flex-shrink-0"
  6342. title={t('smartPlugs.power')}
  6343. >
  6344. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6345. </span>
  6346. </div>
  6347. {/* Spacer */}
  6348. <div className="flex-1" />
  6349. <div className="flex items-center gap-2">
  6350. {/* Auto-off */}
  6351. <button
  6352. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6353. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6354. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6355. 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 ${
  6356. !hasPermission('smart_plugs:control')
  6357. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6358. : smartPlug.auto_off || smartPlug.auto_off_executed
  6359. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6360. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6361. }`}
  6362. >
  6363. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6364. </button>
  6365. <button
  6366. onClick={() => {
  6367. if (plugStatus?.state === 'ON') {
  6368. setShowPowerOffConfirm(true);
  6369. } else {
  6370. setShowPowerOnConfirm(true);
  6371. }
  6372. }}
  6373. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6374. 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 ${
  6375. !hasPermission('smart_plugs:control')
  6376. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6377. : plugStatus?.state === 'ON'
  6378. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6379. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6380. }`}
  6381. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6382. >
  6383. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6384. </button>
  6385. </div>
  6386. </div>
  6387. {/* HA entity buttons row */}
  6388. {scriptPlugs && scriptPlugs.length > 0 && (
  6389. <div className="flex items-center gap-2 mt-2">
  6390. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6391. <span className="text-xs text-bambu-gray">HA:</span>
  6392. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6393. <div className="flex flex-wrap gap-1">
  6394. {scriptPlugs.map(script => {
  6395. const isScript = script.ha_entity_id?.startsWith('script.');
  6396. return (
  6397. <button
  6398. key={script.id}
  6399. onClick={() => {
  6400. if (isScript) {
  6401. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6402. } else {
  6403. setHaToggleConfirm(script);
  6404. }
  6405. }}
  6406. disabled={runScriptMutation.isPending}
  6407. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6408. className="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1"
  6409. >
  6410. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6411. {script.name}
  6412. </button>
  6413. );
  6414. })}
  6415. </div>
  6416. </div>
  6417. )}
  6418. </div>
  6419. )}
  6420. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6421. a printer can have an enclosure door contact without having a plug,
  6422. and nesting it there would hide the row on exactly those setups. */}
  6423. <PrinterHASensorRow printerId={printer.id} />
  6424. {/* Connection Info & Actions */}
  6425. <div className="pt-4">
  6426. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6427. <div className="flex items-center justify-between gap-2">
  6428. {printerActionsMenu}
  6429. <div className="flex items-center justify-end gap-2 flex-wrap">
  6430. {/* Camera split button: the icon opens whichever view was used
  6431. last, the caret picks between the two and remembers it.
  6432. Replaces the old Settings > General > Camera switch, which
  6433. made choosing between an overlay and a window a trip to
  6434. another page for something you decide per camera. */}
  6435. <div className="flex items-center flex-shrink-0">
  6436. <Button
  6437. variant="secondary"
  6438. size="sm"
  6439. onClick={() => openCameraIn(cameraViewMode)}
  6440. disabled={!status?.connected || !hasPermission('camera:view')}
  6441. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6442. className={`${footerIconButtonClass} !rounded-r-none`}
  6443. >
  6444. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6445. </Button>
  6446. <Button
  6447. variant="secondary"
  6448. size="sm"
  6449. onClick={(e) => {
  6450. // No open/close toggle: the menu's own outside-mousedown
  6451. // handler has already dismissed it by the time this lands.
  6452. const rect = e.currentTarget.getBoundingClientRect();
  6453. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6454. }}
  6455. disabled={!status?.connected || !hasPermission('camera:view')}
  6456. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6457. aria-label={t('settings.cameraViewMode')}
  6458. // Not footerIconButtonClass plus an override: both widths
  6459. // would carry !important and the stylesheet's own order,
  6460. // not this one, would decide which won.
  6461. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6462. >
  6463. <ChevronDown className="w-3 h-3" />
  6464. </Button>
  6465. </div>
  6466. {cameraMenuAnchor && (
  6467. <ContextMenu
  6468. x={cameraMenuAnchor.x}
  6469. y={cameraMenuAnchor.y}
  6470. items={cameraViewModeMenuItems}
  6471. onClose={() => setCameraMenuAnchor(null)}
  6472. />
  6473. )}
  6474. <Button
  6475. variant="secondary"
  6476. size="sm"
  6477. onClick={() => setShowFileManager(true)}
  6478. disabled={!hasPermission('printers:files')}
  6479. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6480. className={footerIconButtonClass}
  6481. >
  6482. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6483. </Button>
  6484. {/* Shown whatever the printer is doing (#2849): this uploads a
  6485. file and queues it, which a busy or offline printer is no
  6486. reason to refuse -- it only means the item waits. Hiding it
  6487. while the drop zone accepted the same file would have left
  6488. the two routes into this flow disagreeing. */}
  6489. <Button
  6490. size="sm"
  6491. onClick={() => setShowUploadForPrint(true)}
  6492. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6493. title={
  6494. !hasPermission('library:upload')
  6495. ? t('fileManager.noPermissionUpload')
  6496. : !hasPermission('queue:create')
  6497. ? t('fileManager.noPermissionAddToQueue')
  6498. : t('common.print')
  6499. }
  6500. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6501. >
  6502. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6503. {t('common.print')}
  6504. </Button>
  6505. </div>
  6506. </div>
  6507. </div>
  6508. </div>
  6509. )}
  6510. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6511. card's horizontal padding instead of running full-bleed into the
  6512. rounded bottom edge. */}
  6513. <ScheduledDryingBanner
  6514. printerId={printer.id}
  6515. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6516. timeFormat={timeFormat}
  6517. />
  6518. </CardContent>
  6519. {/* File Manager Modal */}
  6520. {showFileManager && (
  6521. <FileManagerModal
  6522. printerId={printer.id}
  6523. printerName={printer.name}
  6524. onClose={() => setShowFileManager(false)}
  6525. />
  6526. )}
  6527. {/* Upload for Print Modal */}
  6528. {showUploadForPrint && (
  6529. <FileUploadModal
  6530. folderId={null}
  6531. onClose={() => setShowUploadForPrint(false)}
  6532. onUploadComplete={() => {}}
  6533. autoUpload
  6534. accept=".gcode,.3mf"
  6535. validateFile={(file) => {
  6536. const lower = file.name.toLowerCase();
  6537. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6538. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6539. }
  6540. }}
  6541. onFileUploaded={(uploadedFile) => {
  6542. // Check printer compatibility if sliced_for_model is available in metadata
  6543. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6544. const printerModel = mapModelCode(printer.model);
  6545. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6546. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6547. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6548. }
  6549. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6550. }}
  6551. />
  6552. )}
  6553. {/* Print Modal (after upload) */}
  6554. {printAfterUpload && (
  6555. <PrintModal
  6556. mode="create"
  6557. libraryFileId={printAfterUpload.id}
  6558. archiveName={printAfterUpload.filename}
  6559. initialSelectedPrinterIds={[printer.id]}
  6560. onClose={() => setPrintAfterUpload(null)}
  6561. onSuccess={() => setPrintAfterUpload(null)}
  6562. cleanupLibraryAfterDispatch
  6563. />
  6564. )}
  6565. {/* MQTT Debug Modal */}
  6566. {showMQTTDebug && (
  6567. <MQTTDebugModal
  6568. printerId={printer.id}
  6569. printerName={printer.name}
  6570. onClose={() => setShowMQTTDebug(false)}
  6571. />
  6572. )}
  6573. {showDiagnostic && (
  6574. <ConnectionDiagnosticModal
  6575. printerId={printer.id}
  6576. printerName={printer.name}
  6577. onClose={() => setShowDiagnostic(false)}
  6578. />
  6579. )}
  6580. {showPrinterInfo && (
  6581. <PrinterInfoModal
  6582. printer={printer}
  6583. status={status}
  6584. totalPrintHours={maintenanceInfo?.total_print_hours}
  6585. onClose={closePrinterInfo}
  6586. />
  6587. )}
  6588. {/* Plate Check Result Modal */}
  6589. {plateCheckResult && (
  6590. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6591. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6592. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6593. <div className="flex items-center gap-2">
  6594. {plateCheckResult.needs_calibration ? (
  6595. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6596. ) : plateCheckResult.is_empty ? (
  6597. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6598. ) : (
  6599. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6600. )}
  6601. <h2 className="text-lg font-semibold text-white">
  6602. Build Plate Check
  6603. </h2>
  6604. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6605. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6606. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6607. </span>
  6608. )}
  6609. </div>
  6610. <button
  6611. onClick={() => closePlateCheckModal()}
  6612. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6613. >
  6614. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6615. </button>
  6616. </div>
  6617. <div className="p-4 space-y-4">
  6618. {plateCheckResult.needs_calibration ? (
  6619. <>
  6620. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6621. <p className="font-medium text-blue-700 dark:text-blue-400">
  6622. {t('printers.plateDetection.calibrationRequired')}
  6623. </p>
  6624. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6625. </div>
  6626. <div className="text-sm text-bambu-gray space-y-2">
  6627. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6628. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6629. </div>
  6630. </>
  6631. ) : (
  6632. <>
  6633. <div className={`p-3 rounded-lg ${plateCheckResult.is_empty ? 'bg-green-100 dark:bg-green-500/20 border border-green-300 dark:border-green-500/50' : 'bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-300 dark:border-yellow-500/50'}`}>
  6634. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6635. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6636. </p>
  6637. <p className="text-sm text-bambu-gray mt-1">
  6638. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6639. </p>
  6640. </div>
  6641. {plateCheckResult.debug_image_url && (
  6642. <div>
  6643. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6644. <img
  6645. src={plateCheckResult.debug_image_url}
  6646. alt={t('printers.plateDetection.analysisPreview')}
  6647. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6648. />
  6649. <p className="text-xs text-bambu-gray mt-2">
  6650. {t('printers.plateDetection.analysisLegend')}
  6651. </p>
  6652. </div>
  6653. )}
  6654. <p className="text-xs text-bambu-gray">
  6655. {plateCheckResult.message}
  6656. </p>
  6657. </>
  6658. )}
  6659. {/* Saved References Grid */}
  6660. {plateReferences && plateReferences.references.length > 0 && (
  6661. <div className="mt-4">
  6662. <div className="flex items-center gap-2 mb-2">
  6663. <p className="text-sm font-medium text-white shrink-0">
  6664. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6665. </p>
  6666. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6667. </div>
  6668. <div className="grid grid-cols-5 gap-2">
  6669. {plateReferences.references.map((ref) => (
  6670. <div key={ref.index} className="relative group">
  6671. <img
  6672. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6673. alt={ref.label || `Reference ${ref.index + 1}`}
  6674. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6675. />
  6676. {/* Delete button */}
  6677. <button
  6678. onClick={() => handleDeleteRef(ref.index)}
  6679. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded can-hover:opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
  6680. title={t('printers.plateDetection.deleteReference')}
  6681. >
  6682. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6683. </button>
  6684. {/* Label */}
  6685. {editingRefLabel?.index === ref.index ? (
  6686. <input
  6687. type="text"
  6688. value={editingRefLabel.label}
  6689. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6690. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6691. onKeyDown={(e) => {
  6692. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6693. if (e.key === 'Escape') setEditingRefLabel(null);
  6694. }}
  6695. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6696. autoFocus
  6697. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6698. />
  6699. ) : (
  6700. <p
  6701. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6702. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6703. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6704. >
  6705. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6706. </p>
  6707. )}
  6708. {/* Timestamp */}
  6709. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6710. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6711. </p>
  6712. </div>
  6713. ))}
  6714. </div>
  6715. </div>
  6716. )}
  6717. {/* ROI Editor */}
  6718. {!plateCheckResult.needs_calibration && (
  6719. <div className="mt-4">
  6720. <div className="flex items-center justify-between mb-2">
  6721. <div className="flex min-w-0 flex-1 items-center gap-2">
  6722. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6723. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6724. </div>
  6725. {!editingRoi ? (
  6726. <Button
  6727. variant="ghost"
  6728. size="sm"
  6729. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6730. >
  6731. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6732. {t('common.edit')}
  6733. </Button>
  6734. ) : (
  6735. <div className="flex gap-1">
  6736. <Button
  6737. variant="ghost"
  6738. size="sm"
  6739. onClick={() => setEditingRoi(null)}
  6740. disabled={isSavingRoi}
  6741. >
  6742. {t('common.cancel')}
  6743. </Button>
  6744. <Button
  6745. size="sm"
  6746. onClick={handleSaveRoi}
  6747. disabled={isSavingRoi}
  6748. >
  6749. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6750. </Button>
  6751. </div>
  6752. )}
  6753. </div>
  6754. {editingRoi ? (
  6755. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6756. <div className="grid grid-cols-2 gap-3">
  6757. <div>
  6758. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6759. <input
  6760. type="range"
  6761. min="0"
  6762. max="0.9"
  6763. step="0.01"
  6764. value={editingRoi.x}
  6765. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6766. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6767. />
  6768. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6769. </div>
  6770. <div>
  6771. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6772. <input
  6773. type="range"
  6774. min="0"
  6775. max="0.9"
  6776. step="0.01"
  6777. value={editingRoi.y}
  6778. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6779. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6780. />
  6781. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6782. </div>
  6783. <div>
  6784. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6785. <input
  6786. type="range"
  6787. min="0.1"
  6788. max="1"
  6789. step="0.01"
  6790. value={editingRoi.w}
  6791. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6792. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6793. />
  6794. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6795. </div>
  6796. <div>
  6797. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6798. <input
  6799. type="range"
  6800. min="0.1"
  6801. max="1"
  6802. step="0.01"
  6803. value={editingRoi.h}
  6804. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6805. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6806. />
  6807. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6808. </div>
  6809. </div>
  6810. <p className="text-xs text-bambu-gray">
  6811. {t('printers.roi.instruction')}
  6812. </p>
  6813. </div>
  6814. ) : (
  6815. <p className="text-xs text-bambu-gray">
  6816. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6817. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6818. </p>
  6819. )}
  6820. </div>
  6821. )}
  6822. </div>
  6823. <div className="flex justify-end gap-2 p-4">
  6824. {plateCheckResult.needs_calibration ? (
  6825. <>
  6826. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6827. {t('common.cancel')}
  6828. </Button>
  6829. <Button
  6830. onClick={() => handleCalibratePlate()}
  6831. disabled={isCalibrating}
  6832. >
  6833. {isCalibrating ? (
  6834. <>
  6835. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6836. Calibrating...
  6837. </>
  6838. ) : (
  6839. 'Calibrate Empty Plate'
  6840. )}
  6841. </Button>
  6842. </>
  6843. ) : (
  6844. <>
  6845. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6846. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6847. </Button>
  6848. <Button onClick={() => closePlateCheckModal()}>
  6849. Close
  6850. </Button>
  6851. </>
  6852. )}
  6853. </div>
  6854. </div>
  6855. </div>
  6856. )}
  6857. {/* Power On Confirmation */}
  6858. {showPowerOnConfirm && smartPlug && (
  6859. <ConfirmModal
  6860. title={t('printers.confirm.powerOnTitle')}
  6861. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6862. confirmText={t('printers.confirm.powerOnButton')}
  6863. variant="default"
  6864. onConfirm={() => {
  6865. powerControlMutation.mutate('on');
  6866. setShowPowerOnConfirm(false);
  6867. }}
  6868. onCancel={() => setShowPowerOnConfirm(false)}
  6869. />
  6870. )}
  6871. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6872. disconnects MQTT, which stops progress tracking + completion
  6873. notifications for the in-flight job. Idle / FINISH / FAILED states
  6874. skip this dialog and toggle directly. */}
  6875. {confirmMaintenanceEnter && (
  6876. <ConfirmModal
  6877. title={t('printers.maintenance.confirmMidPrintTitle')}
  6878. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6879. confirmText={t('printers.maintenance.menuEnter')}
  6880. variant="danger"
  6881. onConfirm={() => {
  6882. maintenanceMutation.mutate(false);
  6883. setConfirmMaintenanceEnter(false);
  6884. }}
  6885. onCancel={() => setConfirmMaintenanceEnter(false)}
  6886. />
  6887. )}
  6888. {/* Power Off Confirmation */}
  6889. {showPowerOffConfirm && smartPlug && (
  6890. <ConfirmModal
  6891. title={t('printers.confirm.powerOffTitle')}
  6892. message={
  6893. status?.state === 'RUNNING'
  6894. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6895. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6896. }
  6897. confirmText={t('printers.confirm.powerOffButton')}
  6898. variant="danger"
  6899. onConfirm={() => {
  6900. powerControlMutation.mutate('off');
  6901. setShowPowerOffConfirm(false);
  6902. }}
  6903. onCancel={() => setShowPowerOffConfirm(false)}
  6904. />
  6905. )}
  6906. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6907. {haToggleConfirm && (
  6908. <ConfirmModal
  6909. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6910. message={
  6911. status?.state === 'RUNNING'
  6912. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6913. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6914. }
  6915. confirmText={t('printers.confirm.haToggleButton')}
  6916. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6917. onConfirm={() => {
  6918. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6919. setHaToggleConfirm(null);
  6920. }}
  6921. onCancel={() => setHaToggleConfirm(null)}
  6922. />
  6923. )}
  6924. {/* Stop Print Confirmation */}
  6925. {showStopConfirm && (
  6926. <ConfirmModal
  6927. title={t('printers.confirm.stopTitle')}
  6928. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6929. confirmText={t('printers.confirm.stopButton')}
  6930. variant="danger"
  6931. onConfirm={() => {
  6932. stopPrintMutation.mutate();
  6933. setShowStopConfirm(false);
  6934. }}
  6935. onCancel={() => setShowStopConfirm(false)}
  6936. />
  6937. )}
  6938. {/* Pause Print Confirmation */}
  6939. {showPauseConfirm && (
  6940. <ConfirmModal
  6941. title={t('printers.confirm.pauseTitle')}
  6942. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6943. confirmText={t('printers.confirm.pauseButton')}
  6944. variant="default"
  6945. onConfirm={() => {
  6946. pausePrintMutation.mutate();
  6947. setShowPauseConfirm(false);
  6948. }}
  6949. onCancel={() => setShowPauseConfirm(false)}
  6950. />
  6951. )}
  6952. {/* Resume Print Confirmation */}
  6953. {showResumeConfirm && (
  6954. <ConfirmModal
  6955. title={t('printers.confirm.resumeTitle')}
  6956. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6957. confirmText={t('printers.confirm.resumeButton')}
  6958. variant="default"
  6959. onConfirm={() => {
  6960. resumePrintMutation.mutate();
  6961. setShowResumeConfirm(false);
  6962. }}
  6963. onCancel={() => setShowResumeConfirm(false)}
  6964. />
  6965. )}
  6966. {/* Skip Objects Modal */}
  6967. <SkipObjectsModal
  6968. printerId={printer.id}
  6969. isOpen={showSkipObjectsModal}
  6970. onClose={() => setShowSkipObjectsModal(false)}
  6971. />
  6972. {/* HMS Error Modal */}
  6973. {showHMSModal && (
  6974. <HMSErrorModal
  6975. printerName={printer.name}
  6976. errors={status?.hms_errors || []}
  6977. onClose={() => setShowHMSModal(false)}
  6978. printerId={printer.id}
  6979. hasPermission={hasPermission}
  6980. runoutGuidance={runoutGuidance}
  6981. />
  6982. )}
  6983. {/* AI failure detection modal (#1546) */}
  6984. {showAiModal && (
  6985. <AiDetectionModal
  6986. printerName={printer.name}
  6987. detection={aiDetection}
  6988. lastError={aiLastError}
  6989. onClose={() => setShowAiModal(false)}
  6990. />
  6991. )}
  6992. {/* AMS Filament Backup status / control modal (#1762) */}
  6993. {amsBackupModalOpen && status && (
  6994. <AmsBackupModal
  6995. isOpen={amsBackupModalOpen}
  6996. state={status.ams_filament_backup}
  6997. amsUnits={status.ams}
  6998. amsExtruderMap={status.ams_extruder_map}
  6999. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  7000. canToggle={hasPermission('printers:control')}
  7001. pending={setAmsBackupMutation.isPending}
  7002. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  7003. onClose={() => setAmsBackupModalOpen(false)}
  7004. />
  7005. )}
  7006. {/* AMS History Modal */}
  7007. {amsHistoryModal && (
  7008. <AMSHistoryModal
  7009. isOpen={!!amsHistoryModal}
  7010. onClose={() => setAmsHistoryModal(null)}
  7011. printerId={printer.id}
  7012. printerName={printer.name}
  7013. amsId={amsHistoryModal.amsId}
  7014. amsLabel={amsHistoryModal.amsLabel}
  7015. initialMode={amsHistoryModal.mode}
  7016. thresholds={amsThresholds}
  7017. />
  7018. )}
  7019. {/* Heater History Modal (nozzle / bed / chamber) */}
  7020. {heaterHistoryModal && (
  7021. <HeaterHistoryModal
  7022. isOpen={!!heaterHistoryModal}
  7023. onClose={() => setHeaterHistoryModal(null)}
  7024. printerId={printer.id}
  7025. printerName={printer.name}
  7026. initialKind={heaterHistoryModal.initialKind}
  7027. availableKinds={heaterHistoryModal.availableKinds}
  7028. />
  7029. )}
  7030. {/* Link Spool Modal */}
  7031. {linkSpoolModal && (
  7032. <LinkSpoolModal
  7033. isOpen={!!linkSpoolModal}
  7034. onClose={() => setLinkSpoolModal(null)}
  7035. tagUid={linkSpoolModal.tagUid}
  7036. trayUuid={linkSpoolModal.trayUuid}
  7037. printerId={linkSpoolModal.printerId}
  7038. amsId={linkSpoolModal.amsId}
  7039. trayId={linkSpoolModal.trayId}
  7040. />
  7041. )}
  7042. {/* Assign Spool Modal */}
  7043. {assignSpoolModal && (
  7044. <AssignSpoolModal
  7045. isOpen={!!assignSpoolModal}
  7046. onClose={() => setAssignSpoolModal(null)}
  7047. printerId={assignSpoolModal.printerId}
  7048. amsId={assignSpoolModal.amsId}
  7049. trayId={assignSpoolModal.trayId}
  7050. trayInfo={assignSpoolModal.trayInfo}
  7051. spoolmanEnabled={!!spoolmanEnabled}
  7052. />
  7053. )}
  7054. {/* Configure AMS Slot Modal */}
  7055. {configureSlotModal && (
  7056. <ConfigureAmsSlotModal
  7057. isOpen={!!configureSlotModal}
  7058. onClose={() => setConfigureSlotModal(null)}
  7059. printerId={printer.id}
  7060. slotInfo={configureSlotModal}
  7061. printerModel={mapModelCode(printer.model) || undefined}
  7062. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  7063. onSuccess={() => {
  7064. // Refresh slot presets to show updated profile name
  7065. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  7066. // Printer status will update automatically via WebSocket when AMS data changes
  7067. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7068. }}
  7069. />
  7070. )}
  7071. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7072. {feedDirectionRequest && (
  7073. <FeedDirectionModal
  7074. slotLabel={feedDirectionRequest.slotLabel}
  7075. amsId={feedDirectionRequest.amsId}
  7076. slotId={feedDirectionRequest.slotId}
  7077. extruderSlots={status?.extruder_slots ?? {}}
  7078. isLoading={loadAmsTrayMutation.isPending}
  7079. onConfirm={(extruderId) =>
  7080. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7081. }
  7082. onCancel={() => setFeedDirectionRequest(null)}
  7083. />
  7084. )}
  7085. {/* Edit Printer Modal */}
  7086. {showEditModal && (
  7087. <EditPrinterModal
  7088. printer={printer}
  7089. onClose={() => setShowEditModal(false)}
  7090. />
  7091. )}
  7092. {/* Firmware Update Modal */}
  7093. {showFirmwareModal && firmwareInfo && (
  7094. <FirmwareUpdateModal
  7095. printer={printer}
  7096. firmwareInfo={firmwareInfo}
  7097. onClose={() => setShowFirmwareModal(false)}
  7098. />
  7099. )}
  7100. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7101. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7102. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7103. const sliderMin = 35;
  7104. const sliderMax = maxTemp + 10;
  7105. return (
  7106. <>
  7107. {/* Backdrop */}
  7108. <div
  7109. className="fixed inset-0 z-[100]"
  7110. data-testid="drying-popover-backdrop"
  7111. onMouseDown={() => {
  7112. // The click that dismisses the native datetime picker lands
  7113. // here; it must not close the popover. The input is still
  7114. // focused at mousedown, so remember that and swallow the
  7115. // matching click.
  7116. dryingBackdropSkipCloseRef.current =
  7117. dryingAtTimeInputRef.current !== null &&
  7118. document.activeElement === dryingAtTimeInputRef.current;
  7119. }}
  7120. onClick={() => {
  7121. if (dryingBackdropSkipCloseRef.current) {
  7122. dryingBackdropSkipCloseRef.current = false;
  7123. return;
  7124. }
  7125. setDryingPopoverAmsId(null);
  7126. }}
  7127. />
  7128. {/* An 'above' popover is anchored by its bottom edge (CSS
  7129. bottom) so late-appearing content grows it upward, staying on
  7130. screen and glued to the trigger. maxHeight caps to the space
  7131. on the anchored side; when the viewport is too short the body
  7132. scrolls and the footer stays pinned. dvh so iOS Safari's
  7133. bottom toolbar doesn't clip the footer. */}
  7134. <div
  7135. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7136. style={{
  7137. left: dryingPopoverPos.left,
  7138. ...(dryingPopoverPos.placement === 'above'
  7139. ? {
  7140. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7141. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7142. }
  7143. : {
  7144. top: dryingPopoverPos.top,
  7145. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7146. }),
  7147. }}
  7148. onClick={e => e.stopPropagation()}
  7149. >
  7150. {/* Header */}
  7151. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7152. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7153. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7154. </div>
  7155. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7156. {/* Body */}
  7157. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7158. {/* Filament type select */}
  7159. <div>
  7160. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7161. <ToolbarDropdown
  7162. value={dryingFilament}
  7163. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7164. onChange={fil => {
  7165. setDryingFilament(fil);
  7166. const preset = dryingPresets[fil];
  7167. if (preset) {
  7168. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7169. setDryingTemp(preset[key]);
  7170. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7171. }
  7172. }}
  7173. fullWidth
  7174. />
  7175. </div>
  7176. {/* Temperature */}
  7177. <div>
  7178. <div className="flex items-center justify-between mb-1">
  7179. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7180. <div className="flex items-center gap-1">
  7181. <input
  7182. type="number"
  7183. min={45}
  7184. max={maxTemp}
  7185. value={dryingTemp}
  7186. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  7187. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  7188. />
  7189. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7190. </div>
  7191. </div>
  7192. <input
  7193. type="range"
  7194. min={sliderMin}
  7195. max={sliderMax}
  7196. value={dryingTemp}
  7197. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7198. className="w-full h-1 accent-bambu-green cursor-pointer"
  7199. />
  7200. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7201. <span>45°C</span>
  7202. <span>{maxTemp}°C</span>
  7203. </div>
  7204. </div>
  7205. {/* Duration */}
  7206. <div>
  7207. <div className="flex items-center justify-between mb-1">
  7208. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7209. <div className="flex items-center gap-1">
  7210. <input
  7211. type="number"
  7212. min={1}
  7213. max={24}
  7214. value={dryingDuration}
  7215. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  7216. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  7217. />
  7218. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7219. </div>
  7220. </div>
  7221. <input
  7222. type="range"
  7223. min={1}
  7224. max={24}
  7225. value={dryingDuration}
  7226. onChange={e => setDryingDuration(Number(e.target.value))}
  7227. className="w-full h-1 accent-bambu-green cursor-pointer"
  7228. />
  7229. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7230. <span>1h</span>
  7231. <span>24h</span>
  7232. </div>
  7233. </div>
  7234. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7235. filament threaded out into the feed tube. The whole AMS
  7236. rotates as one mechanism (all 4 spools turn together), so a
  7237. single loaded slot locks the entire unit. Bambu per-tray
  7238. `state`: 9 = empty, 10 = spool present but not loaded
  7239. (rotation possible), 11 = loaded into tube (rotation impossible).
  7240. Catches both mid-print (active feed) AND idle-with-threaded-
  7241. filament — the H2D's post-print state leaves filament in the
  7242. tube but tray_now resets to 255, which a tray_now-only check
  7243. would silently miss. */}
  7244. {(() => {
  7245. const targetAms = dryingPopoverAmsId !== null
  7246. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7247. : undefined;
  7248. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7249. tray => tray.state === 11,
  7250. );
  7251. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7252. return (
  7253. <button
  7254. type="button"
  7255. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7256. aria-pressed={rotateChecked}
  7257. disabled={trayLoadedInThisAms}
  7258. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7259. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7260. rotateChecked
  7261. ? 'bg-bambu-green border-bambu-green text-white'
  7262. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7263. }`}
  7264. >
  7265. {t('printers.drying.rotateTray')}
  7266. </button>
  7267. );
  7268. })()}
  7269. {/* Start mode: now / after delay / at time (#2638) */}
  7270. <div>
  7271. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7272. <div className="grid grid-cols-3 gap-1">
  7273. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7274. <button
  7275. key={mode}
  7276. type="button"
  7277. onClick={() => setDryingStartMode(mode)}
  7278. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7279. dryingStartMode === mode
  7280. ? 'bg-bambu-green border-bambu-green text-white'
  7281. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7282. }`}
  7283. >
  7284. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7285. </button>
  7286. ))}
  7287. </div>
  7288. {dryingStartMode === 'delay' && (
  7289. // Inline chips: a dropdown menu would be clipped by
  7290. // the popover's scrollable body.
  7291. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7292. {DRYING_DELAY_OPTIONS.map(min => (
  7293. <button
  7294. key={min}
  7295. type="button"
  7296. aria-pressed={dryingDelayMinutes === min}
  7297. onClick={() => setDryingDelayMinutes(min)}
  7298. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7299. dryingDelayMinutes === min
  7300. ? 'bg-bambu-green border-bambu-green text-white'
  7301. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7302. }`}
  7303. >
  7304. {formatDurationFromHours(min / 60)}
  7305. </button>
  7306. ))}
  7307. </div>
  7308. )}
  7309. {dryingStartMode === 'at_time' && (
  7310. <input
  7311. ref={dryingAtTimeInputRef}
  7312. type="datetime-local"
  7313. data-testid="drying-start-at"
  7314. value={dryingStartAt}
  7315. onChange={e => setDryingStartAt(e.target.value)}
  7316. className="mt-1.5 w-full px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] focus:outline-none focus:border-bambu-green [color-scheme:dark]"
  7317. />
  7318. )}
  7319. </div>
  7320. </div>
  7321. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7322. {/* Footer */}
  7323. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7324. <button
  7325. onClick={() => {
  7326. if (dryingPopoverAmsId !== null) {
  7327. // Clamp rotateTray off when any tray in this AMS is loaded into
  7328. // the tube — the rotate UI is disabled there, but the state may
  7329. // linger as `true` from a previous AMS, or a print may have
  7330. // started while the popover was open. Without this clamp the
  7331. // Start payload would carry rotate_tray=true and firmware would
  7332. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7333. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7334. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7335. tray => tray.state === 11,
  7336. );
  7337. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7338. if (dryingStartMode === 'now') {
  7339. startDryingMutation.mutate({
  7340. amsId: dryingPopoverAmsId,
  7341. temp: dryingTemp,
  7342. duration: dryingDuration,
  7343. filament: dryingFilament,
  7344. rotateTray: rotate,
  7345. });
  7346. } else {
  7347. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7348. if (startAfter) {
  7349. scheduleDryingMutation.mutate({
  7350. amsId: dryingPopoverAmsId,
  7351. temp: dryingTemp,
  7352. duration: dryingDuration,
  7353. filament: dryingFilament,
  7354. rotateTray: rotate,
  7355. startAfter,
  7356. });
  7357. }
  7358. }
  7359. }
  7360. }}
  7361. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7362. data-testid="drying-start-confirm"
  7363. 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"
  7364. >
  7365. {dryingStartMode === 'now'
  7366. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7367. : t('printers.drying.schedule')}
  7368. </button>
  7369. </div>
  7370. </div>
  7371. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7372. since the popover clips its own overflow. */}
  7373. <div
  7374. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7375. style={{
  7376. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7377. top: dryingPopoverPos.anchorY - 5,
  7378. ...(dryingPopoverPos.placement === 'above'
  7379. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7380. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7381. }}
  7382. />
  7383. </>
  7384. );
  7385. })()}
  7386. </Card>
  7387. );
  7388. }
  7389. export function AddPrinterModal({
  7390. onClose,
  7391. onAdd,
  7392. existingSerials,
  7393. }: {
  7394. onClose: () => void;
  7395. onAdd: (data: PrinterCreate) => void;
  7396. existingSerials: string[];
  7397. }) {
  7398. const { t } = useTranslation();
  7399. const [form, setForm] = useState<PrinterCreate>({
  7400. name: '',
  7401. serial_number: '',
  7402. ip_address: '',
  7403. access_code: '',
  7404. model: '',
  7405. location: '',
  7406. auto_archive: true,
  7407. });
  7408. // Discovery state
  7409. const [discovering, setDiscovering] = useState(false);
  7410. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7411. const [discoveryError, setDiscoveryError] = useState('');
  7412. const [hasScanned, setHasScanned] = useState(false);
  7413. const [isDocker, setIsDocker] = useState(false);
  7414. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7415. const [subnet, setSubnet] = useState('');
  7416. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7417. // text input so users can scan a subnet Bambuddy isn't directly on
  7418. // (printer behind a router on a different L3 segment — SSDP multicast
  7419. // won't cross that boundary, only an active unicast scan will). #1564
  7420. const [customSubnet, setCustomSubnet] = useState('');
  7421. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7422. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7423. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7424. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7425. // (not block) when checks fail, so the user doesn't add a printer that
  7426. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7427. // failed result awaiting an explicit "save anyway".
  7428. const [checkingSave, setCheckingSave] = useState(false);
  7429. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7430. // Fetch discovery info on mount + restore the last custom CIDR the user
  7431. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7432. // time they open this modal).
  7433. useEffect(() => {
  7434. discoveryApi.getInfo().then(info => {
  7435. setIsDocker(info.is_docker);
  7436. if (info.subnets.length > 0) {
  7437. setDetectedSubnets(info.subnets);
  7438. setSubnet(info.subnets[0]);
  7439. }
  7440. }).catch(() => {
  7441. // Ignore errors, assume not Docker
  7442. });
  7443. try {
  7444. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7445. if (saved) setCustomSubnet(saved);
  7446. } catch {
  7447. // localStorage unavailable (private mode, quota); recall is opportunistic
  7448. }
  7449. }, []);
  7450. // Filter out already-added printers
  7451. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7452. const handleAddSubmit = async (e: React.FormEvent) => {
  7453. e.preventDefault();
  7454. setCheckingSave(true);
  7455. try {
  7456. const result = await api.diagnoseConnection({
  7457. ip_address: form.ip_address.trim(),
  7458. serial_number: form.serial_number.trim() || undefined,
  7459. access_code: form.access_code || undefined,
  7460. });
  7461. if (result.checks.some((c) => c.status === 'fail')) {
  7462. setSaveWarning(result);
  7463. return;
  7464. }
  7465. } catch {
  7466. // Diagnostic infrastructure failed — never block the save on it.
  7467. } finally {
  7468. setCheckingSave(false);
  7469. }
  7470. onAdd(form);
  7471. };
  7472. const startDiscovery = async () => {
  7473. setDiscoveryError('');
  7474. setDiscovered([]);
  7475. setDiscovering(true);
  7476. setHasScanned(false);
  7477. setScanProgress({ scanned: 0, total: 0 });
  7478. // Native installs fall back to subnet scanning when the user picks
  7479. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7480. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7481. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7482. const wantsSubnetScan = isDocker || useCustomSubnet;
  7483. if (wantsSubnetScan && useCustomSubnet) {
  7484. try {
  7485. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7486. } catch {
  7487. // localStorage write best-effort; user just retypes next time
  7488. }
  7489. }
  7490. try {
  7491. if (wantsSubnetScan) {
  7492. await discoveryApi.startSubnetScan(scanCidr);
  7493. // Poll for scan status and results
  7494. const pollInterval = setInterval(async () => {
  7495. try {
  7496. const status = await discoveryApi.getScanStatus();
  7497. setScanProgress({ scanned: status.scanned, total: status.total });
  7498. const printers = await discoveryApi.getDiscoveredPrinters();
  7499. setDiscovered(printers);
  7500. if (!status.running) {
  7501. clearInterval(pollInterval);
  7502. setDiscovering(false);
  7503. setHasScanned(true);
  7504. }
  7505. } catch (e) {
  7506. console.error('Failed to get scan status:', e);
  7507. }
  7508. }, 500);
  7509. } else {
  7510. // Use SSDP discovery for native installs
  7511. await discoveryApi.startDiscovery(10);
  7512. // Poll for discovered printers every second
  7513. const pollInterval = setInterval(async () => {
  7514. try {
  7515. const printers = await discoveryApi.getDiscoveredPrinters();
  7516. setDiscovered(printers);
  7517. } catch (e) {
  7518. console.error('Failed to get discovered printers:', e);
  7519. }
  7520. }, 1000);
  7521. // Stop after 10 seconds
  7522. setTimeout(async () => {
  7523. clearInterval(pollInterval);
  7524. try {
  7525. await discoveryApi.stopDiscovery();
  7526. } catch {
  7527. // Ignore stop errors
  7528. }
  7529. setDiscovering(false);
  7530. setHasScanned(true);
  7531. // Final fetch
  7532. try {
  7533. const printers = await discoveryApi.getDiscoveredPrinters();
  7534. setDiscovered(printers);
  7535. } catch (e) {
  7536. console.error('Failed to get final discovered printers:', e);
  7537. }
  7538. }, 10000);
  7539. }
  7540. } catch (e) {
  7541. console.error('Failed to start discovery:', e);
  7542. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7543. setDiscovering(false);
  7544. setHasScanned(true);
  7545. }
  7546. };
  7547. // Reuse module-level mapModelCode
  7548. const selectPrinter = (printer: DiscoveredPrinter) => {
  7549. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7550. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7551. setForm({
  7552. ...form,
  7553. name: printer.name || '',
  7554. serial_number: serialNumber,
  7555. ip_address: printer.ip_address,
  7556. model: mapModelCode(printer.model),
  7557. });
  7558. // Clear discovery results after selection
  7559. setDiscovered([]);
  7560. };
  7561. // Cleanup discovery on unmount
  7562. useEffect(() => {
  7563. return () => {
  7564. discoveryApi.stopDiscovery().catch(() => {});
  7565. discoveryApi.stopSubnetScan().catch(() => {});
  7566. };
  7567. }, []);
  7568. // Close on Escape key
  7569. useEffect(() => {
  7570. const handleKeyDown = (e: KeyboardEvent) => {
  7571. if (e.key === 'Escape') onClose();
  7572. };
  7573. window.addEventListener('keydown', handleKeyDown);
  7574. return () => window.removeEventListener('keydown', handleKeyDown);
  7575. }, [onClose]);
  7576. return (
  7577. <>
  7578. <div
  7579. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7580. onClick={onClose}
  7581. >
  7582. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7583. <CardContent>
  7584. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7585. {/* Discovery Section */}
  7586. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7587. {/* Subnet picker — always visible. The dropdown lists detected
  7588. interface subnets and a "Custom..." sentinel that reveals
  7589. a CIDR text input for printers on a different L3 segment
  7590. (router, VLAN, etc.). #1564 */}
  7591. <div className="mb-3">
  7592. <label className="block text-sm text-bambu-gray mb-1">
  7593. {t('printers.discovery.subnetToScan')}
  7594. </label>
  7595. {detectedSubnets.length > 0 ? (
  7596. <select
  7597. 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"
  7598. value={useCustomSubnet ? '__custom__' : subnet}
  7599. onChange={(e) => {
  7600. if (e.target.value === '__custom__') {
  7601. setUseCustomSubnet(true);
  7602. } else {
  7603. setUseCustomSubnet(false);
  7604. setSubnet(e.target.value);
  7605. }
  7606. }}
  7607. disabled={discovering}
  7608. >
  7609. {detectedSubnets.map(s => (
  7610. <option key={s} value={s}>{s}</option>
  7611. ))}
  7612. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7613. </select>
  7614. ) : (
  7615. <input
  7616. type="text"
  7617. 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"
  7618. value={subnet}
  7619. onChange={(e) => setSubnet(e.target.value)}
  7620. placeholder="192.168.1.0/24"
  7621. disabled={discovering}
  7622. />
  7623. )}
  7624. {useCustomSubnet && (
  7625. <input
  7626. type="text"
  7627. aria-label={t('printers.discovery.customSubnetLabel')}
  7628. 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"
  7629. value={customSubnet}
  7630. onChange={(e) => setCustomSubnet(e.target.value)}
  7631. placeholder="10.1.1.0/24"
  7632. disabled={discovering}
  7633. />
  7634. )}
  7635. <p className="mt-1 text-xs text-bambu-gray">
  7636. {isDocker
  7637. ? t('printers.discovery.dockerNote')
  7638. : t('printers.discovery.customSubnetNote')}
  7639. </p>
  7640. </div>
  7641. <Button
  7642. type="button"
  7643. variant="secondary"
  7644. onClick={startDiscovery}
  7645. disabled={discovering}
  7646. className="w-full"
  7647. >
  7648. {discovering ? (
  7649. <>
  7650. <Loader2 className="w-4 h-4 animate-spin" />
  7651. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7652. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7653. : t('printers.discovery.scanning')}
  7654. </>
  7655. ) : (
  7656. <>
  7657. <Search className="w-4 h-4" />
  7658. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7659. </>
  7660. )}
  7661. </Button>
  7662. {discoveryError && (
  7663. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7664. )}
  7665. {newPrinters.length > 0 && (
  7666. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7667. {newPrinters.map((printer) => (
  7668. <div
  7669. key={printer.serial}
  7670. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7671. onClick={() => selectPrinter(printer)}
  7672. >
  7673. <div className="min-w-0 flex-1">
  7674. <p className="font-medium text-white text-sm truncate">
  7675. {printer.name || printer.serial}
  7676. </p>
  7677. <p className="text-xs text-bambu-gray truncate">
  7678. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7679. {printer.serial.startsWith('unknown-') && (
  7680. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7681. )}
  7682. </p>
  7683. </div>
  7684. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7685. </div>
  7686. ))}
  7687. </div>
  7688. )}
  7689. {discovering && (
  7690. <p className="mt-2 text-sm text-bambu-gray text-center">
  7691. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7692. </p>
  7693. )}
  7694. {hasScanned && !discovering && discovered.length === 0 && (
  7695. <p className="mt-2 text-sm text-bambu-gray text-center">
  7696. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7697. </p>
  7698. )}
  7699. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7700. <p className="mt-2 text-sm text-bambu-gray text-center">
  7701. {t('printers.discovery.allConfigured')}
  7702. </p>
  7703. )}
  7704. </div>
  7705. <form onSubmit={handleAddSubmit} className="space-y-4">
  7706. <div>
  7707. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7708. <input
  7709. type="text"
  7710. required
  7711. 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"
  7712. value={form.name}
  7713. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7714. placeholder={t('printers.modal.myPrinter')}
  7715. />
  7716. </div>
  7717. <div>
  7718. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7719. <input
  7720. type="text"
  7721. required
  7722. 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])?)*)"
  7723. 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"
  7724. value={form.ip_address}
  7725. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7726. placeholder="192.168.1.100 or printer.local"
  7727. />
  7728. </div>
  7729. <div>
  7730. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7731. <input
  7732. type="text"
  7733. required
  7734. 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"
  7735. value={form.serial_number}
  7736. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7737. placeholder="01P00A000000000"
  7738. />
  7739. </div>
  7740. <div>
  7741. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7742. <input
  7743. type="password"
  7744. required
  7745. 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"
  7746. value={form.access_code}
  7747. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7748. placeholder={t('printers.modal.fromPrinterSettings')}
  7749. />
  7750. </div>
  7751. <div>
  7752. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7753. <select
  7754. 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"
  7755. value={form.model || ''}
  7756. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7757. >
  7758. <option value="">{t('printers.modal.selectModel')}</option>
  7759. <optgroup label="A1 Series">
  7760. <option value="A1">A1</option>
  7761. <option value="A1 Mini">A1 Mini</option>
  7762. </optgroup>
  7763. <optgroup label="A2 Series">
  7764. <option value="A2L">A2L</option>
  7765. </optgroup>
  7766. <optgroup label="H2 Series">
  7767. <option value="H2C">H2C</option>
  7768. <option value="H2D">H2D</option>
  7769. <option value="H2D Pro">H2D Pro</option>
  7770. <option value="H2S">H2S</option>
  7771. </optgroup>
  7772. <optgroup label="P Series">
  7773. <option value="P1P">P1P</option>
  7774. <option value="P1S">P1S</option>
  7775. <option value="P2S">P2S</option>
  7776. </optgroup>
  7777. <optgroup label="X1 Series">
  7778. <option value="X1">X1</option>
  7779. <option value="X1C">X1 Carbon</option>
  7780. <option value="X1E">X1E</option>
  7781. </optgroup>
  7782. <optgroup label="X2 Series">
  7783. <option value="X2D">X2D</option>
  7784. </optgroup>
  7785. </select>
  7786. </div>
  7787. <div>
  7788. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7789. <input
  7790. type="text"
  7791. 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"
  7792. value={form.location || ''}
  7793. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7794. placeholder={t('printers.modal.locationPlaceholder')}
  7795. />
  7796. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7797. </div>
  7798. <div className="flex items-center gap-2">
  7799. <input
  7800. type="checkbox"
  7801. id="auto_archive"
  7802. checked={form.auto_archive}
  7803. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7804. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7805. />
  7806. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7807. {t('printers.modal.autoArchiveLabel')}
  7808. </label>
  7809. </div>
  7810. <button
  7811. type="button"
  7812. onClick={() => setShowDiagnostic(true)}
  7813. disabled={!form.ip_address.trim()}
  7814. 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"
  7815. >
  7816. <Stethoscope className="w-4 h-4" />
  7817. {t('diagnostic.runButton')}
  7818. </button>
  7819. {saveWarning ? (
  7820. <div className="rounded-lg bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 p-3 space-y-3">
  7821. <div className="flex items-start gap-2">
  7822. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7823. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7824. </div>
  7825. <DiagnosticChecklist result={saveWarning} />
  7826. <div className="flex gap-3">
  7827. <Button
  7828. type="button"
  7829. variant="secondary"
  7830. onClick={() => setSaveWarning(null)}
  7831. className="flex-1"
  7832. >
  7833. {t('printers.addPreflight.back')}
  7834. </Button>
  7835. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7836. {t('printers.addPreflight.saveAnyway')}
  7837. </Button>
  7838. </div>
  7839. </div>
  7840. ) : (
  7841. <div className="flex gap-3 pt-2">
  7842. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7843. {t('common.cancel')}
  7844. </Button>
  7845. <Button type="submit" disabled={checkingSave} className="flex-1">
  7846. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7847. </Button>
  7848. </div>
  7849. )}
  7850. </form>
  7851. </CardContent>
  7852. </Card>
  7853. </div>
  7854. {showDiagnostic && (
  7855. <ConnectionDiagnosticModal
  7856. connection={{
  7857. ip_address: form.ip_address.trim(),
  7858. serial_number: form.serial_number.trim() || undefined,
  7859. access_code: form.access_code || undefined,
  7860. }}
  7861. printerName={form.name || null}
  7862. onClose={() => setShowDiagnostic(false)}
  7863. />
  7864. )}
  7865. </>
  7866. );
  7867. }
  7868. function FirmwareUpdateModal({
  7869. printer,
  7870. firmwareInfo,
  7871. onClose,
  7872. }: {
  7873. printer: Printer;
  7874. firmwareInfo: FirmwareUpdateInfo;
  7875. onClose: () => void;
  7876. }) {
  7877. const { t } = useTranslation();
  7878. const queryClient = useQueryClient();
  7879. const { showToast } = useToast();
  7880. const { hasPermission } = useAuth();
  7881. const canUpdate = hasPermission('firmware:update');
  7882. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7883. const [isUploading, setIsUploading] = useState(false);
  7884. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7885. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7886. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7887. );
  7888. // Prepare check query — runs when a version is selected and user can update
  7889. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7890. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7891. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7892. staleTime: 30000,
  7893. enabled: !!selectedVersion && canUpdate && !isUploading,
  7894. });
  7895. // Start upload mutation
  7896. const uploadMutation = useMutation({
  7897. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7898. onSuccess: () => {
  7899. setIsUploading(true);
  7900. // Start polling for status
  7901. const interval = setInterval(async () => {
  7902. try {
  7903. const status = await firmwareApi.getUploadStatus(printer.id);
  7904. setUploadStatus(status);
  7905. if (status.status === 'complete' || status.status === 'error') {
  7906. clearInterval(interval);
  7907. setPollInterval(null);
  7908. setIsUploading(false);
  7909. if (status.status === 'complete') {
  7910. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7911. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7912. }
  7913. }
  7914. } catch {
  7915. // Ignore errors during polling
  7916. }
  7917. }, 2000);
  7918. setPollInterval(interval);
  7919. },
  7920. onError: (error: Error) => {
  7921. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7922. setIsUploading(false);
  7923. },
  7924. });
  7925. // Cleanup on unmount
  7926. useEffect(() => {
  7927. return () => {
  7928. if (pollInterval) clearInterval(pollInterval);
  7929. };
  7930. }, [pollInterval]);
  7931. const handleStartUpload = () => {
  7932. setUploadStatus(null);
  7933. uploadMutation.mutate();
  7934. };
  7935. return (
  7936. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7937. <Card className="w-full max-w-md mx-4">
  7938. <CardContent>
  7939. <div className="flex items-start gap-3 mb-4">
  7940. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7941. {firmwareInfo.update_available
  7942. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7943. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7944. </div>
  7945. <div className="flex-1">
  7946. <h3 className="text-lg font-semibold text-white">
  7947. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7948. </h3>
  7949. <p className="text-sm text-bambu-gray mt-1">
  7950. {printer.name}
  7951. </p>
  7952. </div>
  7953. </div>
  7954. {/* Version Info */}
  7955. {(() => {
  7956. const selectedEntry = selectedVersion
  7957. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7958. : null;
  7959. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7960. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7961. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7962. return (
  7963. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7964. <div className="flex justify-between items-center text-sm">
  7965. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7966. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7967. {firmwareInfo.current_version || t('common.unknown')}
  7968. </span>
  7969. </div>
  7970. {showSecondLine && (
  7971. <div className="flex justify-between items-center text-sm mt-1">
  7972. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7973. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7974. </div>
  7975. )}
  7976. {displayNotes && (
  7977. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7978. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7979. {t('printers.firmwareModal.releaseNotes')}
  7980. </summary>
  7981. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7982. {displayNotes}
  7983. </div>
  7984. </details>
  7985. )}
  7986. </div>
  7987. );
  7988. })()}
  7989. {/* Available versions list */}
  7990. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7991. <div className="mb-4">
  7992. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7993. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7994. {firmwareInfo.available_versions.map((v) => {
  7995. const isCurrent = firmwareInfo.current_version === v.version;
  7996. const isSelected = selectedVersion === v.version;
  7997. const cmp = firmwareInfo.current_version
  7998. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7999. : 0;
  8000. const relLabel = isCurrent
  8001. ? t('printers.firmwareModal.currentBadge')
  8002. : cmp > 0
  8003. ? t('printers.firmwareModal.newerBadge')
  8004. : t('printers.firmwareModal.olderBadge');
  8005. const relClass = isCurrent
  8006. ? 'text-bambu-gray'
  8007. : cmp > 0
  8008. ? 'text-orange-700 dark:text-orange-400'
  8009. : 'text-blue-700 dark:text-blue-400';
  8010. return (
  8011. <button
  8012. key={v.version}
  8013. type="button"
  8014. disabled={!v.file_available || !canUpdate || isCurrent}
  8015. onClick={() => setSelectedVersion(v.version)}
  8016. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  8017. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  8018. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  8019. >
  8020. <div className="flex items-center gap-2 min-w-0">
  8021. <span className="font-mono text-white">{v.version}</span>
  8022. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  8023. </div>
  8024. <span className={`text-xs px-2 py-0.5 rounded-full ${
  8025. isCurrent
  8026. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  8027. : v.file_available
  8028. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  8029. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  8030. }`}>
  8031. {isCurrent
  8032. ? t('printers.firmwareModal.installed')
  8033. : v.file_available
  8034. ? t('printers.firmwareModal.usable')
  8035. : t('printers.firmwareModal.unavailable')}
  8036. </span>
  8037. </button>
  8038. );
  8039. })}
  8040. </div>
  8041. </div>
  8042. )}
  8043. {/* Status / Progress (only when a version is selected) */}
  8044. {!selectedVersion ? null : isPreparing ? (
  8045. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  8046. <Loader2 className="w-4 h-4 animate-spin" />
  8047. {t('printers.firmwareModal.checkingPrereqs')}
  8048. </div>
  8049. ) : prepareInfo && !isUploading && !uploadStatus ? (
  8050. <div className="mb-4">
  8051. {prepareInfo.can_proceed ? (
  8052. <div className="flex items-center gap-2 text-bambu-green text-sm">
  8053. <Box className="w-4 h-4" />
  8054. {t('printers.firmwareModal.sdCardReady')}
  8055. </div>
  8056. ) : (
  8057. <div className="space-y-1">
  8058. {prepareInfo.errors.map((error, i) => (
  8059. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  8060. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  8061. {error}
  8062. </div>
  8063. ))}
  8064. </div>
  8065. )}
  8066. </div>
  8067. ) : null}
  8068. {/* Upload Progress */}
  8069. {(isUploading || uploadStatus) && uploadStatus && (
  8070. <div className="mb-4">
  8071. <div className="flex items-center justify-between text-sm mb-1">
  8072. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8073. <span className="text-white">{uploadStatus.progress}%</span>
  8074. </div>
  8075. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8076. <div
  8077. className={`h-2 rounded-full transition-all ${
  8078. uploadStatus.status === 'error' ? 'bg-status-error' :
  8079. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8080. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8081. style={{ width: `${uploadStatus.progress}%` }}
  8082. />
  8083. </div>
  8084. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8085. {uploadStatus.error && (
  8086. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8087. )}
  8088. </div>
  8089. )}
  8090. {/* Success Message */}
  8091. {uploadStatus?.status === 'complete' && (
  8092. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8093. <p className="text-sm text-bambu-green font-medium mb-2">
  8094. {t('printers.firmwareModal.uploadedSuccess')}
  8095. </p>
  8096. <p className="text-xs text-bambu-gray">
  8097. {t('printers.firmwareModal.applyInstructions')}
  8098. </p>
  8099. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8100. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8101. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8102. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8103. <li>{t('printers.firmwareModal.step4')}</li>
  8104. </ol>
  8105. </div>
  8106. )}
  8107. {/* Buttons */}
  8108. <div className="flex gap-2 justify-end">
  8109. <Button variant="secondary" onClick={onClose}>
  8110. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8111. </Button>
  8112. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8113. <Button
  8114. onClick={handleStartUpload}
  8115. disabled={uploadMutation.isPending}
  8116. >
  8117. {uploadMutation.isPending ? (
  8118. <>
  8119. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8120. {t('printers.firmwareModal.starting')}
  8121. </>
  8122. ) : (
  8123. <>
  8124. <Download className="w-4 h-4 mr-2" />
  8125. {t('printers.firmwareModal.uploadFirmware')}
  8126. </>
  8127. )}
  8128. </Button>
  8129. )}
  8130. </div>
  8131. </CardContent>
  8132. </Card>
  8133. </div>
  8134. );
  8135. }
  8136. function EditPrinterModal({
  8137. printer,
  8138. onClose,
  8139. }: {
  8140. printer: Printer;
  8141. onClose: () => void;
  8142. }) {
  8143. const { t } = useTranslation();
  8144. const queryClient = useQueryClient();
  8145. const { showToast } = useToast();
  8146. const [form, setForm] = useState({
  8147. name: printer.name,
  8148. ip_address: printer.ip_address,
  8149. access_code: '',
  8150. model: printer.model || '',
  8151. location: printer.location || '',
  8152. auto_archive: printer.auto_archive,
  8153. is_active: printer.is_active,
  8154. });
  8155. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8156. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8157. const [checkingSave, setCheckingSave] = useState(false);
  8158. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8159. const updateMutation = useMutation({
  8160. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8161. onSuccess: () => {
  8162. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8163. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8164. onClose();
  8165. },
  8166. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8167. });
  8168. // Close on Escape key
  8169. useEffect(() => {
  8170. const handleKeyDown = (e: KeyboardEvent) => {
  8171. if (e.key === 'Escape') onClose();
  8172. };
  8173. window.addEventListener('keydown', handleKeyDown);
  8174. return () => window.removeEventListener('keydown', handleKeyDown);
  8175. }, [onClose]);
  8176. const doSave = () => {
  8177. const data: Partial<PrinterCreate> = {
  8178. name: form.name,
  8179. ip_address: form.ip_address,
  8180. model: form.model || undefined,
  8181. location: form.location || undefined,
  8182. auto_archive: form.auto_archive,
  8183. is_active: form.is_active,
  8184. };
  8185. // Only include access_code if it was changed
  8186. if (form.access_code) {
  8187. data.access_code = form.access_code;
  8188. }
  8189. updateMutation.mutate(data);
  8190. };
  8191. const handleSubmit = async (e: React.FormEvent) => {
  8192. e.preventDefault();
  8193. setCheckingSave(true);
  8194. try {
  8195. const result = await api.diagnoseConnection({
  8196. ip_address: form.ip_address.trim(),
  8197. serial_number: printer.serial_number,
  8198. access_code: form.access_code || undefined,
  8199. });
  8200. if (result.checks.some((c) => c.status === 'fail')) {
  8201. setSaveWarning(result);
  8202. return;
  8203. }
  8204. } catch {
  8205. // Diagnostic infrastructure failed — never block the save on it.
  8206. } finally {
  8207. setCheckingSave(false);
  8208. }
  8209. doSave();
  8210. };
  8211. return (
  8212. <div
  8213. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8214. onClick={onClose}
  8215. >
  8216. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8217. <CardContent>
  8218. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8219. <form onSubmit={handleSubmit} className="space-y-4">
  8220. <div>
  8221. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8222. <input
  8223. type="text"
  8224. required
  8225. 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"
  8226. value={form.name}
  8227. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8228. placeholder={t('printers.modal.myPrinter')}
  8229. />
  8230. </div>
  8231. <div>
  8232. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8233. <input
  8234. type="text"
  8235. required
  8236. 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])?)*)"
  8237. 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"
  8238. value={form.ip_address}
  8239. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8240. placeholder="192.168.1.100 or printer.local"
  8241. />
  8242. </div>
  8243. <div>
  8244. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8245. <input
  8246. type="text"
  8247. disabled
  8248. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8249. value={printer.serial_number}
  8250. />
  8251. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8252. </div>
  8253. <div>
  8254. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8255. <input
  8256. type="password"
  8257. 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"
  8258. value={form.access_code}
  8259. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8260. placeholder={t('printers.accessCodePlaceholder')}
  8261. />
  8262. </div>
  8263. <div>
  8264. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8265. <select
  8266. 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"
  8267. value={form.model}
  8268. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8269. >
  8270. <option value="">{t('printers.modal.selectModel')}</option>
  8271. <optgroup label="A1 Series">
  8272. <option value="A1">A1</option>
  8273. <option value="A1 Mini">A1 Mini</option>
  8274. </optgroup>
  8275. <optgroup label="A2 Series">
  8276. <option value="A2L">A2L</option>
  8277. </optgroup>
  8278. <optgroup label="H2 Series">
  8279. <option value="H2C">H2C</option>
  8280. <option value="H2D">H2D</option>
  8281. <option value="H2D Pro">H2D Pro</option>
  8282. <option value="H2S">H2S</option>
  8283. </optgroup>
  8284. <optgroup label="P Series">
  8285. <option value="P1P">P1P</option>
  8286. <option value="P1S">P1S</option>
  8287. <option value="P2S">P2S</option>
  8288. </optgroup>
  8289. <optgroup label="X1 Series">
  8290. <option value="X1">X1</option>
  8291. <option value="X1C">X1 Carbon</option>
  8292. <option value="X1E">X1E</option>
  8293. </optgroup>
  8294. <optgroup label="X2 Series">
  8295. <option value="X2D">X2D</option>
  8296. </optgroup>
  8297. </select>
  8298. </div>
  8299. <div>
  8300. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8301. <input
  8302. type="text"
  8303. 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"
  8304. value={form.location}
  8305. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8306. placeholder={t('printers.modal.locationPlaceholder')}
  8307. />
  8308. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8309. </div>
  8310. <div className="flex items-center gap-2">
  8311. <input
  8312. type="checkbox"
  8313. id="edit_auto_archive"
  8314. checked={form.auto_archive}
  8315. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8316. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8317. />
  8318. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8319. {t('printers.modal.autoArchiveLabel')}
  8320. </label>
  8321. </div>
  8322. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8323. is_active because the user-facing concept is "is this printer
  8324. in maintenance" not "is it active". */}
  8325. <div>
  8326. <div className="flex items-center gap-2">
  8327. <input
  8328. type="checkbox"
  8329. id="edit_maintenance_mode"
  8330. checked={!form.is_active}
  8331. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8332. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8333. />
  8334. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8335. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8336. {t('printers.maintenance.editFieldLabel')}
  8337. </label>
  8338. </div>
  8339. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8340. {t('printers.maintenance.editFieldHelp')}
  8341. </p>
  8342. </div>
  8343. {saveWarning ? (
  8344. <div className="rounded-lg bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/30 p-3 space-y-3">
  8345. <div className="flex items-start gap-2">
  8346. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8347. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8348. </div>
  8349. <DiagnosticChecklist result={saveWarning} />
  8350. <div className="flex gap-3">
  8351. <Button
  8352. type="button"
  8353. variant="secondary"
  8354. onClick={() => setSaveWarning(null)}
  8355. className="flex-1"
  8356. >
  8357. {t('printers.addPreflight.back')}
  8358. </Button>
  8359. <Button
  8360. type="button"
  8361. onClick={doSave}
  8362. className="flex-1"
  8363. disabled={updateMutation.isPending}
  8364. >
  8365. {t('printers.addPreflight.saveAnyway')}
  8366. </Button>
  8367. </div>
  8368. </div>
  8369. ) : (
  8370. <div className="flex gap-3 pt-4">
  8371. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8372. {t('common.cancel')}
  8373. </Button>
  8374. <Button
  8375. type="submit"
  8376. className="flex-1"
  8377. disabled={updateMutation.isPending || checkingSave}
  8378. >
  8379. {checkingSave
  8380. ? t('printers.addPreflight.checking')
  8381. : updateMutation.isPending
  8382. ? t('common.saving')
  8383. : t('printers.modal.saveChanges')}
  8384. </Button>
  8385. </div>
  8386. )}
  8387. </form>
  8388. </CardContent>
  8389. </Card>
  8390. </div>
  8391. );
  8392. }
  8393. // Component to check if a printer is offline (for power dropdown)
  8394. function usePrinterOfflineStatus(printerId: number) {
  8395. const { data: status } = useQuery({
  8396. queryKey: ['printerStatus', printerId],
  8397. queryFn: () => api.getPrinterStatus(printerId),
  8398. refetchInterval: 30000,
  8399. });
  8400. return !status?.connected;
  8401. }
  8402. // Power dropdown item for an offline printer
  8403. function PowerDropdownItem({
  8404. printer,
  8405. plug,
  8406. onPowerOn,
  8407. isPowering,
  8408. }: {
  8409. printer: Printer;
  8410. plug: { id: number; name: string };
  8411. onPowerOn: (plugId: number) => void;
  8412. isPowering: boolean;
  8413. }) {
  8414. const isOffline = usePrinterOfflineStatus(printer.id);
  8415. // Fetch plug status
  8416. const { data: plugStatus } = useQuery({
  8417. queryKey: ['smartPlugStatus', plug.id],
  8418. queryFn: () => api.getSmartPlugStatus(plug.id),
  8419. refetchInterval: 10000,
  8420. });
  8421. // Only show if printer is offline
  8422. if (!isOffline) {
  8423. return null;
  8424. }
  8425. return (
  8426. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8427. <div className="flex items-center gap-2 min-w-0">
  8428. <span className="text-sm text-white truncate">{printer.name}</span>
  8429. {plugStatus && (
  8430. <span
  8431. className={`text-xs px-1.5 py-0.5 rounded ${
  8432. plugStatus.state === 'ON'
  8433. ? 'bg-bambu-green/20 text-bambu-green'
  8434. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8435. }`}
  8436. >
  8437. {plugStatus.state || '?'}
  8438. </span>
  8439. )}
  8440. </div>
  8441. <button
  8442. onClick={() => onPowerOn(plug.id)}
  8443. disabled={isPowering || plugStatus?.state === 'ON'}
  8444. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8445. plugStatus?.state === 'ON'
  8446. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8447. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8448. }`}
  8449. >
  8450. <Power className="w-3 h-3" />
  8451. {isPowering ? '...' : 'On'}
  8452. </button>
  8453. </div>
  8454. );
  8455. }
  8456. export function PrintersPage() {
  8457. const { t } = useTranslation();
  8458. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8459. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8460. const accentButtonClass = {
  8461. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8462. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8463. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8464. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8465. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8466. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8467. }[activeAccent];
  8468. const [showAddModal, setShowAddModal] = useState(false);
  8469. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8470. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8471. });
  8472. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8473. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8474. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8475. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8476. });
  8477. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8478. return localStorage.getItem('printerSortAsc') !== 'false';
  8479. });
  8480. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8481. const [cardSize, setCardSize] = useState<number>(() => {
  8482. const saved = localStorage.getItem('printerCardSize');
  8483. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8484. });
  8485. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8486. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8487. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8488. });
  8489. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8490. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8491. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8492. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8493. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8494. });
  8495. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8496. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8497. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8498. });
  8499. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8500. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8501. // Defaulting to 'full' because the cards already show this info — users who
  8502. // pick cam-wall view still want to glance the same details without flipping.
  8503. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8504. const saved = localStorage.getItem('camWallStatusMode');
  8505. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8506. });
  8507. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8508. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8509. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8510. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8511. requestAnimationFrame(() => {
  8512. requestAnimationFrame(() => {
  8513. const card = document.getElementById(`printer-card-${printerId}`);
  8514. if (!card) return;
  8515. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8516. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8517. window.scrollTo({
  8518. top: Math.max(0, top),
  8519. behavior: 'smooth',
  8520. });
  8521. });
  8522. });
  8523. }, []);
  8524. const openCompactCard = useCallback((printerId: number) => {
  8525. setCompactDrilldownPrinterId(printerId);
  8526. setCardSize(2);
  8527. localStorage.setItem('printerCardSize', '2');
  8528. scrollPrinterIntoView(printerId);
  8529. }, [scrollPrinterIntoView]);
  8530. const returnToCompactCards = useCallback(() => {
  8531. const printerId = compactDrilldownPrinterId;
  8532. setCompactDrilldownPrinterId(null);
  8533. setCardSize(1);
  8534. localStorage.setItem('printerCardSize', '1');
  8535. if (printerId != null) {
  8536. scrollPrinterIntoView(printerId);
  8537. }
  8538. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8539. const [search, setSearch] = useState('');
  8540. // Both filters persist like every other preference on this page (#2833).
  8541. // `search` deliberately does not: a box that silently refills itself on
  8542. // return is more surprising than a dropdown that remembers.
  8543. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8544. // Validated on read: a value the dropdown no longer offers would filter
  8545. // every printer out, and nothing would explain why.
  8546. const saved = localStorage.getItem('printerStatusFilter');
  8547. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8548. });
  8549. const [locationFilter, setLocationFilter] = useState<string>(
  8550. () => localStorage.getItem('printerLocationFilter') || 'all'
  8551. );
  8552. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8553. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8554. try {
  8555. const saved = localStorage.getItem('printerCollapsedSections');
  8556. return saved ? JSON.parse(saved) : {};
  8557. } catch { return {}; }
  8558. });
  8559. const queryClient = useQueryClient();
  8560. const { showToast } = useToast();
  8561. const { hasPermission } = useAuth();
  8562. // Which way the camera buttons open a stream. Chosen per click from the
  8563. // button's own menu; null until this browser has made a choice, so the
  8564. // stored setting below can act as the default a fresh browser starts from.
  8565. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8566. () => readStoredCameraViewMode()
  8567. );
  8568. // Embedded camera viewer state - supports multiple simultaneous viewers
  8569. // Persisted to localStorage so cameras reopen after navigation
  8570. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8571. const saved = localStorage.getItem('openEmbeddedCameras');
  8572. if (saved) {
  8573. try {
  8574. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8575. return new Map(cameras.map(c => [c.id, c]));
  8576. } catch {
  8577. return new Map();
  8578. }
  8579. }
  8580. return new Map();
  8581. });
  8582. // Persist open cameras to localStorage when they change
  8583. useEffect(() => {
  8584. const cameras = Array.from(embeddedCameraPrinters.values());
  8585. if (cameras.length > 0) {
  8586. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8587. } else {
  8588. localStorage.removeItem('openEmbeddedCameras');
  8589. }
  8590. }, [embeddedCameraPrinters]);
  8591. const { data: printers, isLoading } = useQuery({
  8592. queryKey: ['printers'],
  8593. queryFn: api.getPrinters,
  8594. });
  8595. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8596. // so users with printers:read but no settings:read still get the values needed
  8597. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8598. const { data: settings } = useQuery({
  8599. queryKey: ['ui-preferences'],
  8600. queryFn: api.getUiPreferences,
  8601. });
  8602. // Parse user-configured temperature/fan presets once, with defensive fallback
  8603. // to built-in defaults on parse failure (validators on the backend already
  8604. // reject malformed writes, so this is just forward-compat).
  8605. const effectiveNozzleTempPresets = useMemo(
  8606. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8607. [settings?.nozzle_temp_presets],
  8608. );
  8609. const effectiveBedTempPresets = useMemo(
  8610. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8611. [settings?.bed_temp_presets],
  8612. );
  8613. const effectiveChamberTempPresets = useMemo(
  8614. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8615. [settings?.chamber_temp_presets],
  8616. );
  8617. const effectiveFanSpeedPresets = useMemo(
  8618. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8619. [settings?.fan_speed_presets],
  8620. );
  8621. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8622. const effectiveDryingPresets = useMemo(() => {
  8623. if (settings?.drying_presets) {
  8624. try {
  8625. const userPresets = JSON.parse(settings.drying_presets);
  8626. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8627. return { ...DRYING_PRESETS, ...userPresets };
  8628. }
  8629. } catch { /* ignore parse errors, use defaults */ }
  8630. }
  8631. return DRYING_PRESETS;
  8632. }, [settings?.drying_presets]);
  8633. // The local choice wins over the stored one: someone without settings:update
  8634. // cannot write their pick back, and a preference that silently reverted on
  8635. // the next render would be worse than none at all.
  8636. const cameraViewMode: CameraViewMode =
  8637. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8638. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8639. storeCameraViewMode(mode);
  8640. setChosenCameraViewMode(mode);
  8641. // Best effort, and only a default for other browsers -- the choice is
  8642. // already in effect here. Users below settings:update simply keep theirs
  8643. // locally, which is why the failure is logged rather than surfaced.
  8644. if (hasPermission('settings:update')) {
  8645. api.updateSettings({ camera_view_mode: mode })
  8646. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8647. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8648. }
  8649. }, [hasPermission, queryClient]);
  8650. // Fetch all smart plugs to know which printers have them
  8651. const { data: smartPlugs } = useQuery({
  8652. queryKey: ['smart-plugs'],
  8653. queryFn: api.getSmartPlugs,
  8654. });
  8655. // Fetch maintenance overview for all printers to show badges
  8656. const { data: maintenanceOverview } = useQuery({
  8657. queryKey: ['maintenanceOverview'],
  8658. queryFn: api.getMaintenanceOverview,
  8659. staleTime: 60 * 1000, // 1 minute
  8660. });
  8661. // Live AI failure detection state for the card badges (#1546). Matches the
  8662. // 10s refetch of the Failure Detection settings panel.
  8663. const { data: obicoPrinterStatus } = useQuery({
  8664. queryKey: ['obico-printer-status'],
  8665. queryFn: api.getObicoPrinterStatus,
  8666. refetchInterval: 10000,
  8667. });
  8668. // Badge visibility: detection enabled AND this printer in the monitored set
  8669. // (monitored_printers null = all). Live per-print state is passed separately.
  8670. const isAiMonitored = useCallback(
  8671. (printerId: number) =>
  8672. obicoPrinterStatus?.enabled === true &&
  8673. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8674. [obicoPrinterStatus],
  8675. );
  8676. // Fetch Spoolman status to enable link spool feature
  8677. const { data: spoolmanStatus } = useQuery({
  8678. queryKey: ['spoolman-status'],
  8679. queryFn: api.getSpoolmanStatus,
  8680. staleTime: 60 * 1000, // 1 minute
  8681. });
  8682. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8683. // Fetch Spoolman settings to get sync mode
  8684. const { data: spoolmanSettings } = useQuery({
  8685. queryKey: ['spoolman-settings'],
  8686. queryFn: api.getSpoolmanSettings,
  8687. enabled: !!spoolmanEnabled,
  8688. staleTime: 60 * 1000, // 1 minute
  8689. });
  8690. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8691. // Fetch unlinked spools to know if link button should be enabled
  8692. const { data: unlinkedSpools } = useQuery({
  8693. queryKey: ['unlinked-spools'],
  8694. queryFn: api.getUnlinkedSpools,
  8695. enabled: !!spoolmanEnabled,
  8696. staleTime: 30 * 1000, // 30 seconds
  8697. });
  8698. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8699. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8700. const { data: linkedSpoolsData } = useQuery({
  8701. queryKey: ['linked-spools'],
  8702. queryFn: api.getLinkedSpools,
  8703. enabled: !!spoolmanEnabled,
  8704. staleTime: 30 * 1000, // 30 seconds
  8705. });
  8706. const linkedSpools = linkedSpoolsData?.linked;
  8707. // Fetch spool assignments for inventory feature
  8708. const { data: spoolAssignments } = useQuery({
  8709. queryKey: ['spool-assignments'],
  8710. queryFn: () => api.getAssignments(),
  8711. enabled: hasPermission('inventory:view_assignments'),
  8712. staleTime: 30 * 1000,
  8713. });
  8714. const unassignMutation = useMutation({
  8715. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8716. api.unassignSpool(printerId, amsId, trayId),
  8717. onSuccess: () => {
  8718. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8719. },
  8720. });
  8721. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8722. queryKey: ['spoolman-inventory-spools'],
  8723. queryFn: () => api.getSpoolmanInventorySpools(false),
  8724. enabled: !!spoolmanEnabled,
  8725. staleTime: 30 * 1000,
  8726. });
  8727. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8728. queryKey: ['spoolman-slot-assignments'],
  8729. queryFn: () => api.getSpoolmanSlotAssignments(),
  8730. enabled: !!spoolmanEnabled,
  8731. staleTime: 30 * 1000,
  8732. });
  8733. const unassignSpoolmanMutation = useMutation({
  8734. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8735. onSuccess: () => {
  8736. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8737. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8738. },
  8739. });
  8740. // Helper to find assignment for a specific slot
  8741. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8742. return spoolAssignments?.find(
  8743. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8744. );
  8745. };
  8746. // Create a map of printer_id -> maintenance info for quick lookup
  8747. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8748. (acc, overview) => {
  8749. acc[overview.printer_id] = {
  8750. due_count: overview.due_count,
  8751. warning_count: overview.warning_count,
  8752. total_print_hours: overview.total_print_hours,
  8753. };
  8754. return acc;
  8755. },
  8756. {} as Record<number, PrinterMaintenanceInfo>
  8757. ) || {};
  8758. // Create a map of printer_id -> smart plug
  8759. const smartPlugByPrinter = smartPlugs?.reduce(
  8760. (acc, plug) => {
  8761. if (plug.printer_id) {
  8762. acc[plug.printer_id] = plug;
  8763. }
  8764. return acc;
  8765. },
  8766. {} as Record<number, typeof smartPlugs[0]>
  8767. ) || {};
  8768. const addMutation = useMutation({
  8769. mutationFn: api.createPrinter,
  8770. onSuccess: () => {
  8771. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8772. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8773. setShowAddModal(false);
  8774. },
  8775. onError: (error: Error) => {
  8776. // Localized message when the backend returns a stable error code;
  8777. // the raw message is an English fallback for non-UI clients.
  8778. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8779. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8780. return;
  8781. }
  8782. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8783. },
  8784. });
  8785. const powerOnMutation = useMutation({
  8786. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8787. onSuccess: () => {
  8788. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8789. setPoweringOn(null);
  8790. },
  8791. onError: () => {
  8792. setPoweringOn(null);
  8793. },
  8794. });
  8795. // Bulk selection state
  8796. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8797. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8798. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8799. const [bulkActionPending, setBulkActionPending] = useState(false);
  8800. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8801. const toggleSelect = useCallback((id: number) => {
  8802. setSelectedPrinterIds(prev => {
  8803. const next = new Set(prev);
  8804. if (next.has(id)) next.delete(id);
  8805. else next.add(id);
  8806. return next;
  8807. });
  8808. }, []);
  8809. const clearSelection = useCallback(() => {
  8810. setSelectedPrinterIds(new Set());
  8811. setIsSelectionMode(false);
  8812. }, []);
  8813. // Escape key exits selection mode
  8814. useEffect(() => {
  8815. const handleKeyDown = (e: KeyboardEvent) => {
  8816. if (e.key === 'Escape' && selectionMode) {
  8817. clearSelection();
  8818. }
  8819. };
  8820. window.addEventListener('keydown', handleKeyDown);
  8821. return () => window.removeEventListener('keydown', handleKeyDown);
  8822. }, [selectionMode, clearSelection]);
  8823. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8824. setBulkActionPending(true);
  8825. const ids = Array.from(selectedPrinterIds);
  8826. // Filter to only applicable printers based on cached state
  8827. const applicableIds = ids.filter(id => {
  8828. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8829. // clearPlate is checked before the connection filter: it only releases a
  8830. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8831. // down — every other action here needs to reach the machine (#2864).
  8832. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8833. if (!status?.connected) return false;
  8834. switch (action) {
  8835. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8836. case 'pause': return status.state === 'RUNNING';
  8837. case 'resume': return status.state === 'PAUSE';
  8838. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8839. default: return false;
  8840. }
  8841. });
  8842. if (applicableIds.length === 0) {
  8843. showToast(t('printers.bulk.noneApplicable'), 'error');
  8844. setBulkActionPending(false);
  8845. setBulkConfirmAction(null);
  8846. return;
  8847. }
  8848. const apiCall = {
  8849. stop: api.stopPrint,
  8850. pause: api.pausePrint,
  8851. resume: api.resumePrint,
  8852. clearPlate: api.clearPlate,
  8853. clearHMS: api.clearHMSErrors,
  8854. }[action];
  8855. const results = await Promise.allSettled(
  8856. applicableIds.map(id => apiCall(id))
  8857. );
  8858. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8859. const failed = results.filter(r => r.status === 'rejected').length;
  8860. if (failed === 0) {
  8861. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8862. } else {
  8863. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8864. }
  8865. // Invalidate status queries for affected printers
  8866. applicableIds.forEach(id => {
  8867. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8868. });
  8869. setBulkActionPending(false);
  8870. setBulkConfirmAction(null);
  8871. }, [selectedPrinterIds, queryClient, showToast, t]);
  8872. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8873. // Actions that need confirmation
  8874. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8875. setBulkConfirmAction(action);
  8876. } else {
  8877. executeBulkAction(action);
  8878. }
  8879. }, [executeBulkAction]);
  8880. const toggleHideDisconnected = () => {
  8881. const newValue = !hideDisconnected;
  8882. setHideDisconnected(newValue);
  8883. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8884. };
  8885. const handleSortChange = (newSort: SortOption) => {
  8886. setSortBy(newSort);
  8887. localStorage.setItem('printerSortBy', newSort);
  8888. };
  8889. const handleStatusFilterChange = (value: string) => {
  8890. setStatusFilter(value);
  8891. localStorage.setItem('printerStatusFilter', value);
  8892. };
  8893. const handleLocationFilterChange = (value: string) => {
  8894. setLocationFilter(value);
  8895. localStorage.setItem('printerLocationFilter', value);
  8896. };
  8897. const toggleSortDirection = () => {
  8898. const newAsc = !sortAsc;
  8899. setSortAsc(newAsc);
  8900. localStorage.setItem('printerSortAsc', String(newAsc));
  8901. };
  8902. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8903. const getGridClasses = () => {
  8904. switch (cardSize) {
  8905. 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
  8906. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8907. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8908. case 4: return 'grid-cols-1'; // XL: single column, full width
  8909. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8910. }
  8911. };
  8912. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8913. // Increment version counter whenever a printer status cache entry is updated so
  8914. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8915. useEffect(() => {
  8916. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8917. if (
  8918. event.type === 'updated' &&
  8919. Array.isArray(event.query.queryKey) &&
  8920. event.query.queryKey[0] === 'printerStatus'
  8921. ) {
  8922. setStatusCacheVersion(v => v + 1);
  8923. }
  8924. });
  8925. return unsubscribe;
  8926. }, [queryClient]);
  8927. // Filter printers by search term, status, and location
  8928. const filteredPrinters = useMemo(() => {
  8929. if (!printers) return [];
  8930. let result = printers;
  8931. // Text search
  8932. if (search.trim()) {
  8933. const q = search.trim().toLowerCase();
  8934. result = result.filter(p =>
  8935. p.name.toLowerCase().includes(q) ||
  8936. (p.model || '').toLowerCase().includes(q) ||
  8937. (p.location || '').toLowerCase().includes(q) ||
  8938. (p.serial_number || '').toLowerCase().includes(q)
  8939. );
  8940. }
  8941. // Location filter
  8942. if (locationFilter !== 'all') {
  8943. result = result.filter(p => (p.location || '') === locationFilter);
  8944. }
  8945. // Status filter
  8946. if (statusFilter !== 'all') {
  8947. result = result.filter(p => {
  8948. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8949. if (!status?.connected) return statusFilter === 'offline';
  8950. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8951. switch (statusFilter) {
  8952. case 'printing': return status.state === 'RUNNING';
  8953. case 'paused': return status.state === 'PAUSE';
  8954. case 'finished': return status.state === 'FINISH';
  8955. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8956. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8957. case 'offline': return false; // Connected printers are never offline
  8958. default: return true;
  8959. }
  8960. });
  8961. }
  8962. return result;
  8963. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8964. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8965. // Derive unique locations for the location filter dropdown
  8966. const availableLocations = useMemo(() => {
  8967. if (!printers) return [];
  8968. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8969. }, [printers]);
  8970. // A saved location can outlive what it matched -- renamed, cleared, or the
  8971. // only printer that had it deleted. The dropdown is rendered only while some
  8972. // printer has a location, so a stale one would hide every printer *and* the
  8973. // control to undo it, leaving an empty page and no way back (#2833).
  8974. // Deliberately waits for `printers`: it is undefined while the query is in
  8975. // flight, and acting on the empty list that produces would throw the saved
  8976. // filter away every time the page loads.
  8977. useEffect(() => {
  8978. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8979. setLocationFilter('all');
  8980. localStorage.setItem('printerLocationFilter', 'all');
  8981. }, [printers, availableLocations, locationFilter]);
  8982. // Sort printers based on selected option
  8983. const sortedPrinters = useMemo(() => {
  8984. const sorted = [...filteredPrinters];
  8985. switch (sortBy) {
  8986. case 'name':
  8987. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8988. break;
  8989. case 'model':
  8990. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8991. break;
  8992. case 'location':
  8993. // Sort by location, with ungrouped printers last
  8994. sorted.sort((a, b) => {
  8995. const locA = a.location || '';
  8996. const locB = b.location || '';
  8997. if (!locA && locB) return 1;
  8998. if (locA && !locB) return -1;
  8999. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  9000. });
  9001. break;
  9002. case 'status':
  9003. // Sort by status: HMS errors > printing > idle > offline
  9004. sorted.sort((a, b) => {
  9005. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  9006. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  9007. const getPriority = (s: typeof statusA) => {
  9008. if (!s?.connected) return 3; // offline
  9009. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  9010. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  9011. if (s.state === 'RUNNING') return 1; // printing
  9012. return 2; // idle
  9013. };
  9014. return getPriority(statusA) - getPriority(statusB);
  9015. });
  9016. break;
  9017. case 'eta':
  9018. sorted.sort((a, b) => {
  9019. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  9020. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  9021. const tier = (s: typeof statusA) => {
  9022. if (!s?.connected) return 3; // offline last
  9023. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  9024. if (s.state === 'RUNNING') return 1; // printing without ETA
  9025. return 2; // idle
  9026. };
  9027. const ta = tier(statusA);
  9028. const tb = tier(statusB);
  9029. if (ta !== tb) return ta - tb;
  9030. if (ta === 0) {
  9031. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  9032. if (diff !== 0) return diff;
  9033. }
  9034. return a.name.localeCompare(b.name);
  9035. });
  9036. break;
  9037. }
  9038. // Apply ascending/descending
  9039. if (!sortAsc) {
  9040. sorted.reverse();
  9041. }
  9042. return sorted;
  9043. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  9044. const selectAll = useCallback(() => {
  9045. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  9046. setIsSelectionMode(true);
  9047. }, [sortedPrinters]);
  9048. const selectByState = useCallback((state: PrinterState) => {
  9049. setSelectedPrinterIds(prev => {
  9050. const next = new Set(prev);
  9051. sortedPrinters.forEach(p => {
  9052. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  9053. if (classifyPrinterStatus(status) === state) next.add(p.id);
  9054. });
  9055. return next;
  9056. });
  9057. setIsSelectionMode(true);
  9058. }, [sortedPrinters, queryClient]);
  9059. const selectByLocation = useCallback((location: string) => {
  9060. setSelectedPrinterIds(prev => {
  9061. const next = new Set(prev);
  9062. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  9063. return next;
  9064. });
  9065. setIsSelectionMode(true);
  9066. }, [sortedPrinters]);
  9067. const selectByModel = useCallback((model: string) => {
  9068. setSelectedPrinterIds(prev => {
  9069. const next = new Set(prev);
  9070. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9071. return next;
  9072. });
  9073. setIsSelectionMode(true);
  9074. }, [sortedPrinters]);
  9075. const toggleSectionCollapse = useCallback((key: string) => {
  9076. setCollapsedSections(prev => {
  9077. const next = { ...prev, [key]: !prev[key] };
  9078. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9079. return next;
  9080. });
  9081. }, []);
  9082. // Group printers when sorted by location, status, or model
  9083. const groupedPrinters = useMemo(() => {
  9084. if (sortBy === 'name' || sortBy === 'eta') return null;
  9085. const groups: Record<string, typeof sortedPrinters> = {};
  9086. if (sortBy === 'location') {
  9087. sortedPrinters.forEach(printer => {
  9088. const location = printer.location || 'Ungrouped';
  9089. if (!groups[location]) groups[location] = [];
  9090. groups[location].push(printer);
  9091. });
  9092. } else if (sortBy === 'model') {
  9093. sortedPrinters.forEach(printer => {
  9094. const model = printer.model || 'Unknown';
  9095. if (!groups[model]) groups[model] = [];
  9096. groups[model].push(printer);
  9097. });
  9098. } else if (sortBy === 'status') {
  9099. sortedPrinters.forEach(printer => {
  9100. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9101. const group = classifyPrinterStatus(status);
  9102. if (!groups[group]) groups[group] = [];
  9103. groups[group].push(printer);
  9104. });
  9105. }
  9106. return groups;
  9107. // 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
  9108. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9109. const toolbarRef = useRef<HTMLDivElement>(null);
  9110. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9111. const expandedToolbarWidthRef = useRef(0);
  9112. const [compactToolbar, setCompactToolbar] = useState(false);
  9113. const measureToolbar = useCallback(() => {
  9114. const toolbar = toolbarRef.current;
  9115. if (!toolbar) return;
  9116. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9117. if (measuredControlsWidth) {
  9118. expandedToolbarWidthRef.current = measuredControlsWidth;
  9119. }
  9120. const searchMinimumWidth = 220;
  9121. const gapWidth = 8;
  9122. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9123. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9124. }, []);
  9125. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9126. useLayoutEffect(() => {
  9127. measureToolbar();
  9128. const toolbar = toolbarRef.current;
  9129. if (!toolbar) return;
  9130. if (typeof ResizeObserver === 'undefined') {
  9131. window.addEventListener('resize', measureToolbar);
  9132. return () => window.removeEventListener('resize', measureToolbar);
  9133. }
  9134. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9135. resizeObserver.observe(toolbar);
  9136. window.addEventListener('resize', measureToolbar);
  9137. return () => {
  9138. resizeObserver.disconnect();
  9139. window.removeEventListener('resize', measureToolbar);
  9140. };
  9141. }, [
  9142. measureToolbar,
  9143. printers?.length,
  9144. availableLocations.length,
  9145. hideDisconnected,
  9146. smartPlugCount,
  9147. ]);
  9148. const renderFilterControls = (inMenu = false) => (
  9149. <>
  9150. {/* Status filter */}
  9151. {printers && printers.length > 0 && (
  9152. <ToolbarDropdown
  9153. value={statusFilter}
  9154. onChange={handleStatusFilterChange}
  9155. fullWidth={inMenu}
  9156. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9157. />
  9158. )}
  9159. {/* Location filter — only shown when at least one printer has a location */}
  9160. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9161. <ToolbarDropdown
  9162. value={locationFilter}
  9163. onChange={handleLocationFilterChange}
  9164. fullWidth={inMenu}
  9165. options={[
  9166. { value: 'all', label: t('printers.filter.allLocations') },
  9167. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9168. ]}
  9169. />
  9170. )}
  9171. <button
  9172. type="button"
  9173. onClick={toggleHideDisconnected}
  9174. aria-pressed={hideDisconnected}
  9175. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9176. hideDisconnected
  9177. ? 'bg-bambu-green border-bambu-green text-white'
  9178. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9179. }`}
  9180. >
  9181. {t('printers.hideOffline')}
  9182. </button>
  9183. </>
  9184. );
  9185. const renderViewControls = (inMenu = false) => (
  9186. <>
  9187. {/* Sort dropdown */}
  9188. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9189. <ToolbarDropdown<SortOption>
  9190. value={sortBy}
  9191. onChange={handleSortChange}
  9192. fullWidth={inMenu}
  9193. options={[
  9194. { value: 'name', label: t('printers.sort.name') },
  9195. { value: 'status', label: t('printers.sort.status') },
  9196. { value: 'model', label: t('printers.sort.model') },
  9197. { value: 'location', label: t('printers.sort.location') },
  9198. { value: 'eta', label: t('printers.sort.eta') },
  9199. ]}
  9200. />
  9201. <button
  9202. onClick={toggleSortDirection}
  9203. 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"
  9204. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9205. >
  9206. {sortAsc ? (
  9207. <ArrowUp className="w-4 h-4 text-white" />
  9208. ) : (
  9209. <ArrowDown className="w-4 h-4 text-white" />
  9210. )}
  9211. </button>
  9212. </div>
  9213. {/* Page view toggle: Cards / Cam Wall */}
  9214. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9215. <button
  9216. type="button"
  9217. onClick={() => {
  9218. setPageView('cards');
  9219. localStorage.setItem('printerPageView', 'cards');
  9220. }}
  9221. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9222. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9223. }`}
  9224. title={t('printers.pageView.cards')}
  9225. aria-pressed={pageView === 'cards'}
  9226. >
  9227. <LayoutGrid className="w-3.5 h-3.5" />
  9228. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9229. </button>
  9230. <button
  9231. type="button"
  9232. onClick={() => {
  9233. setPageView('camwall');
  9234. localStorage.setItem('printerPageView', 'camwall');
  9235. }}
  9236. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9237. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9238. }`}
  9239. title={t('printers.pageView.camWall')}
  9240. aria-pressed={pageView === 'camwall'}
  9241. disabled={!hasPermission('camera:view')}
  9242. >
  9243. <MonitorPlay className="w-3.5 h-3.5" />
  9244. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9245. </button>
  9246. </div>
  9247. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9248. view, and the page a kiosk token points at. Only offered once the wall
  9249. is the active view, so it doesn't compete with the toggle above. */}
  9250. {pageView === 'camwall' && hasPermission('camera:view') && (
  9251. <RouterLink
  9252. to="/camwall"
  9253. className={`flex h-8 items-center gap-1 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary ${inMenu ? 'w-full justify-center' : ''}`}
  9254. title={t('printers.pageView.openCamWallPage')}
  9255. >
  9256. <ExternalLink className="w-3.5 h-3.5" />
  9257. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9258. </RouterLink>
  9259. )}
  9260. {/* Card size selector */}
  9261. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${pageView === 'camwall' ? 'opacity-40 pointer-events-none' : ''} ${inMenu ? 'w-full' : ''}`}>
  9262. {cardSizeLabels.map((label, index) => {
  9263. const size = index + 1;
  9264. const isSelected = cardSize === size;
  9265. return (
  9266. <button
  9267. key={label}
  9268. onClick={() => {
  9269. setCompactDrilldownPrinterId(null);
  9270. setCardSize(size);
  9271. localStorage.setItem('printerCardSize', String(size));
  9272. }}
  9273. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9274. index === 0 ? 'rounded-l-lg' : ''
  9275. } ${
  9276. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9277. } ${
  9278. isSelected
  9279. ? 'bg-bambu-green text-white'
  9280. : 'text-white hover:bg-bambu-dark-tertiary'
  9281. }`}
  9282. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  9283. >
  9284. {label}
  9285. </button>
  9286. );
  9287. })}
  9288. </div>
  9289. </>
  9290. );
  9291. const renderActionControls = (inMenu = false) => (
  9292. <>
  9293. {/* Bulk select toggle */}
  9294. <button
  9295. onClick={() => {
  9296. if (selectionMode) clearSelection();
  9297. else setIsSelectionMode(true);
  9298. }}
  9299. 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' : ''} ${
  9300. selectionMode
  9301. ? 'bg-bambu-green border-bambu-green text-white'
  9302. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9303. }`}
  9304. title={t('printers.bulk.select')}
  9305. disabled={!hasPermission('printers:control')}
  9306. >
  9307. <CheckSquare className="w-4 h-4" />
  9308. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9309. </button>
  9310. {/* Power dropdown for offline printers with smart plugs */}
  9311. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9312. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9313. <button
  9314. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9315. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9316. inMenu
  9317. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9318. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9319. }`}
  9320. >
  9321. <span className="flex items-center gap-1.5">
  9322. <Power className="w-4 h-4" />
  9323. {t('printers.powerOn')}
  9324. </span>
  9325. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9326. </button>
  9327. {showPowerDropdown && (
  9328. <>
  9329. {/* Backdrop to close dropdown */}
  9330. <div
  9331. className="fixed inset-0 z-10"
  9332. onClick={() => setShowPowerDropdown(false)}
  9333. />
  9334. <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">
  9335. <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">
  9336. {t('printers.offlinePrintersWithPlugs')}
  9337. </div>
  9338. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9339. <PowerDropdownItem
  9340. key={printer.id}
  9341. printer={printer}
  9342. plug={smartPlugByPrinter[printer.id]}
  9343. onPowerOn={(plugId) => {
  9344. setPoweringOn(plugId);
  9345. powerOnMutation.mutate(plugId);
  9346. }}
  9347. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9348. />
  9349. ))}
  9350. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9351. <div className="px-3 py-2 text-sm text-bambu-gray">
  9352. No printers with smart plugs
  9353. </div>
  9354. )}
  9355. </div>
  9356. </>
  9357. )}
  9358. </div>
  9359. )}
  9360. <Button
  9361. onClick={() => setShowAddModal(true)}
  9362. disabled={!hasPermission('printers:create')}
  9363. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9364. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9365. >
  9366. <Plus className="w-4 h-4" />
  9367. {t('printers.addPrinter')}
  9368. </Button>
  9369. </>
  9370. );
  9371. return (
  9372. <div className="p-4 md:p-8">
  9373. <div className="space-y-3 mb-6">
  9374. <div>
  9375. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9376. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9377. {t('printers.title')}
  9378. </h1>
  9379. <StatusSummaryBar printers={printers} />
  9380. </div>
  9381. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9382. {/* Only show search bar when printers exist */}
  9383. {printers && printers.length > 0 && (
  9384. <div className="relative min-w-0 flex-1">
  9385. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9386. <input
  9387. type="search"
  9388. name="printer-search"
  9389. autoComplete="off"
  9390. data-1p-ignore
  9391. data-lpignore="true"
  9392. value={search}
  9393. onChange={(e) => setSearch(e.target.value)}
  9394. placeholder={t('printers.search')}
  9395. aria-label={t('printers.search')}
  9396. 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"
  9397. />
  9398. {search && (
  9399. <button
  9400. type="button"
  9401. aria-label={t('common.clear')}
  9402. onClick={() => setSearch('')}
  9403. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9404. >
  9405. <X className="w-4 h-4" />
  9406. </button>
  9407. )}
  9408. </div>
  9409. )}
  9410. <div
  9411. ref={expandedToolbarControlsRef}
  9412. aria-hidden={compactToolbar}
  9413. inert={compactToolbar}
  9414. 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`}
  9415. >
  9416. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9417. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9418. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9419. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9420. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9421. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9422. </div>
  9423. {compactToolbar && (
  9424. <div className="ml-auto flex items-center justify-end gap-1">
  9425. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9426. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9427. </ToolbarMenu>
  9428. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9429. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9430. </ToolbarMenu>
  9431. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9432. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9433. </ToolbarMenu>
  9434. </div>
  9435. )}
  9436. </div>
  9437. </div>
  9438. {isLoading ? (
  9439. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9440. ) : printers?.length === 0 ? (
  9441. <Card>
  9442. <CardContent className="text-center py-12">
  9443. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9444. <Button
  9445. onClick={() => setShowAddModal(true)}
  9446. disabled={!hasPermission('printers:create')}
  9447. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9448. >
  9449. <Plus className="w-4 h-4" />
  9450. {t('printers.addPrinter')}
  9451. </Button>
  9452. </CardContent>
  9453. </Card>
  9454. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9455. <Card>
  9456. <CardContent className="text-center py-12">
  9457. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9458. </CardContent>
  9459. </Card>
  9460. ) : pageView === 'camwall' ? (
  9461. <CameraWall
  9462. printers={sortedPrinters}
  9463. maxLive={camWallMaxLive}
  9464. snapshotIntervalSec={camWallSnapshotSec}
  9465. onTileClick={(id, name) => {
  9466. // A wall tile has no room for a split button, so it follows the
  9467. // mode the card buttons last chose.
  9468. if (cameraViewMode === 'embedded') {
  9469. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9470. } else {
  9471. openCameraWindow(id);
  9472. }
  9473. }}
  9474. statusMode={camWallStatusMode}
  9475. onChangeMaxLive={(next) => {
  9476. setCamWallMaxLive(next);
  9477. localStorage.setItem('camWallMaxLive', String(next));
  9478. }}
  9479. onChangeSnapshotIntervalSec={(next) => {
  9480. setCamWallSnapshotSec(next);
  9481. localStorage.setItem('camWallSnapshotSec', String(next));
  9482. }}
  9483. onChangeStatusMode={(next) => {
  9484. setCamWallStatusMode(next);
  9485. localStorage.setItem('camWallStatusMode', next);
  9486. }}
  9487. />
  9488. ) : groupedPrinters ? (
  9489. /* Grouped view (location, status, or model) */
  9490. <div className="space-y-6">
  9491. {(() => {
  9492. const keys = sortBy === 'status'
  9493. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9494. : Object.keys(groupedPrinters);
  9495. // For status grouping, asc/desc flips the fixed priority order
  9496. // (asc = error→offline, desc = offline→error). This matches the
  9497. // sort-toggle behaviour for other groupings.
  9498. return (sortAsc ? keys : [...keys].reverse());
  9499. })().map((groupKey) => {
  9500. const groupPrinters = groupedPrinters[groupKey];
  9501. const collapseKey = `${sortBy}:${groupKey}`;
  9502. const isOpen = !collapsedSections[collapseKey];
  9503. const dot = sortBy === 'status'
  9504. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9505. : 'bg-bambu-green';
  9506. const label = sortBy === 'status'
  9507. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9508. : groupKey;
  9509. return (
  9510. <Collapsible
  9511. key={groupKey}
  9512. open={isOpen}
  9513. onToggle={() => toggleSectionCollapse(collapseKey)}
  9514. summaryClassName="py-1"
  9515. summary={
  9516. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9517. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9518. {label}
  9519. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9520. {selectionMode && (
  9521. <button
  9522. onClick={(e) => {
  9523. e.stopPropagation();
  9524. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9525. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9526. else if (sortBy === 'model') selectByModel(groupKey);
  9527. }}
  9528. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9529. >
  9530. {t('printers.bulk.selectAll')}
  9531. </button>
  9532. )}
  9533. </h2>
  9534. }
  9535. >
  9536. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9537. {groupPrinters.map((printer) => (
  9538. <PrinterCard
  9539. key={printer.id}
  9540. printer={printer}
  9541. hideIfDisconnected={hideDisconnected}
  9542. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9543. viewMode={viewMode}
  9544. cardSize={cardSize}
  9545. amsThresholds={settings ? {
  9546. humidityGood: Number(settings.ams_humidity_good) || 40,
  9547. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9548. tempGood: Number(settings.ams_temp_good) || 28,
  9549. tempFair: Number(settings.ams_temp_fair) || 35,
  9550. } : undefined}
  9551. spoolmanEnabled={spoolmanEnabled}
  9552. hasUnlinkedSpools={hasUnlinkedSpools}
  9553. linkedSpools={linkedSpools}
  9554. spoolmanUrl={spoolmanStatus?.url}
  9555. spoolmanSyncMode={spoolmanSyncMode}
  9556. onGetAssignment={getAssignment}
  9557. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9558. spoolmanSpools={spoolmanSpools}
  9559. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9560. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9561. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9562. timeFormat={settings?.time_format || 'system'}
  9563. cameraViewMode={cameraViewMode}
  9564. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9565. onSelectCameraViewMode={selectCameraViewMode}
  9566. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9567. dryingPresets={effectiveDryingPresets}
  9568. nozzleTempPresets={effectiveNozzleTempPresets}
  9569. bedTempPresets={effectiveBedTempPresets}
  9570. chamberTempPresets={effectiveChamberTempPresets}
  9571. fanSpeedPresets={effectiveFanSpeedPresets}
  9572. requirePlateClear={settings?.require_plate_clear === true}
  9573. selectionMode={selectionMode}
  9574. isSelected={selectedPrinterIds.has(printer.id)}
  9575. onToggleSelect={toggleSelect}
  9576. onOpenCompactCard={openCompactCard}
  9577. aiDetectionEnabled={isAiMonitored(printer.id)}
  9578. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9579. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9580. />
  9581. ))}
  9582. </div>
  9583. </Collapsible>
  9584. );
  9585. })}
  9586. </div>
  9587. ) : (
  9588. /* Regular grid view */
  9589. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9590. {sortedPrinters.map((printer) => (
  9591. <PrinterCard
  9592. key={printer.id}
  9593. printer={printer}
  9594. hideIfDisconnected={hideDisconnected}
  9595. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9596. viewMode={viewMode}
  9597. cardSize={cardSize}
  9598. spoolmanEnabled={spoolmanEnabled}
  9599. hasUnlinkedSpools={hasUnlinkedSpools}
  9600. linkedSpools={linkedSpools}
  9601. spoolmanUrl={spoolmanStatus?.url}
  9602. spoolmanSyncMode={spoolmanSyncMode}
  9603. onGetAssignment={getAssignment}
  9604. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9605. spoolmanSpools={spoolmanSpools}
  9606. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9607. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9608. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9609. amsThresholds={settings ? {
  9610. humidityGood: Number(settings.ams_humidity_good) || 40,
  9611. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9612. tempGood: Number(settings.ams_temp_good) || 28,
  9613. tempFair: Number(settings.ams_temp_fair) || 35,
  9614. } : undefined}
  9615. timeFormat={settings?.time_format || 'system'}
  9616. cameraViewMode={cameraViewMode}
  9617. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9618. onSelectCameraViewMode={selectCameraViewMode}
  9619. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9620. dryingPresets={effectiveDryingPresets}
  9621. nozzleTempPresets={effectiveNozzleTempPresets}
  9622. bedTempPresets={effectiveBedTempPresets}
  9623. chamberTempPresets={effectiveChamberTempPresets}
  9624. fanSpeedPresets={effectiveFanSpeedPresets}
  9625. requirePlateClear={settings?.require_plate_clear === true}
  9626. selectionMode={selectionMode}
  9627. isSelected={selectedPrinterIds.has(printer.id)}
  9628. onToggleSelect={toggleSelect}
  9629. onOpenCompactCard={openCompactCard}
  9630. aiDetectionEnabled={isAiMonitored(printer.id)}
  9631. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9632. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9633. />
  9634. ))}
  9635. </div>
  9636. )}
  9637. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9638. <button
  9639. type="button"
  9640. onClick={returnToCompactCards}
  9641. 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}`}
  9642. title={t('common.back', 'Back')}
  9643. >
  9644. <ArrowLeft className="w-4 h-4" />
  9645. {t('common.back', 'Back')}
  9646. </button>
  9647. )}
  9648. {showAddModal && (
  9649. <AddPrinterModal
  9650. onClose={() => setShowAddModal(false)}
  9651. onAdd={(data) => addMutation.mutate(data)}
  9652. existingSerials={printers?.map(p => p.serial_number) || []}
  9653. />
  9654. )}
  9655. {/* Bulk selection toolbar */}
  9656. {selectionMode && printers && (
  9657. <BulkPrinterToolbar
  9658. selectedIds={selectedPrinterIds}
  9659. printers={printers}
  9660. onClose={clearSelection}
  9661. onSelectAll={selectAll}
  9662. onSelectByLocation={selectByLocation}
  9663. onSelectByState={selectByState}
  9664. onAction={handleBulkAction}
  9665. actionPending={bulkActionPending}
  9666. />
  9667. )}
  9668. {/* Bulk action confirmation modals */}
  9669. {bulkConfirmAction === 'stop' && (
  9670. <ConfirmModal
  9671. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9672. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9673. confirmText={t('printers.bulk.confirm.stopButton')}
  9674. variant="danger"
  9675. isLoading={bulkActionPending}
  9676. onConfirm={() => executeBulkAction('stop')}
  9677. onCancel={() => setBulkConfirmAction(null)}
  9678. />
  9679. )}
  9680. {bulkConfirmAction === 'pause' && (
  9681. <ConfirmModal
  9682. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9683. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9684. confirmText={t('printers.bulk.confirm.pauseButton')}
  9685. isLoading={bulkActionPending}
  9686. onConfirm={() => executeBulkAction('pause')}
  9687. onCancel={() => setBulkConfirmAction(null)}
  9688. />
  9689. )}
  9690. {bulkConfirmAction === 'clearPlate' && (
  9691. <ConfirmModal
  9692. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9693. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9694. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9695. isLoading={bulkActionPending}
  9696. onConfirm={() => executeBulkAction('clearPlate')}
  9697. onCancel={() => setBulkConfirmAction(null)}
  9698. />
  9699. )}
  9700. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9701. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9702. <EmbeddedCameraViewer
  9703. key={camera.id}
  9704. printerId={camera.id}
  9705. printerName={camera.name}
  9706. viewerIndex={index}
  9707. onClose={() => setEmbeddedCameraPrinters(prev => {
  9708. const next = new Map(prev);
  9709. next.delete(camera.id);
  9710. return next;
  9711. })}
  9712. />
  9713. ))}
  9714. </div>
  9715. );
  9716. }