| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406 |
- import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
- import { createPortal } from 'react-dom';
- import { compareFwVersions } from '../utils/firmwareVersion';
- import { formatPrintName } from '../utils/printName';
- import { computePopoverPosition } from '../utils/popoverPosition';
- import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
- import {
- isExternalSpoolHidden,
- setExternalSpoolHidden as persistExternalSpoolHidden,
- } from '../utils/printerCardPrefs';
- import {
- BED_TEMP_DEFAULTS,
- CHAMBER_TEMP_DEFAULTS,
- FAN_SPEED_DEFAULTS,
- NOZZLE_TEMP_DEFAULTS,
- buildPresetOptions,
- parsePresetTriple,
- } from '../utils/temperatureFanPresets';
- // AMS drying popover dimensions — w-[240px] on the popover, estimated height
- // covers header + filament select + temp slider + duration + rotate-tray
- // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
- // earlier); under-estimating leaves the popover clipped off the bottom (the
- // original bug at #1447).
- const DRYING_POPOVER_WIDTH = 240;
- const DRYING_POPOVER_ESTIMATED_HEIGHT = 320;
- import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
- import { useTranslation } from 'react-i18next';
- import { useTheme } from '../contexts/ThemeContext';
- import { useAuth } from '../contexts/AuthContext';
- import {
- Plus,
- Link,
- Unlink,
- Signal,
- Clock,
- MoreVertical,
- Trash2,
- RefreshCw,
- RotateCw,
- Box,
- HardDrive,
- AlertTriangle,
- AlertCircle,
- Terminal,
- Power,
- Zap,
- Wrench,
- ChevronDown,
- Eye,
- EyeOff,
- Filter,
- Pencil,
- ArrowLeft,
- ArrowRight,
- ArrowUp,
- ArrowDown,
- Layers,
- Video,
- Search,
- Loader2,
- Square,
- Pause,
- Play,
- X,
- Fan,
- Wind,
- AirVent,
- Download,
- ScanSearch,
- CheckCircle,
- CheckSquare,
- XCircle,
- User,
- Home,
- Printer as PrinterIcon,
- Info,
- Cable,
- Flame,
- Repeat,
- Snowflake,
- Gauge,
- DoorOpen,
- DoorClosed,
- Move,
- LogIn,
- LogOut,
- MoreHorizontal,
- SlidersHorizontal,
- Stethoscope,
- ScanEye,
- LineChart as LineChartIcon,
- LayoutGrid,
- MonitorPlay,
- ExternalLink,
- } from 'lucide-react';
- // Aliased: lucide-react already exports a `Link` icon into this module.
- import { Link as RouterLink, useNavigate } from 'react-router-dom';
- import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
- import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
- import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
- import { Card, CardContent } from '../components/Card';
- import { Button } from '../components/Button';
- import { ConfirmModal } from '../components/ConfirmModal';
- import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
- import { FileManagerModal } from '../components/FileManagerModal';
- import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
- import { CameraWall } from '../components/CameraWall';
- import { MQTTDebugModal } from '../components/MQTTDebugModal';
- import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
- import { AiDetectionModal } from '../components/AiDetectionModal';
- import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
- import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
- import { AMSHistoryModal } from '../components/AMSHistoryModal';
- import { AmsBackupModal } from '../components/AmsBackupModal';
- import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
- import type { HeaterSensorKind } from '../api/client';
- import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
- import { LinkSpoolModal } from '../components/LinkSpoolModal';
- import { AssignSpoolModal } from '../components/AssignSpoolModal';
- import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
- import { useToast } from '../contexts/ToastContext';
- import { ChamberLight } from '../components/icons/ChamberLight';
- import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
- import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
- import { FileUploadModal } from '../components/FileUploadModal';
- import { PrintModal } from '../components/PrintModal';
- import { PrinterInfoModal } from '../components/PrinterInfoModal';
- import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool, resolveSlotNozzleDiameter } from '../utils/amsHelpers';
- import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
- import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
- import { Collapsible } from '../components/Collapsible';
- import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
- import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
- // The status filter's options, and the only values it may hold. One list so a
- // saved filter cannot be validated against a set the dropdown has since moved
- // on from (#2833). Labels stay literal so they remain greppable.
- const STATUS_FILTER_OPTIONS = [
- { value: 'all', labelKey: 'printers.filter.allStatuses' },
- { value: 'printing', labelKey: 'printers.status.printing' },
- { value: 'paused', labelKey: 'printers.status.paused' },
- { value: 'idle', labelKey: 'printers.status.idle' },
- { value: 'finished', labelKey: 'printers.status.finished' },
- { value: 'error', labelKey: 'printers.status.error' },
- { value: 'offline', labelKey: 'printers.status.offline' },
- ] as const;
- function isKnownStatusFilter(value: string | null): boolean {
- return STATUS_FILTER_OPTIONS.some(option => option.value === value);
- }
- export interface SpoolmanSlotAssignmentRow {
- printer_id: number;
- ams_id: number;
- tray_id: number;
- spoolman_spool_id: number;
- }
- // Color names resolve via getColorName() which reads the backend color_catalog
- // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
- // Format K value with 3 decimal places, default to 0.020 if null
- function formatKValue(k: number | null | undefined): string {
- const value = k ?? 0.020;
- return value.toFixed(3);
- }
- // Nozzle side indicators (Bambu Lab style - square badge with L/R)
- function NozzleBadge({ side }: { side: 'L' | 'R' }) {
- const { mode } = useTheme();
- // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
- const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
- return (
- <span
- 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"
- style={{ backgroundColor: bgColor, color: '#00ae42' }}
- >
- {side}
- </span>
- );
- }
- // Expand nozzle type codes to material names
- // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
- // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
- function nozzleTypeName(type: string, t: (key: string) => string): string {
- if (!type) return '';
- // Full text names (from main nozzle info)
- if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
- if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
- if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
- // 4-char codes (e.g. "HS01"): last 2 digits = material
- if (type.length >= 4) {
- const material = type.slice(2, 4);
- if (material === '00') return t('printers.nozzleStainlessSteel');
- if (material === '01') return t('printers.nozzleHardenedSteel');
- if (material === '05') return t('printers.nozzleTungstenCarbide');
- }
- // 2-digit numeric codes
- if (type === '00') return t('printers.nozzleStainlessSteel');
- if (type === '01') return t('printers.nozzleHardenedSteel');
- if (type === '05') return t('printers.nozzleTungstenCarbide');
- // 2-char alpha codes: H prefix = hardened steel
- if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
- return type;
- }
- // Parse flow type from nozzle type code
- // HH = high flow, HS = standard/normal
- function nozzleFlowName(type: string, t: (key: string) => string): string {
- if (!type) return '';
- if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
- if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
- return '';
- }
- // Per-slot hover card for nozzle rack
- // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
- function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
- slot: import('../api/client').NozzleRackSlot;
- index: number;
- activeStatus?: boolean;
- filamentName?: string;
- children: React.ReactNode;
- }) {
- const { t } = useTranslation();
- const [isVisible, setIsVisible] = useState(false);
- const [position, setPosition] = useState<'top' | 'bottom'>('top');
- const triggerRef = useRef<HTMLDivElement>(null);
- const cardRef = useRef<HTMLDivElement>(null);
- const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
- const isMounted = slot.stat === 1;
- useEffect(() => {
- if (isVisible && triggerRef.current && cardRef.current) {
- const triggerRect = triggerRef.current.getBoundingClientRect();
- const cardHeight = cardRef.current.offsetHeight;
- const headerHeight = 56;
- const spaceAbove = triggerRect.top - headerHeight;
- const spaceBelow = window.innerHeight - triggerRect.bottom;
- if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
- setPosition('bottom');
- } else {
- setPosition('top');
- }
- }
- }, [isVisible]);
- const handleMouseEnter = () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
- };
- const handleMouseLeave = () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
- };
- useEffect(() => {
- return () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- };
- }, []);
- const filamentCss = parseFilamentColor(slot.filament_color);
- const typeFull = nozzleTypeName(slot.nozzle_type, t);
- const flowFull = nozzleFlowName(slot.nozzle_type, t);
- return (
- <div
- ref={triggerRef}
- className="relative"
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- >
- {children}
- {isVisible && (
- <div
- ref={cardRef}
- className={`
- absolute left-1/2 -translate-x-1/2 z-50
- ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
- animate-in fade-in-0 zoom-in-95 duration-150
- `}
- style={{ maxWidth: 'calc(100vw - 24px)' }}
- >
- <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
- {isEmpty ? (
- <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
- Slot {index + 1} — Empty
- </div>
- ) : (
- <div className="p-2.5 space-y-1.5">
- {/* Diameter */}
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
- <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
- </div>
- {/* Type */}
- {typeFull && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
- <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
- </div>
- )}
- {/* Flow (hide if empty) */}
- {flowFull && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
- <span className="text-xs text-white font-semibold">{flowFull}</span>
- </div>
- )}
- {/* Status badge */}
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
- <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
- activeStatus || isMounted
- ? 'bg-green-900/50 text-green-400'
- : 'bg-bambu-dark-tertiary text-bambu-gray'
- }`}>
- {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
- </span>
- </div>
- {/* Wear (hide if null) */}
- {slot.wear != null && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
- <span className="text-xs text-white font-semibold">{slot.wear}%</span>
- </div>
- )}
- {/* Max Temp (hide if 0) */}
- {slot.max_temp > 0 && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
- <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
- </div>
- )}
- {/* Serial (hide if empty) */}
- {slot.serial_number && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
- <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
- </div>
- )}
- {/* Filament: material type + color swatch (hide if no color) */}
- {(filamentCss || slot.filament_type) && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
- <div className="flex items-center gap-1">
- {filamentCss && (
- <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
- )}
- <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- {/* Arrow pointer */}
- <div
- className={`
- absolute left-1/2 -translate-x-1/2 w-0 h-0
- border-l-[6px] border-l-transparent
- border-r-[6px] border-r-transparent
- ${position === 'top'
- ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
- : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
- `}
- />
- </div>
- )}
- </div>
- );
- }
- // Dual-nozzle hover card showing L and R nozzle details side by side
- function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
- leftSlot?: import('../api/client').NozzleRackSlot;
- rightSlot?: import('../api/client').NozzleRackSlot;
- activeNozzle: 'L' | 'R';
- filamentInfo?: Record<string, { name: string; k: number | null }>;
- children: React.ReactNode;
- }) {
- const { t } = useTranslation();
- const [isVisible, setIsVisible] = useState(false);
- const [position, setPosition] = useState<'top' | 'bottom'>('top');
- const triggerRef = useRef<HTMLDivElement>(null);
- const cardRef = useRef<HTMLDivElement>(null);
- const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- useEffect(() => {
- if (isVisible && triggerRef.current && cardRef.current) {
- const triggerRect = triggerRef.current.getBoundingClientRect();
- const cardHeight = cardRef.current.offsetHeight;
- const headerHeight = 56;
- const spaceAbove = triggerRect.top - headerHeight;
- const spaceBelow = window.innerHeight - triggerRect.bottom;
- if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
- setPosition('bottom');
- } else {
- setPosition('top');
- }
- }
- }, [isVisible]);
- const handleMouseEnter = () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
- };
- const handleMouseLeave = () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
- };
- useEffect(() => {
- return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
- }, []);
- if (!leftSlot && !rightSlot) return <>{children}</>;
- const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
- const isActive = activeNozzle === side;
- const typeFull = nozzleTypeName(slot.nozzle_type, t);
- const flowFull = nozzleFlowName(slot.nozzle_type, t);
- const filamentCss = parseFilamentColor(slot.filament_color);
- const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
- return (
- <div className="flex-1 space-y-1.5">
- <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'}`}>
- {side === 'L' ? t('common.left') : t('common.right')}
- </div>
- {slot.nozzle_diameter && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
- <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
- </div>
- )}
- {typeFull && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
- <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
- </div>
- )}
- {flowFull && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
- <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
- </div>
- )}
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
- <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
- isActive
- ? 'bg-green-900/50 text-green-400'
- : 'bg-bambu-dark-tertiary text-bambu-gray'
- }`}>
- {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
- </span>
- </div>
- {slot.wear != null && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
- <span className="text-xs text-white font-semibold">{slot.wear}%</span>
- </div>
- )}
- {/* Serial and max temp only available on the right (removable) nozzle */}
- {side === 'R' && slot.max_temp > 0 && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
- <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
- </div>
- )}
- {side === 'R' && slot.serial_number && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
- <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
- </div>
- )}
- {(filamentCss || slot.filament_type || slot.filament_id) && (
- <div className="flex items-center justify-between">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
- <div className="flex items-center gap-1">
- {filamentCss && (
- <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
- )}
- <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
- {filamentName || slot.filament_type || slot.filament_id || ''}
- </span>
- </div>
- </div>
- )}
- </div>
- );
- };
- return (
- <div
- ref={triggerRef}
- className="relative flex-1"
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- >
- {children}
- {isVisible && (
- <div
- ref={cardRef}
- className={`
- absolute left-1/2 -translate-x-1/2 z-50
- ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
- animate-in fade-in-0 zoom-in-95 duration-150
- `}
- style={{ maxWidth: 'calc(100vw - 24px)' }}
- >
- <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
- <div className="p-2.5 flex gap-3">
- {leftSlot && renderColumn(leftSlot, 'L')}
- {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
- {rightSlot && renderColumn(rightSlot, 'R')}
- </div>
- </div>
- {/* Arrow pointer */}
- <div
- className={`
- absolute left-1/2 -translate-x-1/2 w-0 h-0
- border-l-[6px] border-l-transparent
- border-r-[6px] border-r-transparent
- ${position === 'top'
- ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
- : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
- `}
- />
- </div>
- )}
- </div>
- );
- }
- // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
- function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
- const { t } = useTranslation();
- // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
- // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
- // hotend the firmware omits that rack ID entirely, so we must map by the fixed
- // base — computing it from min(present IDs) shifts everything left when slot 16
- // is the one currently mounted (#943).
- const rackNozzles = slots.filter(s => s.id >= 2);
- const RACK_SIZE = 6;
- const RACK_BASE_ID = 16;
- const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
- { length: RACK_SIZE },
- (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
- id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
- max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
- },
- );
- return (
- // Sized to its contents rather than growing: the six chips are a fixed
- // width at any one card size, so extra width would be dead space taken
- // from the temperature cards beside it — which are flex-1 with a 0 basis
- // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
- // stays enabled so the card still gives way on a narrow printer card
- // instead of overflowing.
- <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
- <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
- <div className="flex gap-[3px] justify-center">
- {rackSlots.map((slot, i) => {
- const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
- const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
- const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
- return (
- <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
- <div className="flex flex-col items-center gap-0.5">
- <div
- className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
- isEmpty
- ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
- : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
- }`}
- style={filamentBg ? { backgroundColor: filamentBg } : undefined}
- >
- <span
- data-rack-diameter
- className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
- style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
- >
- {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
- </span>
- </div>
- {/* Physical rack position, so "swap the nozzle in slot 4" can be
- acted on without counting chips. Sits below the chip rather
- than inside it: the chip is barely wider than its own
- diameter text and already carries that over a
- filament-coloured background. */}
- <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
- {i + 1}
- </span>
- </div>
- </NozzleSlotHoverCard>
- );
- })}
- </div>
- </div>
- );
- }
- // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
- function WaterDropEmpty({ className }: { className?: string }) {
- return (
- <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
- <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"/>
- </svg>
- );
- }
- // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
- function WaterDropHalf({ className }: { className?: string }) {
- return (
- <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
- <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"/>
- <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"/>
- </svg>
- );
- }
- // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
- function WaterDropFull({ className }: { className?: string }) {
- return (
- <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
- <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"/>
- <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"/>
- </svg>
- );
- }
- // Thermometer SVG - empty outline
- function ThermometerEmpty({ className }: { className?: string }) {
- return (
- <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
- <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"/>
- <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
- </svg>
- );
- }
- // Thermometer SVG - half filled (gold - same as humidity fair)
- function ThermometerHalf({ className }: { className?: string }) {
- return (
- <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
- <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
- <circle cx="6" cy="15" r="2" fill="#d4a017"/>
- <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"/>
- </svg>
- );
- }
- // Thermometer SVG - fully filled (red - same as humidity bad)
- function ThermometerFull({ className }: { className?: string }) {
- return (
- <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
- <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
- <circle cx="6" cy="15" r="2" fill="#c62828"/>
- <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"/>
- </svg>
- );
- }
- // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
- // Added for visual parity with the thermometer icons on the dual-nozzle card
- // that previously had no icon at all (#1115, design by @m4rtini2).
- function NozzleIcon({ className }: { className?: string }) {
- return (
- <svg
- className={className}
- viewBox="0 0 24 24"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <rect x="9.2" y="3.4" width="5.6" height="8.1" />
- <rect x="6" y="11.5" width="12.1" height="3.7" />
- <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
- </svg>
- );
- }
- // Heater thermometer icon - filled when heating, outline when off
- interface HeaterThermometerProps {
- className?: string;
- color: string; // The color class (e.g., "text-orange-400")
- isHeating: boolean;
- }
- function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
- // Extract the actual color from Tailwind class for SVG fill
- const colorMap: Record<string, string> = {
- 'text-orange-400': '#fb923c',
- 'text-blue-400': '#60a5fa',
- 'text-green-400': '#4ade80',
- };
- const fillColor = colorMap[color] || '#888';
- // Glow style when heating
- const glowStyle = isHeating ? {
- filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
- } : {};
- if (isHeating) {
- // Filled thermometer with glow - heater is ON
- return (
- <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
- <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
- <circle cx="6" cy="15" r="2" fill={fillColor}/>
- <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"/>
- </svg>
- );
- }
- // Empty thermometer - heater is OFF
- return (
- <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
- <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"/>
- <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
- </svg>
- );
- }
- // AMS Filament Backup tri-state indicator + toggle.
- // state=true → ON, click to disable
- // state=false → OFF, click opens modal
- // state=null → unknown/unsupported (e.g. A1 family), click disabled
- interface AmsBackupBadgeProps {
- state: boolean | null;
- onClick: () => void;
- }
- function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
- const { t } = useTranslation();
- const known = state !== null;
- let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
- let title: string;
- if (state === true) {
- className += known
- ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
- : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
- title = t('printers.amsBackup.titleOn');
- } else if (state === false) {
- className += known
- ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
- : 'bg-bambu-dark text-bambu-gray cursor-default';
- title = t('printers.amsBackup.titleOff');
- } else {
- className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
- title = t('printers.amsBackup.titleUnknown');
- }
- return (
- <button
- type="button"
- disabled={!known}
- onClick={() => known && onClick()}
- className={className}
- title={title}
- aria-label={title}
- >
- {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
- </button>
- );
- }
- // Hide/show the external spool in the filament row (#1782). Sized and shaped
- // like AmsBackupBadge so the two sit together in the section header, but
- // pinned to the right-hand end of the rule: this is a view preference for the
- // row, not a property of the printer.
- interface ExternalSpoolToggleProps {
- hidden: boolean;
- onClick: () => void;
- }
- function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
- const { t } = useTranslation();
- const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
- return (
- <button
- type="button"
- onClick={onClick}
- aria-pressed={hidden}
- className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
- hidden
- ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
- : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
- }`}
- title={title}
- aria-label={title}
- >
- {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)]" />}
- </button>
- );
- }
- // Humidity indicator with water drop that fills based on level (Bambu Lab style)
- // Reference: https://github.com/theicedmango/bambu-humidity
- interface HumidityIndicatorProps {
- humidity: number | string;
- goodThreshold?: number; // <= this is green
- fairThreshold?: number; // <= this is orange, > is red
- onClick?: () => void;
- compact?: boolean; // Smaller version for grid layout
- }
- function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
- const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
- const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
- const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
- // Status thresholds (configurable via settings)
- // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
- let textColor: string;
- let statusText: string;
- if (isNaN(humidityValue)) {
- textColor = '#C3C2C1';
- statusText = 'Unknown';
- } else if (humidityValue <= good) {
- textColor = '#22a352'; // Green - Good
- statusText = 'Good';
- } else if (humidityValue <= fair) {
- textColor = '#d4a017'; // Gold - Fair
- statusText = 'Fair';
- } else {
- textColor = '#c62828'; // Red - Bad
- statusText = 'Bad';
- }
- // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
- let DropComponent: React.FC<{ className?: string }>;
- if (isNaN(humidityValue)) {
- DropComponent = WaterDropEmpty;
- } else if (humidityValue <= good) {
- DropComponent = WaterDropEmpty; // Good - empty drop (dry)
- } else if (humidityValue <= fair) {
- DropComponent = WaterDropHalf; // Fair - half filled
- } else {
- DropComponent = WaterDropFull; // Bad - full (too humid)
- }
- return (
- <button
- type="button"
- onClick={onClick}
- className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
- title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
- >
- <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
- <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
- </button>
- );
- }
- // Temperature indicator with dynamic icon and coloring
- interface TemperatureIndicatorProps {
- temp: number;
- goodThreshold?: number; // <= this is blue
- fairThreshold?: number; // <= this is orange, > is red
- onClick?: () => void;
- compact?: boolean; // Smaller version for grid layout
- }
- function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
- // Ensure thresholds are numbers
- const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
- const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
- let textColor: string;
- let statusText: string;
- let ThermoComponent: React.FC<{ className?: string }>;
- if (temp <= good) {
- textColor = '#22a352'; // Green - good (same as humidity)
- statusText = 'Good';
- ThermoComponent = ThermometerEmpty;
- } else if (temp <= fair) {
- textColor = '#d4a017'; // Gold - fair (same as humidity)
- statusText = 'Fair';
- ThermoComponent = ThermometerHalf;
- } else {
- textColor = '#c62828'; // Red - bad (same as humidity)
- statusText = 'Bad';
- ThermoComponent = ThermometerFull;
- }
- return (
- <button
- type="button"
- onClick={onClick}
- className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
- title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
- >
- <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
- <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
- </button>
- );
- }
- /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
- *
- * "physical" — firmware positively confirmed no spool (state 9 or 10). The
- * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
- * every empty-by-bitmask slot lands here regardless of firmware payload
- * shape.
- *
- * "reset" — tray_type is missing/empty but firmware hasn't confirmed
- * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
- * the user cleared with "Reset Slot" where a physical spool may still be
- * loaded but unassigned.
- *
- * Returns null when the slot is loaded (tray_type is present).
- */
- function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
- if (tray?.tray_type) return null;
- // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
- // spool the firmware can't identify is physically present (exists === true)
- // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
- // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
- // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
- if (tray?.exists === true) return 'reset';
- if (tray?.exists === false) return 'physical';
- return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
- }
- // How long to wait for an AMS to report a live drying cycle after the printer
- // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
- // within a couple of seconds; 30s covers the slowest observed push cadence
- // without leaving the user waiting on a verdict.
- const DRY_START_CONFIRM_MS = 30_000;
- export function CoverImage({
- url,
- printName,
- className = 'w-20 h-20',
- radiusClass = 'rounded-lg',
- }: {
- url: string | null;
- printName?: string;
- className?: string;
- radiusClass?: string;
- }) {
- const { t } = useTranslation();
- const [loaded, setLoaded] = useState(false);
- const [error, setError] = useState(false);
- const [showOverlay, setShowOverlay] = useState(false);
- const imgRef = useRef<HTMLImageElement>(null);
- // Cache-bust the image URL when the print name changes so the browser
- // fetches the new cover instead of serving the stale cached image.
- const cacheBustedUrl = useMemo(() => {
- if (!url) return null;
- const sep = url.includes('?') ? '&' : '?';
- return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
- }, [url, printName]);
- // Re-evaluate load state when the image URL changes, and ask the element
- // whether it is already showing something rather than assuming it is not.
- //
- // `onLoad` used to be the only thing that could set `loaded`, and this
- // effect reset it to false unconditionally. That is right when the URL
- // really changes, but it also runs on mount — and the two are not the same
- // situation (#2826). The URL is cache-busted on the print *name*, which is
- // constant for the duration of a print, so navigating away from the
- // printers page and back re-mounts with a byte-identical src that the
- // browser serves from its in-memory cache. The `load` event for a cache hit
- // and React's passive-effect flush are both plain tasks with no ordering
- // between them, so when `load` won, this effect ran afterwards and undid
- // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
- // sat there until a full reload. Nothing recovered it, because the URL
- // never changes again during the print and so this effect never re-runs.
- //
- // Being a race, it reproduced every time for #2826's reporter and not at
- // all here, which is also why the network panel showed no request: there
- // was no request to show.
- //
- // Asking `complete && naturalWidth > 0` settles it without needing to know
- // which of the two ran first. It is also correct for the case the reporter
- // proposed (a `load` that fires before React's handler is live), so the
- // fix stands whichever mechanism is really at work.
- useEffect(() => {
- setError(false);
- const el = imgRef.current;
- setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
- }, [cacheBustedUrl]);
- return (
- <>
- <div
- className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
- onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
- >
- {cacheBustedUrl && !error ? (
- <>
- <img
- ref={imgRef}
- src={cacheBustedUrl}
- alt={t('printers.printPreview')}
- className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
- onLoad={() => setLoaded(true)}
- onError={() => setError(true)}
- />
- {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
- </>
- ) : (
- <Box className="w-8 h-8 text-bambu-gray" />
- )}
- </div>
- {/* Cover Image Overlay */}
- {showOverlay && cacheBustedUrl && (
- <div
- className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
- onClick={() => setShowOverlay(false)}
- >
- <div className="relative max-w-2xl max-h-full">
- <img
- src={cacheBustedUrl}
- alt={t('printers.printPreview')}
- className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
- />
- {printName && (
- <p className="text-white text-center mt-4 text-lg">{printName}</p>
- )}
- </div>
- </div>
- )}
- </>
- );
- }
- interface PrinterMaintenanceInfo {
- due_count: number;
- warning_count: number;
- total_print_hours: number;
- }
- // Status summary bar component - uses queryClient to read cached statuses
- function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
- const { t } = useTranslation();
- const queryClient = useQueryClient();
- // Subscribe to query cache changes to re-render when status updates
- // Throttled to prevent rapid re-renders from causing tab crashes
- const [cacheTick, setCacheTick] = useState(0);
- useEffect(() => {
- let pending = false;
- const unsubscribe = queryClient.getQueryCache().subscribe(() => {
- if (!pending) {
- pending = true;
- requestAnimationFrame(() => {
- setCacheTick(t => t + 1);
- pending = false;
- });
- }
- });
- return () => unsubscribe();
- }, [queryClient]);
- const { counts, nextFinish } = useMemo(() => {
- let printing = 0;
- let paused = 0;
- let finished = 0;
- let idle = 0;
- let offline = 0;
- let loading = 0;
- let error = 0;
- let nextPrinterName: string | null = null;
- let nextRemainingMin: number | null = null;
- let nextProgress: number = 0;
- printers?.forEach((printer) => {
- const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
- if (status === undefined) {
- // Status not yet loaded - don't count as offline yet
- loading++;
- } else if (!status.connected) {
- offline++;
- } else {
- // Count printers with active HMS errors as problems
- const knownHmsCount =
- status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
- if (knownHmsCount > 0) {
- error++;
- }
- switch (status.state) {
- case 'RUNNING':
- printing++;
- if (status.remaining_time != null && status.remaining_time > 0) {
- if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
- nextRemainingMin = status.remaining_time;
- nextPrinterName = printer.name;
- nextProgress = status.progress || 0;
- }
- }
- break;
- case 'PAUSE':
- paused++;
- break;
- case 'FINISH':
- finished++;
- break;
- case 'FAILED':
- // FAILED is the printer's terminal gcode_state after a print stops —
- // including user cancellations, where there's no actual fault. Only
- // count it as a "problem" when an HMS error is also active; otherwise
- // it's just a print that ended unsuccessfully and the plate needs
- // clearing (same as FINISH from the operator's perspective).
- if (knownHmsCount > 0) {
- // Already counted above
- } else {
- finished++;
- }
- break;
- default:
- idle++;
- break;
- }
- }
- });
- return {
- counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
- nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [printers, queryClient, cacheTick]);
- if (!printers?.length) return null;
- const badges: { count: number; dot: string; label: string }[] = [
- { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
- { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
- { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
- { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
- { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
- { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
- ];
- return (
- <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
- {badges.map(({ count, dot, label }) => count > 0 && (
- <div key={label} className="flex items-center gap-1.5">
- <div className={`w-2 h-2 rounded-full ${dot}`} />
- <span className="text-bambu-gray">
- <span className="text-white font-medium">{count}</span> {label}
- </span>
- </div>
- ))}
- {nextFinish && (
- <>
- <div className="w-px h-4 bg-bambu-dark-tertiary" />
- <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
- <div className="flex items-center gap-2">
- <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
- <span className="text-white font-medium">{nextFinish.name}</span>
- </div>
- <div className="flex items-center gap-2 w-full sm:w-auto">
- <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
- <div
- className="bg-bambu-green h-1.5 rounded-full transition-all"
- style={{ width: `${nextFinish.progress}%` }}
- />
- </div>
- <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
- <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
- </div>
- </div>
- </>
- )}
- </div>
- );
- }
- type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
- type ViewMode = 'expanded' | 'compact';
- type ToolbarDropdownOption<T extends string> = {
- value: T;
- label: string;
- };
- function ToolbarDropdown<T extends string>({
- value,
- options,
- onChange,
- fullWidth = false,
- }: {
- value: T;
- options: ToolbarDropdownOption<T>[];
- onChange: (value: T) => void;
- fullWidth?: boolean;
- }) {
- const [isOpen, setIsOpen] = useState(false);
- const selectedOption = options.find(option => option.value === value) ?? options[0];
- return (
- <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
- <button
- type="button"
- onClick={() => setIsOpen(open => !open)}
- 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'}`}
- >
- <span className="truncate">{selectedOption?.label}</span>
- <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
- </button>
- {isOpen && (
- <>
- <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
- <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">
- {options.map(option => (
- <button
- key={option.value}
- type="button"
- onClick={() => {
- onChange(option.value);
- setIsOpen(false);
- }}
- className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
- option.value === value ? 'text-bambu-green' : 'text-white'
- }`}
- >
- {option.label}
- </button>
- ))}
- </div>
- </>
- )}
- </div>
- );
- }
- function ToolbarMenu({
- label,
- icon,
- children,
- }: {
- label: string;
- icon: React.ReactNode;
- children: React.ReactNode;
- }) {
- const [isOpen, setIsOpen] = useState(false);
- return (
- <div className="relative">
- <button
- type="button"
- onClick={() => setIsOpen(open => !open)}
- 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"
- aria-label={label}
- title={label}
- >
- {icon}
- </button>
- {isOpen && (
- <>
- <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
- <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">
- {children}
- </div>
- </>
- )}
- </div>
- );
- }
- function IndicatorControlPopover({
- title,
- options = [],
- unit,
- customMin,
- customMax,
- customStep = 1,
- widthClass = 'w-[240px]',
- popoverWidth = 240,
- popoverHeight = 280,
- isPending,
- onClose,
- onSubmit,
- children,
- }: {
- title: string;
- options?: Array<{ label: string; value: number }>;
- unit?: string;
- customMin?: number;
- customMax?: number;
- customStep?: number;
- widthClass?: string;
- popoverWidth?: number;
- popoverHeight?: number;
- isPending?: boolean;
- onClose: () => void;
- onSubmit?: (value: number) => void;
- children?: React.ReactNode;
- }) {
- const anchorRef = useRef<HTMLSpanElement>(null);
- const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
- const [customValue, setCustomValue] = useState('');
- // Anchor to the trigger (the popover's DOM parent before portaling) so we
- // can position via fixed coords. Portaling to document.body escapes
- // ancestor stacking contexts — sibling PrinterCard wrappers create their
- // own contexts and would otherwise cover the popover even at z-[60].
- useLayoutEffect(() => {
- const trigger = anchorRef.current?.parentElement;
- if (!trigger) return;
- const measure = () => {
- const rect = trigger.getBoundingClientRect();
- setCoords(computePopoverPosition({
- triggerRect: rect,
- popoverWidth,
- estimatedHeight: popoverHeight,
- horizontalAlign: 'center',
- }));
- };
- measure();
- window.addEventListener('resize', measure);
- window.addEventListener('scroll', measure, true);
- return () => {
- window.removeEventListener('resize', measure);
- window.removeEventListener('scroll', measure, true);
- };
- }, [popoverWidth, popoverHeight]);
- const showCustomInput = unit !== undefined;
- const submitCustom = () => {
- const value = Number(customValue);
- if (!Number.isFinite(value)) return;
- const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
- onSubmit?.(Math.round(bounded));
- };
- return (
- <>
- <span ref={anchorRef} className="hidden" aria-hidden="true" />
- {createPortal(
- <>
- <div className="fixed inset-0 z-[1000]" onClick={onClose} />
- <div
- className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
- style={{
- top: coords?.top ?? -9999,
- left: coords?.left ?? -9999,
- visibility: coords ? 'visible' : 'hidden',
- }}
- onClick={e => e.stopPropagation()}
- >
- <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
- <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
- {options.length > 0 && (
- <div className="px-3 py-2.5">
- <div className="grid grid-cols-2 gap-1.5">
- {options.map(option => (
- <button
- key={`${option.label}-${option.value}`}
- type="button"
- disabled={isPending}
- onClick={() => onSubmit?.(option.value)}
- 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"
- >
- {option.label}
- </button>
- ))}
- </div>
- </div>
- )}
- {children}
- {showCustomInput && (
- <>
- <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
- <form
- className="flex gap-1.5 px-3 pt-2.5 pb-3"
- onSubmit={(e) => {
- e.preventDefault();
- submitCustom();
- }}
- >
- <input
- type="number"
- min={customMin}
- max={customMax}
- step={customStep}
- value={customValue}
- onChange={e => setCustomValue(e.target.value)}
- placeholder="Custom"
- 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"
- />
- <button
- type="submit"
- disabled={isPending || customValue.trim() === ''}
- 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"
- >
- Set
- </button>
- </form>
- </>
- )}
- </div>
- </>,
- document.body
- )}
- </>
- );
- }
- const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
- function NozzleTemperatureControlBox({
- label,
- current,
- target,
- isActive,
- isPending,
- onSubmit,
- options = NOZZLE_TEMPERATURE_OPTIONS,
- }: {
- label: string;
- current?: number;
- target?: number;
- isActive: boolean;
- isPending?: boolean;
- onSubmit: (value: number) => void;
- options?: Array<{ label: string; value: number }>;
- }) {
- const [customValue, setCustomValue] = useState('');
- const submitCustom = () => {
- const value = Number(customValue);
- if (!Number.isFinite(value)) return;
- onSubmit(Math.min(320, Math.max(0, Math.round(value))));
- };
- return (
- <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'}`}>
- <div className="mb-1.5 flex items-center justify-between gap-2">
- <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
- <span className="text-[10px] text-bambu-gray">
- {Math.round(current ?? 0)}°C
- {target !== undefined ? ` / ${Math.round(target)}°` : ''}
- </span>
- </div>
- <div className="grid grid-cols-2 gap-1">
- {options.map(option => (
- <button
- key={`${label}-${option.value}`}
- type="button"
- disabled={isPending}
- onClick={() => onSubmit(option.value)}
- 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"
- >
- {option.label}
- </button>
- ))}
- </div>
- <form
- className="mt-1.5 flex gap-1"
- onSubmit={(e) => {
- e.preventDefault();
- submitCustom();
- }}
- >
- <input
- type="number"
- min={0}
- max={320}
- step={1}
- value={customValue}
- onChange={e => setCustomValue(e.target.value)}
- placeholder="Custom"
- 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"
- />
- <button
- type="submit"
- disabled={isPending || customValue.trim() === ''}
- 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"
- >
- Set
- </button>
- </form>
- </div>
- );
- }
- const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
- const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
- error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
- printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
- paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
- finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
- idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
- offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
- };
- /** Classify a printer into one of the UI status buckets. */
- function classifyPrinterStatus(
- status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
- ): PrinterState {
- if (!status?.connected) return 'offline';
- const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
- if (hmsErrors.length > 0) return 'error';
- switch (status.state) {
- case 'RUNNING': return 'printing';
- case 'PAUSE': return 'paused';
- case 'FINISH': return 'finished';
- // FAILED without an active HMS error is the printer's terminal state after
- // any unsuccessful end — including user-cancellations. Treat the same as
- // FINISH for grouping/badging purposes; only escalate to "error" when an
- // HMS code is actually attached (handled by the early-return above).
- case 'FAILED': return 'finished';
- default: return 'idle';
- }
- }
- /**
- * Get human-readable status display text for a printer.
- * Uses stg_cur_name for detailed calibration/preparation stages,
- * otherwise formats the gcode_state nicely.
- */
- function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
- // If we have a specific stage name (calibration, heating, etc.), use it
- if (stg_cur_name) {
- return stg_cur_name;
- }
- // Format the gcode_state nicely
- switch (state) {
- case 'RUNNING':
- return 'Printing';
- case 'PAUSE':
- return 'Paused';
- case 'FINISH':
- return 'Finished';
- case 'FAILED':
- return 'Failed';
- case 'IDLE':
- return 'Idle';
- default:
- return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
- }
- }
- // Bambu models that ship with an enclosure chamber fan (firmware field
- // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
- // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
- // widget is hidden in fanItems instead of rendered greyed-out.
- const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
- 'X1C',
- 'X1',
- 'X1E',
- 'X2D',
- 'P1S',
- 'P2S',
- 'H2D',
- 'H2D Pro',
- 'H2C',
- 'H2S',
- ]);
- // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
- // dedicated chamber EXHAUST fan: it's its own control and stays the same
- // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
- // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
- // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
- // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
- const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
- 'P2S',
- 'X2D',
- ]);
- // Map SSDP model codes to display names
- function mapModelCode(ssdpModel: string | null): string {
- if (!ssdpModel) return '';
- const modelMap: Record<string, string> = {
- // H2 Series
- 'O1D': 'H2D',
- 'O1E': 'H2D Pro',
- 'O2D': 'H2D Pro',
- 'O1C': 'H2C',
- 'O1C2': 'H2C',
- 'O1S': 'H2S',
- // X1 Series
- 'BL-P001': 'X1C',
- 'BL-P002': 'X1',
- 'BL-P003': 'X1E',
- // X2 Series
- 'N6': 'X2D',
- // A2 Series
- 'N9': 'A2L',
- // P Series
- 'C11': 'P1S',
- 'C12': 'P1P',
- 'C13': 'P2S',
- // A1 Series
- 'N2S': 'A1',
- 'N1': 'A1 Mini',
- // Direct matches
- 'X1C': 'X1C',
- 'X1': 'X1',
- 'X1E': 'X1E',
- 'X2D': 'X2D',
- 'P1S': 'P1S',
- 'P1P': 'P1P',
- 'P2S': 'P2S',
- 'A1': 'A1',
- 'A1 Mini': 'A1 Mini',
- 'A2L': 'A2L',
- 'H2D': 'H2D',
- 'H2D Pro': 'H2D Pro',
- 'H2C': 'H2C',
- 'H2S': 'H2S',
- };
- return modelMap[ssdpModel] || ssdpModel;
- }
- // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
- // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
- // • User-defined friendly name (editable, protected by printers:update)
- // • AMS serial number
- // • AMS firmware version
- export function AmsNameHoverCard({
- ams,
- printerId,
- label,
- amsLabels,
- canEdit,
- onSaved,
- children,
- }: {
- ams: import('../api/client').AMSUnit;
- printerId: number;
- label: string; // auto-generated label, e.g. "AMS-A"
- amsLabels?: Record<number, string>;
- canEdit: boolean;
- onSaved: () => void;
- children: React.ReactNode;
- }) {
- const { t } = useTranslation();
- const [isVisible, setIsVisible] = useState(false);
- const [position, setPosition] = useState<'top' | 'bottom'>('top');
- const [editValue, setEditValue] = useState('');
- const [isSaving, setIsSaving] = useState(false);
- const [saveError, setSaveError] = useState<string | null>(null);
- const [isInputFocused, setIsInputFocused] = useState(false);
- const triggerRef = useRef<HTMLDivElement>(null);
- const cardRef = useRef<HTMLDivElement>(null);
- const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- useEffect(() => {
- if (isVisible) {
- setEditValue(amsLabels?.[ams.id] ?? '');
- setSaveError(null);
- requestAnimationFrame(() => {
- if (triggerRef.current && cardRef.current) {
- const rect = triggerRef.current.getBoundingClientRect();
- const spaceAbove = rect.top - 56;
- const spaceBelow = window.innerHeight - rect.bottom;
- setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
- }
- });
- }
- }, [isVisible, amsLabels, ams.id]);
- const handleMouseEnter = () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
- };
- const handleMouseLeave = () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- if (!isInputFocused) {
- timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
- }
- };
- useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
- const handleSave = async () => {
- if (!canEdit) return;
- setIsSaving(true);
- setSaveError(null);
- try {
- const trimmed = editValue.trim();
- if (trimmed) {
- await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
- } else {
- await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
- }
- onSaved();
- setIsVisible(false);
- } catch (err) {
- setSaveError(err instanceof Error ? err.message : String(err));
- } finally {
- setIsSaving(false);
- }
- };
- const handleClear = async () => {
- if (!canEdit) return;
- setIsSaving(true);
- setSaveError(null);
- try {
- await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
- onSaved();
- setIsVisible(false);
- } catch (err) {
- setSaveError(err instanceof Error ? err.message : String(err));
- } finally {
- setIsSaving(false);
- }
- };
- return (
- <div
- ref={triggerRef}
- className="relative inline-block"
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- >
- {children}
- {isVisible && (
- <div
- ref={cardRef}
- className={`
- absolute left-0 z-50
- ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
- animate-in fade-in-0 zoom-in-95 duration-150
- `}
- style={{ maxWidth: 'calc(100vw - 24px)' }}
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- >
- <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">
- {/* AMS auto-label */}
- <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
- {/* Serial number */}
- <div className="flex items-center justify-between gap-2">
- <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
- {t('printers.amsPopup.serialNumber')}
- </span>
- <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
- </div>
- {/* Firmware version */}
- <div className="flex items-center justify-between gap-2">
- <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
- {t('printers.amsPopup.firmwareVersion')}
- </span>
- <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
- </div>
- {/* Friendly name editor */}
- <div className="space-y-1">
- <div className="flex items-center gap-2">
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
- {t('printers.amsPopup.friendlyName')}
- </span>
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
- </div>
- <input
- type="text"
- value={editValue}
- onChange={(e) => canEdit && setEditValue(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && handleSave()}
- onFocus={() => setIsInputFocused(true)}
- onBlur={() => {
- setIsInputFocused(false);
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
- }}
- placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
- disabled={!canEdit}
- title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
- 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"
- maxLength={100}
- />
- {canEdit && (
- <div className="space-y-1">
- {saveError && (
- <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
- )}
- <div className="flex gap-1 justify-end">
- <button
- onClick={handleSave}
- disabled={isSaving}
- 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"
- >
- {t('printers.amsPopup.save')}
- </button>
- {amsLabels?.[ams.id] && (
- <button
- onClick={handleClear}
- disabled={isSaving}
- 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"
- >
- {t('printers.amsPopup.clear')}
- </button>
- )}
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- )}
- </div>
- );
- }
- // AMS drying presets from BambuStudio filament profiles (idle mode temps)
- // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
- const DRYING_PRESETS: Record<string, DryingPreset> = {
- 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
- 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
- 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
- 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
- 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
- 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
- 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
- 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
- };
- // How much the printer card's body type and icons grow at each card size
- // (#1848). S is the dense fleet view and M is the default, so both stay at
- // 1.0 and an existing install looks identical until the user picks L or XL --
- // the same control the request asked to have this follow.
- const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
- // The scaled sizes, handed to the card subtree as custom properties. Every
- // converted class names its old fixed value as the fallback, so anything that
- // renders outside a card root -- the portalled temperature popover -- keeps
- // exactly the size it has today.
- function buildCardScaleStyle(cardSize: number): React.CSSProperties {
- const scale = CARD_BODY_SCALE[cardSize] ?? 1;
- // Rounded to a tenth so the values stay readable in devtools.
- const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
- return {
- '--pc-t8': px(8),
- '--pc-t9': px(9),
- '--pc-t10': px(10),
- '--pc-t11': px(11),
- '--pc-i2': px(8),
- '--pc-i25': px(10),
- '--pc-i3': px(12),
- '--pc-i35': px(14),
- '--pc-i4': px(16),
- '--pc-i5': px(20),
- '--pc-i7': px(28),
- } as React.CSSProperties;
- }
- function PrinterCard({
- printer,
- hideIfDisconnected,
- maintenanceInfo,
- viewMode = 'expanded',
- cardSize = 2,
- amsThresholds,
- spoolmanEnabled = false,
- linkedSpools,
- spoolmanUrl,
- spoolmanSyncMode,
- onGetAssignment,
- onUnassignSpool,
- spoolmanSpools,
- spoolmanSlotAssignments,
- spoolmanLoading = false,
- onUnassignSpoolmanSpool,
- timeFormat = 'system',
- cameraViewMode = 'window',
- onOpenEmbeddedCamera,
- checkPrinterFirmware = true,
- dryingPresets = DRYING_PRESETS,
- requirePlateClear = false,
- selectionMode = false,
- isSelected = false,
- onToggleSelect,
- onOpenCompactCard,
- nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
- bedTempPresets = BED_TEMP_DEFAULTS,
- chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
- fanSpeedPresets = FAN_SPEED_DEFAULTS,
- aiDetectionEnabled = false,
- aiDetection,
- aiLastError = null,
- }: {
- printer: Printer;
- hideIfDisconnected?: boolean;
- maintenanceInfo?: PrinterMaintenanceInfo;
- viewMode?: ViewMode;
- cardSize?: number;
- amsThresholds?: {
- humidityGood: number;
- humidityFair: number;
- tempGood: number;
- tempFair: number;
- };
- spoolmanEnabled?: boolean;
- hasUnlinkedSpools?: boolean;
- linkedSpools?: Record<string, LinkedSpoolInfo>;
- spoolmanUrl?: string | null;
- spoolmanSyncMode?: string | null;
- spoolAssignments?: SpoolAssignment[];
- onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
- onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
- spoolmanSpools?: InventorySpool[];
- spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
- spoolmanLoading?: boolean;
- onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
- timeFormat?: 'system' | '12h' | '24h';
- cameraViewMode?: 'window' | 'embedded';
- onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
- checkPrinterFirmware?: boolean;
- dryingPresets?: Record<string, DryingPreset>;
- requirePlateClear?: boolean;
- selectionMode?: boolean;
- isSelected?: boolean;
- onToggleSelect?: (id: number) => void;
- onOpenCompactCard?: (id: number) => void;
- nozzleTempPresets?: readonly [number, number, number];
- bedTempPresets?: readonly [number, number, number];
- chamberTempPresets?: readonly [number, number, number];
- fanSpeedPresets?: readonly [number, number, number];
- aiDetectionEnabled?: boolean;
- aiDetection?: { class: string; frame_count: number; score: number };
- aiLastError?: string | null;
- }) {
- const { t } = useTranslation();
- const queryClient = useQueryClient();
- const navigate = useNavigate();
- const { showToast } = useToast();
- const { hasPermission } = useAuth();
- const [showMenu, setShowMenu] = useState(false);
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
- const [deleteArchives, setDeleteArchives] = useState(true);
- const [showEditModal, setShowEditModal] = useState(false);
- const [showFileManager, setShowFileManager] = useState(false);
- const [showMQTTDebug, setShowMQTTDebug] = useState(false);
- const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
- const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
- const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
- const [showHMSModal, setShowHMSModal] = useState(false);
- // #1546: AI failure detection modal — opens from the AI badge.
- const [showAiModal, setShowAiModal] = useState(false);
- // #1762: AMS Filament Backup status / control modal — opens from the badge.
- const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
- // External spool visibility (#1782) — browser-local, per printer. Read once
- // per card; the toggle that writes it is the only thing that changes it.
- const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
- isExternalSpoolHidden(printer.id),
- );
- const toggleExternalSpool = useCallback(() => {
- setExternalSpoolHidden((prev) => {
- const next = !prev;
- persistExternalSpoolHidden(printer.id, next);
- return next;
- });
- }, [printer.id]);
- const [showStopConfirm, setShowStopConfirm] = useState(false);
- const [showPauseConfirm, setShowPauseConfirm] = useState(false);
- const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
- const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
- const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
- const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
- const [bedJogStep, setBedJogStep] = useState<number>(10);
- const [showResumeConfirm, setShowResumeConfirm] = useState(false);
- const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
- const [showUploadForPrint, setShowUploadForPrint] = useState(false);
- const [showPrinterInfo, setShowPrinterInfo] = useState(false);
- const [showDiagnostic, setShowDiagnostic] = useState(false);
- const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
- const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
- // AMS drying popover state: which AMS unit has the popover open
- const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
- const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
- const [dryingFilament, setDryingFilament] = useState('PLA');
- const [dryingTemp, setDryingTemp] = useState(50);
- const [dryingDuration, setDryingDuration] = useState(4);
- const [dryingRotateTray, setDryingRotateTray] = useState(false);
- const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
- // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
- // an object rather than a bare id so restarting drying on the SAME unit produces
- // a new identity and rearms the timeout below.
- const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
- const [isDraggingFile, setIsDraggingFile] = useState(false);
- const [isDropUploading, setIsDropUploading] = useState(false);
- const printerActionsMenuRef = useRef<HTMLDivElement>(null);
- const dragCounterRef = useRef(0);
- const [amsHistoryModal, setAmsHistoryModal] = useState<{
- amsId: number;
- amsLabel: string;
- mode: 'humidity' | 'temperature';
- } | null>(null);
- const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
- initialKind: HeaterSensorKind;
- availableKinds: HeaterSensorKind[];
- } | null>(null);
- const [linkSpoolModal, setLinkSpoolModal] = useState<{
- tagUid: string;
- trayUuid: string;
- printerId: number;
- amsId: number;
- trayId: number;
- } | null>(null);
- const [assignSpoolModal, setAssignSpoolModal] = useState<{
- printerId: number;
- amsId: number;
- trayId: number;
- trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
- } | null>(null);
- const [configureSlotModal, setConfigureSlotModal] = useState<{
- amsId: number;
- trayId: number;
- trayCount: number;
- trayType?: string;
- trayColor?: string;
- traySubBrands?: string;
- trayInfoIdx?: string;
- extruderId?: number;
- caliIdx?: number | null;
- savedPresetId?: string;
- } | null>(null);
- const [showFirmwareModal, setShowFirmwareModal] = useState(false);
- const [plateCheckResult, setPlateCheckResult] = useState<{
- is_empty: boolean;
- confidence: number;
- difference_percent: number;
- message: string;
- debug_image_url?: string;
- needs_calibration: boolean;
- light_warning?: boolean;
- reference_count?: number;
- max_references?: number;
- roi?: { x: number; y: number; w: number; h: number };
- } | null>(null);
- const [isCheckingPlate, setIsCheckingPlate] = useState(false);
- const [isCalibrating, setIsCalibrating] = useState(false);
- const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
- const [isSavingRoi, setIsSavingRoi] = useState(false);
- const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
- const { data: status } = useQuery({
- queryKey: ['printerStatus', printer.id],
- queryFn: () => api.getPrinterStatus(printer.id),
- refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
- });
- // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
- const { data: firmwareInfo } = useQuery({
- queryKey: ['firmwareUpdate', printer.id],
- queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
- staleTime: 5 * 60 * 1000,
- refetchInterval: 5 * 60 * 1000,
- enabled: checkPrinterFirmware && hasPermission('firmware:read'),
- });
- // Collect unique tray_info_idx values for cloud filament info lookup
- const trayInfoIds = useMemo(() => {
- const ids = new Set<string>();
- if (status?.ams) {
- for (const ams of status.ams) {
- for (const tray of ams.tray || []) {
- if (tray.tray_info_idx) {
- ids.add(tray.tray_info_idx);
- }
- }
- }
- }
- for (const vt of status?.vt_tray ?? []) {
- if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
- }
- if (status?.nozzle_rack) {
- for (const slot of status.nozzle_rack) {
- if (slot.filament_id) {
- ids.add(slot.filament_id);
- }
- }
- }
- return Array.from(ids);
- }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
- // Collect loaded filament types for queue widget filtering
- const loadedFilamentTypes = useMemo(() => {
- const types = new Set<string>();
- if (status?.ams) {
- for (const ams of status.ams) {
- for (const tray of ams.tray || []) {
- if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
- }
- }
- }
- for (const vt of status?.vt_tray ?? []) {
- if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
- }
- return types;
- }, [status?.ams, status?.vt_tray]);
- // Collect loaded filament type+color pairs for queue widget override matching
- // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
- const loadedFilaments = useMemo(() => {
- const filaments = new Set<string>();
- if (status?.ams) {
- for (const ams of status.ams) {
- for (const tray of ams.tray || []) {
- if (tray.tray_type && tray.tray_color) {
- const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
- filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
- }
- }
- }
- }
- for (const vt of status?.vt_tray ?? []) {
- if (vt.tray_type && vt.tray_color) {
- const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
- filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
- }
- }
- return filaments;
- }, [status?.ams, status?.vt_tray]);
- // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
- // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
- // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
- const loadedVariants = useMemo(() => {
- const variants = new Set<string>();
- if (status?.ams) {
- for (const ams of status.ams) {
- for (const tray of ams.tray || []) {
- if (tray.tray_type && tray.tray_color) {
- const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
- variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
- }
- }
- }
- }
- for (const vt of status?.vt_tray ?? []) {
- if (vt.tray_type && vt.tray_color) {
- const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
- variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
- }
- }
- return variants;
- }, [status?.ams, status?.vt_tray]);
- // Fetch cloud filament info for tooltips (name includes color, also has K value)
- const { data: filamentInfo } = useQuery({
- queryKey: ['filamentInfo', trayInfoIds],
- queryFn: () => api.getFilamentInfo(trayInfoIds),
- enabled: trayInfoIds.length > 0,
- staleTime: 5 * 60 * 1000, // 5 minutes
- });
- // Fetch slot preset mappings (stores preset name for user-configured slots)
- const { data: slotPresets } = useQuery({
- queryKey: ['slotPresets', printer.id],
- queryFn: () => api.getSlotPresets(printer.id),
- staleTime: 2 * 60 * 1000, // 2 minutes
- });
- // Fetch plate list for the archive linked to the active print (#881 follow-up).
- // Only queried when there's a running print backed by an archive; shared
- // React Query cache with the Queue / Archives pages keeps it cheap.
- const activeArchiveId =
- (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
- const { data: activeArchivePlates } = useQuery({
- queryKey: ['archive-plates', activeArchiveId],
- queryFn: () => api.getArchivePlates(activeArchiveId!),
- enabled: activeArchiveId != null,
- staleTime: 5 * 60 * 1000,
- });
- const activePlateLabel = (() => {
- if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
- const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
- return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
- })();
- // Fetch user-defined AMS friendly names from the database
- const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
- queryKey: ['amsLabels', printer.id],
- queryFn: () => api.getAmsLabels(printer.id),
- staleTime: 5 * 60 * 1000, // 5 minutes
- });
- // Cache WiFi signal to prevent it disappearing on updates
- const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
- useEffect(() => {
- if (status?.wifi_signal != null) {
- setCachedWifiSignal(status.wifi_signal);
- }
- }, [status?.wifi_signal]);
- const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
- // Cache connected state to prevent flicker when status briefly becomes undefined
- const cachedConnected = useRef<boolean | undefined>(undefined);
- useEffect(() => {
- if (status?.connected !== undefined) {
- cachedConnected.current = status.connected;
- }
- }, [status?.connected]);
- const isConnected = status?.connected ?? cachedConnected.current;
- // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
- const cachedAmsExtruderMap = useRef<Record<string, number>>({});
- useEffect(() => {
- if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
- cachedAmsExtruderMap.current = status.ams_extruder_map;
- }
- }, [status?.ams_extruder_map]);
- const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
- ? status.ams_extruder_map
- : cachedAmsExtruderMap.current;
- // Cache AMS data to prevent it disappearing on idle/offline printers
- const cachedAmsData = useRef<AMSUnit[]>([]);
- useEffect(() => {
- if (status?.ams && status.ams.length > 0) {
- cachedAmsData.current = status.ams;
- }
- }, [status?.ams]);
- const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
- // Confirm a drying cycle actually started (#2533). Firmware answers
- // ams_filament_drying with result=success even when it then silently declines,
- // and P1-family firmware never publishes dry_sf_reason — so the server-side
- // reason guard is blind there and the card just sits unchanged. Watch the unit
- // after the ack: leaving DryStatus 0 means the cycle is live, staying there
- // means the printer took the command and dropped it.
- useEffect(() => {
- if (!dryStartWatch) return;
- const unit = amsData.find(a => a.id === dryStartWatch.amsId);
- if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
- }, [dryStartWatch, amsData]);
- // Deps deliberately exclude amsData: status pushes arrive continuously and would
- // otherwise rearm the timeout on every frame, so it would never elapse.
- useEffect(() => {
- if (!dryStartWatch) return;
- const timer = setTimeout(() => {
- setDryStartWatch(null);
- showToast(t('printers.drying.toastNotStarted'), 'error');
- }, DRY_START_CONFIRM_MS);
- return () => clearTimeout(timer);
- }, [dryStartWatch, showToast, t]);
- // Cache tray_now to prevent flickering when undefined values come in
- // Valid tray IDs: 0-253 for AMS, 254 for external spool
- // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
- const cachedTrayNow = useRef<number | undefined>(undefined);
- const currentTrayNow = status?.tray_now;
- // Update cache: 255 means "no tray" so clear cache; valid values get cached
- if (currentTrayNow !== undefined && currentTrayNow !== 255) {
- cachedTrayNow.current = currentTrayNow;
- } else if (currentTrayNow === 255) {
- cachedTrayNow.current = undefined;
- }
- const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
- ? currentTrayNow
- : cachedTrayNow.current;
- // Runout / filament-replacement guidance (#2587). The backend fills these only
- // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
- // expectedTray = the slot the firmware now expects filament in
- // previousTray = the slot that ran out
- // With AMS Filament Backup the firmware advances to the next compatible slot,
- // so these are often different — the graphic highlights the expected one.
- const expectedTray = status?.expected_tray ?? null;
- const previousTray = status?.previous_tray ?? null;
- // Pre-format the runout slot labels (honoring user AMS friendly names) for the
- // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
- const formatRunoutSlotLabel = (globalId: number | null): string | null => {
- if (globalId === null) return null;
- if (globalId === 254) return t('printers.expectedSlot.external');
- if (globalId >= 128 && globalId <= 135) {
- return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
- }
- const amsId = Math.floor(globalId / 4);
- const slot = globalId % 4;
- const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
- return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
- };
- const runoutGuidance = status?.state === 'PAUSE'
- ? {
- expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
- ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
- }
- : null;
- // Fetch smart plug for this printer
- const { data: smartPlug } = useQuery({
- queryKey: ['smartPlugByPrinter', printer.id],
- queryFn: () => api.getSmartPlugByPrinter(printer.id),
- });
- // Fetch script plugs for this printer (for multi-device control)
- const { data: scriptPlugs } = useQuery({
- queryKey: ['scriptPlugsByPrinter', printer.id],
- queryFn: () => api.getScriptPlugsByPrinter(printer.id),
- });
- // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
- const { data: plugStatus } = useQuery({
- queryKey: ['smartPlugStatus', smartPlug?.id],
- queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
- enabled: !!smartPlug,
- refetchInterval: 10000, // 10 seconds for real-time power display
- });
- // Fetch queue count for this printer
- const { data: queueItems } = useQuery({
- queryKey: ['queue', printer.id, 'pending'],
- queryFn: () => api.getQueue(printer.id, 'pending'),
- });
- // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
- // so the badge only shows on printers that can actually run the queued jobs.
- // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
- const queueCount = useMemo(() => {
- if (!queueItems?.length) return 0;
- return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
- }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
- // Fetch currently printing queue item to show who started it (Issue #206)
- const { data: printingQueueItems } = useQuery({
- queryKey: ['queue', printer.id, 'printing'],
- queryFn: () => api.getQueue(printer.id, 'printing'),
- enabled: status?.state === 'RUNNING',
- });
- // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
- const { data: reprintUser } = useQuery({
- queryKey: ['currentPrintUser', printer.id],
- queryFn: () => api.getCurrentPrintUser(printer.id),
- enabled: status?.state === 'RUNNING',
- });
- // Combine both sources: queue item user takes precedence, then reprint user
- const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
- // Fetch last completed print for this printer
- const { data: lastPrints } = useQuery({
- queryKey: ['archives', printer.id, 'last'],
- queryFn: () => api.getArchives(printer.id, 1, 0),
- enabled: status?.connected && status?.state !== 'RUNNING',
- });
- const lastPrint = lastPrints?.[0];
- const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
- const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
- const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
- const activePrintName = status?.current_print && isPrintingOrPaused
- ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
- : null;
- const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
- useEffect(() => {
- if (activePrintName) {
- setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
- } else if (!needsPlateClear) {
- setRetainedPrintJob(null);
- }
- }, [activePrintName, needsPlateClear, status?.cover_url]);
- const plateStatus = (() => {
- if (!requirePlateClear || !status?.connected) return null;
- if (isPrintingOrPaused) {
- return {
- label: t('printers.plateStatus.inUse'),
- className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
- };
- }
- if (status.awaiting_plate_clear) {
- return {
- label: t('printers.plateStatus.notCleared'),
- className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
- };
- }
- return {
- label: t('printers.plateStatus.cleared'),
- className: 'bg-status-ok/20 text-status-ok',
- };
- })();
- const plateStatusPill = plateStatus ? (
- <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}`}>
- {plateStatus.label}
- </span>
- ) : null;
- // Determine if this card should be hidden (use cached connected state to prevent flicker)
- const shouldHide = hideIfDisconnected && isConnected === false;
- const deleteMutation = useMutation({
- mutationFn: (options: { deleteArchives: boolean }) =>
- api.deletePrinter(printer.id, options.deleteArchives),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['printers'] });
- queryClient.invalidateQueries({ queryKey: ['archives'] });
- queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
- });
- const connectMutation = useMutation({
- mutationFn: () => api.connectPrinter(printer.id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- });
- const forceRefreshMutation = useMutation({
- mutationFn: () => api.refreshPrinterStatus(printer.id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- showToast(t('printers.forceRefreshSuccess'), 'success');
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const unlinkSpoolMutation = useMutation({
- mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
- onSuccess: (result) => {
- showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
- queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
- queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
- queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
- },
- onError: (error: Error) => {
- showToast(error.message || t('spoolman.unlinkFailed'), 'error');
- },
- });
- // AMS drying mutations
- const startDryingMutation = useMutation({
- mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
- api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
- onSuccess: (_data, { amsId }) => {
- setDryingPopoverAmsId(null);
- setDryStartWatch({ amsId });
- // "Command sent", not "drying started" — at this point the printer has only
- // taken the command. The amber countdown badge (dry_time > 0) is what says
- // the cycle is genuinely live; the watcher below covers the case where it
- // never appears.
- showToast(t('printers.drying.toastCommandSent'), 'success');
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const stopDryingMutation = useMutation({
- mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
- onSuccess: () => {
- setDryStartWatch(null);
- showToast(t('printers.drying.toastStopped'), 'success');
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
- // Invalidate BOTH printer-status cache keys — the codebase has two conventions
- // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
- // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
- // showing the old backup state until the user reopens it.
- const setAmsBackupMutation = useMutation({
- mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
- onSuccess: (_data, enabled) => {
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
- showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- // Smart plug control mutations
- const powerControlMutation = useMutation({
- mutationFn: (action: 'on' | 'off') =>
- smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
- },
- });
- const toggleAutoOffMutation = useMutation({
- mutationFn: (enabled: boolean) =>
- smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
- // Also invalidate the smart-plugs list to keep Settings page in sync
- queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
- },
- });
- // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
- const runScriptMutation = useMutation({
- mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
- onSuccess: () => {
- showToast(t('printers.toast.scriptTriggered'));
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
- });
- // Print control mutations
- const stopPrintMutation = useMutation({
- mutationFn: () => api.stopPrint(printer.id),
- onSuccess: () => {
- showToast(t('printers.toast.printStopped'));
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
- });
- const pausePrintMutation = useMutation({
- mutationFn: () => api.pausePrint(printer.id),
- onSuccess: () => {
- showToast(t('printers.toast.printPaused'));
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
- });
- const resumePrintMutation = useMutation({
- mutationFn: () => api.resumePrint(printer.id),
- onSuccess: () => {
- showToast(t('printers.toast.printResumed'));
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
- });
- const clearPlateMutation = useMutation({
- mutationFn: () => api.clearPlate(printer.id),
- onSuccess: () => {
- showToast(t('queue.clearPlateSuccess'));
- queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
- old ? { ...old, awaiting_plate_clear: false } : old
- );
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const nozzleTemperatureMutation = useMutation({
- mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
- api.setNozzleTemperature(printer.id, target, nozzle),
- onSuccess: (result) => {
- setStatusControlMenu(null);
- showToast(result.message);
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const bedTemperatureMutation = useMutation({
- mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
- onSuccess: (result) => {
- setStatusControlMenu(null);
- showToast(result.message);
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const chamberTemperatureMutation = useMutation({
- mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
- onSuccess: (result) => {
- setStatusControlMenu(null);
- showToast(result.message);
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const fanSpeedMutation = useMutation({
- mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
- api.setFanSpeed(printer.id, fan, speed),
- onMutate: async ({ fan, speed }) => {
- await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
- const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
- const fanField = {
- part: 'cooling_fan_speed',
- aux: 'big_fan1_speed',
- aux2: 'left_aux_fan_speed',
- chamber: 'big_fan2_speed',
- }[fan];
- queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
- old ? { ...old, [fanField]: speed } : old
- );
- return { previousStatus };
- },
- onSuccess: (result) => {
- setStatusControlMenu(null);
- showToast(result.message);
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error, _variables, context) => {
- if (context?.previousStatus) {
- queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
- }
- showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
- },
- });
- const selectExtruderMutation = useMutation({
- mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
- onMutate: async (extruder) => {
- await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
- const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
- queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
- old ? { ...old, active_extruder: extruder } : old
- );
- return { previousStatus };
- },
- onSuccess: (result) => {
- setStatusControlMenu(null);
- showToast(result.message);
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- },
- onError: (error: Error, _extruder, context) => {
- if (context?.previousStatus) {
- queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
- }
- showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
- },
- });
- // Chamber light mutation with optimistic update
- const chamberLightMutation = useMutation({
- mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
- onMutate: async (on) => {
- // Cancel any outgoing refetches
- await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
- // Snapshot the previous value
- const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
- // Optimistically update
- queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
- ...old,
- chamber_light: on,
- }));
- return { previousStatus };
- },
- onSuccess: (_, on) => {
- showToast(`Chamber light ${on ? 'on' : 'off'}`);
- },
- onError: (error: Error, _, context) => {
- // Rollback on error
- if (context?.previousStatus) {
- queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
- }
- showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
- },
- });
- // Print speed mutation with optimistic update
- const printSpeedMutation = useMutation({
- mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
- onMutate: async (mode) => {
- await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
- const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
- queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
- ...old,
- speed_level: mode,
- }));
- return { previousStatus };
- },
- onError: (error: Error, _, context) => {
- if (context?.previousStatus) {
- queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
- }
- showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
- },
- });
- const airductMutation = useMutation({
- mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
- onMutate: async (mode) => {
- await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
- const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
- queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
- ...old,
- airduct_mode: mode === 'cooling' ? 0 : 1,
- }));
- return { previousStatus };
- },
- onError: (error: Error, _, context) => {
- if (context?.previousStatus) {
- queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
- }
- showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
- },
- });
- const bedJogMutation = useMutation({
- mutationFn: ({ distance }: { distance: number }) =>
- api.bedJog(printer.id, distance),
- onError: (error: Error) =>
- showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const xyJogMutation = useMutation({
- mutationFn: ({ x, y }: { x: number; y: number }) =>
- api.xyJog(printer.id, x, y),
- onError: (error: Error) =>
- showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const extruderJogMutation = useMutation({
- mutationFn: (distance: number) =>
- api.extruderJog(printer.id, distance),
- onError: (error: Error) =>
- showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- const homeAxesMutation = useMutation({
- mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
- onSuccess: () => {
- showToast(t('printers.bedJog.homingStarted'));
- },
- onError: (error: Error) =>
- showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
- });
- // Plate detection setting mutation
- const plateDetectionMutation = useMutation({
- mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['printers'] });
- showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
- });
- // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
- // already gates MQTT connection, queue dispatch, scheduler eligibility,
- // metrics, and the print picker — so flipping this flag puts the printer
- // out of service across every consumer in one place. Used from the
- // overflow menu and EditPrinterModal.
- const maintenanceMutation = useMutation({
- mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
- onSuccess: (_data, isActive) => {
- queryClient.invalidateQueries({ queryKey: ['printers'] });
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- showToast(
- isActive
- ? t('printers.maintenance.toastExited', { name: printer.name })
- : t('printers.maintenance.toastEntered', { name: printer.name }),
- 'success',
- );
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
- });
- // Confirm before entering maintenance on a printing printer (entering mode
- // disconnects MQTT, which stops progress tracking + completion notifications
- // for the in-flight job).
- const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
- const handleEnterMaintenance = () => {
- if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
- setConfirmMaintenanceEnter(true);
- } else {
- maintenanceMutation.mutate(false);
- }
- };
- // Query for printable objects (for skip functionality)
- // Fetch when printing with 2+ objects OR when modal is open
- const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
- const { data: objectsData } = useQuery({
- queryKey: ['printableObjects', printer.id],
- queryFn: () => api.getPrintableObjects(printer.id),
- enabled: showSkipObjectsModal || isPrintingWithObjects,
- refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
- });
- // State for tracking which AMS slot is being refreshed
- const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
- // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
- const seenBusyStateRef = useRef<boolean>(false);
- // Fallback timeout ref
- const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- // Minimum display time passed
- const minTimePassedRef = useRef<boolean>(false);
- // AMS slot refresh mutation
- const refreshAmsSlotMutation = useMutation({
- mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
- api.refreshAmsSlot(printer.id, amsId, slotId),
- onMutate: ({ amsId, slotId }) => {
- // Clear any existing timeout
- if (refreshTimeoutRef.current) {
- clearTimeout(refreshTimeoutRef.current);
- }
- // Reset state
- seenBusyStateRef.current = false;
- minTimePassedRef.current = false;
- setRefreshingSlot({ amsId, slotId });
- // Minimum display time (2 seconds)
- setTimeout(() => {
- minTimePassedRef.current = true;
- }, 2000);
- // Fallback timeout (30 seconds max)
- refreshTimeoutRef.current = setTimeout(() => {
- setRefreshingSlot(null);
- }, 30000);
- },
- onSuccess: (data) => {
- showToast(data.message || t('printers.toast.rfidRereadInitiated'));
- },
- onError: (error: Error) => {
- showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
- if (refreshTimeoutRef.current) {
- clearTimeout(refreshTimeoutRef.current);
- }
- setRefreshingSlot(null);
- },
- });
- // AMS load/unload mutations (#891)
- const loadAmsTrayMutation = useMutation({
- mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
- onSuccess: (data) => {
- showToast(data.message || t('printers.toast.loadInitiated'));
- },
- onError: (error: Error) => {
- showToast(error.message || t('printers.toast.failedToLoad'), 'error');
- },
- });
- const unloadAmsMutation = useMutation({
- mutationFn: () => api.unloadAms(printer.id),
- onSuccess: (data) => {
- showToast(data.message || t('printers.toast.unloadInitiated'));
- },
- onError: (error: Error) => {
- showToast(error.message || t('printers.toast.failedToUnload'), 'error');
- },
- });
- // Plate references state
- const [plateReferences, setPlateReferences] = useState<{
- references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
- max_references: number;
- } | null>(null);
- const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
- // Fetch plate references
- const fetchPlateReferences = async () => {
- try {
- const data = await api.getPlateReferences(printer.id);
- setPlateReferences(data);
- } catch {
- // Ignore errors - references will show as empty
- }
- };
- // Toggle plate detection enabled/disabled
- const handleTogglePlateDetection = () => {
- plateDetectionMutation.mutate(!printer.plate_detection_enabled);
- };
- // Open plate detection management modal (for calibration/references)
- const handleOpenPlateManagement = async () => {
- setIsCheckingPlate(true);
- setPlateCheckResult(null);
- // Auto-turn on light if it's off
- const lightWasOff = status?.chamber_light === false;
- setPlateCheckLightWasOff(lightWasOff);
- if (lightWasOff) {
- await api.setChamberLight(printer.id, true);
- // Wait for light to physically turn on and camera to adjust exposure
- // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
- await new Promise(resolve => setTimeout(resolve, 2500));
- }
- try {
- const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
- setPlateCheckResult(result);
- fetchPlateReferences();
- } catch (error) {
- showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
- // Restore light if check failed
- if (lightWasOff) {
- await api.setChamberLight(printer.id, false);
- setPlateCheckLightWasOff(false);
- }
- } finally {
- setIsCheckingPlate(false);
- }
- };
- // Close plate check modal and restore light state
- const closePlateCheckModal = useCallback(async () => {
- setPlateCheckResult(null);
- // Restore light to original state if we turned it on
- if (plateCheckLightWasOff) {
- await api.setChamberLight(printer.id, false);
- setPlateCheckLightWasOff(false);
- }
- }, [plateCheckLightWasOff, printer.id]);
- // Calibrate plate detection handler
- const handleCalibratePlate = async (label?: string) => {
- setIsCalibrating(true);
- try {
- const result = await api.calibratePlateDetection(printer.id, { label });
- if (result.success) {
- showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
- // Refresh references and re-check
- fetchPlateReferences();
- const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
- setPlateCheckResult(checkResult);
- } else {
- showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
- }
- } catch (error) {
- showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
- } finally {
- setIsCalibrating(false);
- }
- };
- // Update reference label
- const handleUpdateRefLabel = async (index: number, label: string) => {
- try {
- await api.updatePlateReferenceLabel(printer.id, index, label);
- setEditingRefLabel(null);
- fetchPlateReferences();
- } catch (error) {
- showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
- }
- };
- // Delete reference
- const handleDeleteRef = async (index: number) => {
- try {
- await api.deletePlateReference(printer.id, index);
- showToast(t('printers.toast.referenceDeleted'), 'success');
- fetchPlateReferences();
- // Re-check to update counts
- const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
- setPlateCheckResult(checkResult);
- } catch (error) {
- showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
- }
- };
- // Save ROI settings
- const handleSaveRoi = async () => {
- if (!editingRoi) return;
- setIsSavingRoi(true);
- try {
- await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
- showToast(t('printers.toast.detectionAreaSaved'), 'success');
- setEditingRoi(null);
- // Re-check to see new ROI in action
- const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
- setPlateCheckResult(checkResult);
- } catch (error) {
- showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
- } finally {
- setIsSavingRoi(false);
- }
- };
- // Close plate check modal on Escape key
- useEffect(() => {
- const handleEscape = (e: KeyboardEvent) => {
- if (e.key === 'Escape' && plateCheckResult) {
- closePlateCheckModal();
- }
- };
- window.addEventListener('keydown', handleEscape);
- return () => window.removeEventListener('keydown', handleEscape);
- }, [plateCheckResult, closePlateCheckModal]);
- // Watch ams_status_main to detect when RFID read completes
- // ams_status_main: 0=idle, 2=rfid_identifying
- const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- useEffect(() => {
- if (!refreshingSlot) return;
- const amsStatus = status?.ams_status_main ?? 0;
- // Track when we see non-idle state (printer is working)
- if (amsStatus !== 0) {
- seenBusyStateRef.current = true;
- // Cancel any deferred clear since we're back to busy
- if (deferredClearRef.current) {
- clearTimeout(deferredClearRef.current);
- deferredClearRef.current = null;
- }
- }
- // When we've seen busy and now idle, clear (with min time check)
- if (seenBusyStateRef.current && amsStatus === 0) {
- if (minTimePassedRef.current) {
- // Min time passed - clear now
- if (refreshTimeoutRef.current) {
- clearTimeout(refreshTimeoutRef.current);
- }
- setRefreshingSlot(null);
- } else {
- // Schedule clear after min time (2 seconds from start)
- if (!deferredClearRef.current) {
- deferredClearRef.current = setTimeout(() => {
- if (refreshTimeoutRef.current) {
- clearTimeout(refreshTimeoutRef.current);
- }
- setRefreshingSlot(null);
- }, 2000);
- }
- }
- }
- return () => {
- if (deferredClearRef.current) {
- clearTimeout(deferredClearRef.current);
- }
- };
- }, [status?.ams_status_main, refreshingSlot]);
- useEffect(() => {
- if (!showMenu) return;
- const handleClickOutside = (event: MouseEvent) => {
- const target = event.target as Node;
- if (!printerActionsMenuRef.current?.contains(target)) {
- setShowMenu(false);
- }
- };
- document.addEventListener('mousedown', handleClickOutside);
- return () => document.removeEventListener('mousedown', handleClickOutside);
- }, [showMenu]);
- if (shouldHide) {
- return null;
- }
- // Size-based styling helpers
- // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
- // width, its thumbnail and the printer name, but every label inside the
- // body was pinned at 8-11px, so an XL card showed the same tiny text as an
- // S one -- the disparity was worst exactly where someone asking for more
- // room ends up. These custom properties carry the scaled sizes into the
- // card's subtree. S and M are deliberately 1.0: nobody's card changes
- // unless they reach for a size that is already asking for more space.
- // Plain computation rather than useMemo: this sits after the card's early
- // returns, where a hook would break the rules-of-hooks ordering, and
- // building ten strings per render costs nothing.
- const cardScaleStyle = buildCardScaleStyle(cardSize);
- const getImageSize = () => {
- switch (cardSize) {
- case 1: return 'w-10 h-10';
- case 2: return 'w-14 h-14';
- case 3: return 'w-16 h-16';
- case 4: return 'w-20 h-20';
- default: return 'w-14 h-14';
- }
- };
- const getTitleSize = () => {
- switch (cardSize) {
- case 1: return 'text-base truncate';
- case 2: return 'text-lg';
- case 3: return 'text-xl';
- case 4: return 'text-2xl';
- default: return 'text-lg';
- }
- };
- const getSpacing = () => {
- switch (cardSize) {
- case 1: return 'mb-2';
- case 2: return 'mb-4';
- case 3: return 'mb-5';
- case 4: return 'mb-6';
- default: return 'mb-4';
- }
- };
- const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
- const handleCardDragEnter = (e: React.DragEvent) => {
- e.preventDefault();
- dragCounterRef.current++;
- if (dragCounterRef.current === 1) setIsDraggingFile(true);
- };
- const handleCardDragOver = (e: React.DragEvent) => {
- e.preventDefault();
- e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
- };
- const handleCardDragLeave = (e: React.DragEvent) => {
- e.preventDefault();
- dragCounterRef.current--;
- if (dragCounterRef.current === 0) setIsDraggingFile(false);
- };
- const handleCardDrop = async (e: React.DragEvent) => {
- e.preventDefault();
- dragCounterRef.current = 0;
- setIsDraggingFile(false);
- if (!canDrop) return;
- const droppedFiles = Array.from(e.dataTransfer.files);
- const file = droppedFiles[0];
- if (!file) return;
- // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
- const lower = file.name.toLowerCase();
- if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
- showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
- return;
- }
- setIsDropUploading(true);
- try {
- const result = await api.uploadLibraryFile(file, null);
- // Check printer compatibility if sliced_for_model is available in metadata
- const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
- const printerModel = mapModelCode(printer.model);
- if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
- await api.deleteLibraryFile(result.id).catch(() => {});
- showToast(
- t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
- 'error'
- );
- return;
- }
- setPrintAfterUpload({ id: result.id, filename: result.filename });
- } catch {
- showToast(t('common.uploadFailed', 'Upload failed'), 'error');
- } finally {
- setIsDropUploading(false);
- }
- };
- const handleCardClick = (e: React.MouseEvent) => {
- if (viewMode !== 'compact' || selectionMode) return;
- const target = e.target as HTMLElement;
- if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
- onOpenCompactCard?.(printer.id);
- };
- const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
- const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
- const renderAmsSlotActions = ({
- amsId,
- slotId,
- loadTrayId,
- isRefreshing,
- includeRfid = true,
- }: {
- amsId: number;
- slotId: number;
- loadTrayId: number;
- isRefreshing?: boolean;
- includeRfid?: boolean;
- }) => {
- const printerBusy = status?.state === 'RUNNING';
- return (
- <>
- {includeRfid && (
- <button
- className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
- hasPermission('printers:ams_rfid')
- ? 'text-white hover:bg-bambu-dark-tertiary'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- onClick={(e) => {
- e.stopPropagation();
- if (printerBusy || !hasPermission('printers:ams_rfid')) return;
- refreshAmsSlotMutation.mutate({ amsId, slotId });
- }}
- disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
- title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
- >
- <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
- {t('printers.rfid.reread')}
- </button>
- )}
- <button
- className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
- hasPermission('printers:control')
- ? 'text-white hover:bg-bambu-dark-tertiary'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- onClick={(e) => {
- e.stopPropagation();
- if (printerBusy || !hasPermission('printers:control')) return;
- loadAmsTrayMutation.mutate({ trayId: loadTrayId });
- }}
- disabled={printerBusy || !hasPermission('printers:control')}
- title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
- >
- <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {t('printers.ams.load')}
- </button>
- <button
- className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
- hasPermission('printers:control')
- ? 'text-white hover:bg-bambu-dark-tertiary'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- onClick={(e) => {
- e.stopPropagation();
- if (printerBusy || !hasPermission('printers:control')) return;
- unloadAmsMutation.mutate();
- }}
- disabled={printerBusy || !hasPermission('printers:control')}
- title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
- >
- <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {t('printers.ams.unload')}
- </button>
- </>
- );
- };
- const printerActionsMenu = (
- <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowMenu(!showMenu)}
- title={t('common.more', 'More')}
- className={footerIconButtonClass}
- >
- <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </Button>
- {showMenu && (
- <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">
- <button
- className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
- hasPermission('printers:update')
- ? 'hover:bg-bambu-dark-tertiary'
- : 'opacity-50 cursor-not-allowed'
- }`}
- onClick={() => {
- if (!hasPermission('printers:update')) return;
- setShowEditModal(true);
- setShowMenu(false);
- }}
- title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
- >
- <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {t('common.edit')}
- </button>
- <button
- className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
- onClick={() => {
- setShowPrinterInfo(true);
- setShowMenu(false);
- }}
- >
- <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {t('printers.printerInformation')}
- </button>
- {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
- <button
- className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
- hasPermission('printers:update')
- ? 'hover:bg-bambu-dark-tertiary'
- : 'opacity-50 cursor-not-allowed'
- }`}
- disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
- onClick={() => {
- if (!hasPermission('printers:update')) return;
- setShowMenu(false);
- if (printer.is_active !== false) {
- handleEnterMaintenance();
- } else {
- maintenanceMutation.mutate(true);
- }
- }}
- title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
- >
- <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {printer.is_active !== false
- ? t('printers.maintenance.menuEnter')
- : t('printers.maintenance.menuExit')}
- </button>
- <button
- className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
- onClick={() => {
- connectMutation.mutate();
- setShowMenu(false);
- }}
- >
- <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {t('printers.reconnect')}
- </button>
- <button
- className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
- disabled={forceRefreshMutation.isPending}
- onClick={() => {
- forceRefreshMutation.mutate();
- setShowMenu(false);
- }}
- >
- <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
- {t('printers.forceRefresh')}
- </button>
- <button
- className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
- onClick={() => {
- setShowMQTTDebug(true);
- setShowMenu(false);
- }}
- >
- <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {t('printers.mqttDebug')}
- </button>
- <button
- className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
- onClick={() => {
- setShowDiagnostic(true);
- setShowMenu(false);
- }}
- >
- <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {t('diagnostic.runButton')}
- </button>
- <button
- className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
- hasPermission('printers:delete')
- ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
- : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
- }`}
- onClick={() => {
- if (!hasPermission('printers:delete')) return;
- setShowDeleteConfirm(true);
- setShowMenu(false);
- }}
- title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
- >
- <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {t('common.delete')}
- </button>
- </div>
- )}
- </div>
- );
- return (
- <Card
- id={`printer-card-${printer.id}`}
- className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
- style={cardScaleStyle}
- onClick={handleCardClick}
- onDragEnter={handleCardDragEnter}
- onDragOver={handleCardDragOver}
- onDragLeave={handleCardDragLeave}
- onDrop={handleCardDrop}
- >
- {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
- {selectionMode && (
- <div
- className="absolute inset-0 z-20 flex items-start p-2"
- onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
- >
- {isSelected ? (
- <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
- ) : (
- <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
- )}
- </div>
- )}
- {/* Drop zone overlay */}
- {(isDraggingFile || isDropUploading) && (
- <div
- className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
- isDropUploading
- ? 'bg-bambu-green/10 border-bambu-green/50'
- : canDrop
- ? 'bg-bambu-green/10 border-bambu-green'
- : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
- }`}
- >
- <div className="text-center">
- {isDropUploading ? (
- <>
- <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
- <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
- </>
- ) : canDrop ? (
- <>
- <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
- <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
- </>
- ) : (
- <>
- <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
- <p className="text-sm font-medium text-red-700 dark:text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
- </>
- )}
- </div>
- </div>
- )}
- <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
- {/* Header */}
- <div className={getSpacing()}>
- {/* Top row: Image, Name, Menu */}
- <div className="flex items-start justify-between gap-2">
- <div className="flex items-center gap-3 min-w-0 flex-1">
- {/* Printer Model Image */}
- <img
- src={getPrinterImage(printer.model)}
- alt={printer.model || t('common.printer')}
- className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
- />
- <div className="min-w-0 flex-1">
- <div className="flex items-center justify-between gap-2">
- <div className="flex min-w-0 items-center gap-2">
- <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
- {/* Connection indicator dot for compact mode */}
- {viewMode === 'compact' && (() => {
- const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
- const hasSevere = hmsErrors.some(e => e.severity <= 2);
- const hasWarning = hmsErrors.length > 0;
- const pipColor = !status?.connected
- ? 'bg-status-error'
- : hasSevere
- ? 'bg-status-error'
- : hasWarning
- ? 'bg-status-warning'
- : 'bg-status-ok';
- const pipTitle = !status?.connected
- ? t('printers.connection.offline')
- : hasWarning
- ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
- : t('printers.connection.connected');
- return (
- <div
- className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
- title={pipTitle}
- />
- );
- })()}
- </div>
- {viewMode === 'compact' && showClearPlateButton && (
- <button
- type="button"
- onClick={() => clearPlateMutation.mutate()}
- disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
- aria-label={t('printers.plateStatus.markCleared')}
- 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"
- title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
- >
- {clearPlateMutation.isPending ? (
- <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
- ) : (
- <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- )}
- </button>
- )}
- </div>
- <p className="text-sm text-bambu-gray">
- {printer.model || 'Unknown Model'}
- {/* Nozzle Info - only in expanded */}
- {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
- <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
- • {status.nozzles[0].nozzle_diameter}mm
- </span>
- )}
- {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
- <span className="ml-2 text-bambu-gray">
- <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
- {Math.round(maintenanceInfo.total_print_hours)}h
- </span>
- )}
- </p>
- </div>
- </div>
- </div>
- {/* Badges row - only in expanded mode */}
- {viewMode === 'expanded' && (
- <div className="mt-2">
- <div className="flex flex-wrap items-center gap-2">
- {/* Connection status badge (or Maintenance pill when out of service).
- Defensive: only swap when is_active is EXPLICITLY false. An
- undefined / missing field defaults to "active" so the regular
- pill renders — matches the backend default and prevents test
- fixtures (or stale clients) from accidentally tripping the
- maintenance UI. */}
- {printer.is_active === false ? (
- <span
- 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"
- title={t('printers.maintenance.subtitle')}
- >
- <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {t('printers.maintenance.pillLabel')}
- </span>
- ) : (
- <span
- className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
- status?.connected
- ? 'bg-status-ok/20 text-status-ok'
- : 'bg-status-error/20 text-status-error'
- }`}
- >
- {status?.connected ? (
- <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- ) : (
- <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- )}
- {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
- </span>
- )}
- {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
- {printer.is_active !== false && !status?.connected && (
- <button
- onClick={() => setShowDiagnostic(true)}
- 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"
- title={t('diagnostic.runButton')}
- >
- <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {t('diagnostic.runButton')}
- </button>
- )}
- {/* Network connection indicator */}
- {status?.connected && status?.wired_network && (
- <span
- className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
- title={t('printers.connection.ethernet', 'Ethernet')}
- >
- <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {t('printers.connection.ethernet', 'Ethernet')}
- </span>
- )}
- {/* WiFi signal indicator */}
- {status?.connected && !status?.wired_network && wifiSignal != null && (
- <span
- className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
- wifiSignal >= -50
- ? 'bg-status-ok/20 text-status-ok'
- : wifiSignal >= -60
- ? 'bg-status-ok/20 text-status-ok'
- : wifiSignal >= -70
- ? 'bg-status-warning/20 text-status-warning'
- : wifiSignal >= -80
- ? 'bg-orange-500/20 text-orange-600'
- : 'bg-status-error/20 text-status-error'
- }`}
- title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
- >
- <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {wifiSignal}dBm
- </span>
- )}
- {/* HMS Status Indicator */}
- {status?.connected && (() => {
- const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
- return (
- <button
- onClick={() => setShowHMSModal(true)}
- className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
- knownErrors.length > 0
- ? knownErrors.some(e => e.severity <= 2)
- ? 'bg-status-error/20 text-status-error'
- : 'bg-status-warning/20 text-status-warning'
- : 'bg-status-ok/20 text-status-ok'
- }`}
- title={t('printers.clickToViewHmsErrors')}
- >
- <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {knownErrors.length > 0 ? knownErrors.length : 'OK'}
- </button>
- );
- })()}
- {/* AI failure detection badge (#1546) — always shown while detection
- is enabled for this printer, like the other health badges. Gray
- "Idle" outside a monitored print, class-colored during one. */}
- {aiDetectionEnabled && (() => {
- const cls = aiDetection
- ? (aiDetection.class === 'failure' || aiDetection.class === 'warning' ? aiDetection.class : 'safe')
- : 'idle';
- const colorClass =
- cls === 'failure'
- ? 'bg-status-error/20 text-status-error'
- : cls === 'warning'
- ? 'bg-status-warning/20 text-status-warning'
- : cls === 'safe'
- ? 'bg-status-ok/20 text-status-ok'
- : 'bg-bambu-dark-tertiary text-bambu-gray';
- return (
- <button
- onClick={() => setShowAiModal(true)}
- className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
- title={
- aiDetection
- ? t('printers.aiDetection.tooltip', {
- status: t(`printers.aiDetection.${cls}`),
- score: aiDetection.score.toFixed(3),
- })
- : t('printers.aiDetection.tooltipIdle')
- }
- >
- <ScanEye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {t(`printers.aiDetection.${cls}`)}
- </button>
- );
- })()}
- {/* Maintenance Status Indicator */}
- {maintenanceInfo && (
- <button
- onClick={() => navigate('/maintenance')}
- className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
- maintenanceInfo.due_count > 0
- ? 'bg-status-error/20 text-status-error'
- : maintenanceInfo.warning_count > 0
- ? 'bg-status-warning/20 text-status-warning'
- : 'bg-status-ok/20 text-status-ok'
- }`}
- title={
- maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
- ? `${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`
- : t('printers.maintenanceUpToDate')
- }
- >
- <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
- ? maintenanceInfo.due_count + maintenanceInfo.warning_count
- : 'OK'}
- </button>
- )}
- {/* Queue Count Badge */}
- {queueCount > 0 && (
- <button
- onClick={() => navigate('/queue')}
- 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"
- title={t('printers.queue.inQueue', { count: queueCount })}
- >
- <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {queueCount}
- </button>
- )}
- {/* Firmware Version Badge */}
- {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
- <button
- onClick={() => setShowFirmwareModal(true)}
- className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
- firmwareInfo.update_available
- ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
- : 'bg-status-ok/20 text-status-ok'
- }`}
- title={
- firmwareInfo.update_available
- ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
- : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
- }
- >
- {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)]" />}
- {firmwareInfo.current_version}
- </button>
- ) : status?.firmware_version ? (
- <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
- {status.firmware_version}
- </span>
- ) : null}
- {/* Enclosure Door Badge — models with an actual door sensor.
- P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
- {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
- <span
- className={`flex items-center px-2 py-1 rounded-full text-xs ${
- status.door_open
- ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
- : 'bg-status-ok/20 text-status-ok'
- }`}
- title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
- >
- {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)]" />}
- </span>
- )}
- </div>
- </div>
- )}
- </div>
- {/* Delete Confirmation */}
- {showDeleteConfirm && (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
- <Card className="w-full max-w-md mx-4">
- <CardContent>
- <div className="flex items-start gap-3 mb-4">
- <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
- <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
- </div>
- <div>
- <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
- <p className="text-sm text-bambu-gray mt-1">
- {t('printers.confirm.deleteMessage', { name: printer.name })}
- </p>
- </div>
- </div>
- <div className="bg-bambu-dark rounded-lg p-3 mb-4">
- <label className="flex items-start gap-3 cursor-pointer">
- <input
- type="checkbox"
- checked={deleteArchives}
- onChange={(e) => setDeleteArchives(e.target.checked)}
- 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"
- />
- <div>
- <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
- <p className="text-xs text-bambu-gray mt-0.5">
- {deleteArchives
- ? t('printers.confirm.deleteArchivesNote')
- : t('printers.confirm.keepArchivesNote')}
- </p>
- </div>
- </label>
- </div>
- <div className="flex justify-end gap-2">
- <Button
- variant="secondary"
- onClick={() => {
- setShowDeleteConfirm(false);
- setDeleteArchives(true);
- }}
- >
- {t('common.cancel')}
- </Button>
- <Button
- variant="danger"
- onClick={() => {
- deleteMutation.mutate({ deleteArchives });
- setShowDeleteConfirm(false);
- setDeleteArchives(true);
- }}
- >
- Delete
- </Button>
- </div>
- </CardContent>
- </Card>
- </div>
- )}
- {/* Status — see the equivalent defensive `=== false` check on the
- header pill above for why this is not `!printer.is_active`. */}
- {printer.is_active === false ? (
- // Maintenance mode (#1476) — replaces the cover/progress container
- // so the card keeps the same height. Renders for both compact and
- // expanded view modes so the printer stays visible but plainly
- // out-of-service.
- <>
- {viewMode === 'compact' ? (
- <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">
- <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
- <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
- {t('printers.maintenance.pillLabel')}
- </span>
- </div>
- ) : (
- <>
- <div className="flex items-center gap-2 mb-2">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
- {t('printers.status.title', 'Status')}
- </span>
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
- </div>
- <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">
- <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
- <div className="flex-1 min-w-0">
- <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
- {t('printers.maintenance.title')}
- </p>
- <p className="text-xs text-bambu-gray mt-0.5">
- {t('printers.maintenance.subtitle')}
- </p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
- onClick={() => maintenanceMutation.mutate(true)}
- title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
- >
- {t('printers.maintenance.exitButton')}
- </Button>
- </div>
- </>
- )}
- </>
- ) : status?.connected && (
- <>
- {/* Compact: Simple status bar */}
- {viewMode === 'compact' ? (
- (() => {
- const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
- const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
- const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
- ? Math.max(0, Math.min(100, status.progress || 0))
- : showClearPlateButton
- ? 100
- : hasProblem
- ? 100
- : 0;
- const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
- const compactProgressClass = hasProblem
- ? 'bg-status-error'
- : status.state === 'PAUSE'
- ? 'bg-status-warning'
- : 'bg-bambu-green';
- const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
- const hasCompactLayers =
- isActiveCompactPrint &&
- status.layer_num != null &&
- status.total_layers != null &&
- status.total_layers > 0;
- return (
- <>
- <div className="relative mt-2 flex items-center gap-2">
- <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
- <div
- className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
- style={{ width: `${compactProgress}%` }}
- />
- </div>
- <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
- {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
- </span>
- </div>
- {/* #2674: size S showed only a name, a pip and a progress bar — not
- enough to answer "which printer finishes first", which is what a
- wall-mounted fleet view is for. One line of the metrics the
- expanded card already renders, using the same formatters and the
- same ETA styling so S and M read alike. The row keeps its height
- when idle so cards don't shift as prints start and stop. */}
- <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">
- {hasCompactEta && (
- <>
- <span className="flex shrink-0 items-center gap-1">
- <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {formatDuration(status.remaining_time! * 60)}
- </span>
- <span
- className="shrink-0 font-medium text-bambu-green"
- title={t('printers.estimatedCompletion')}
- >
- ETA {formatETA(status.remaining_time!, timeFormat, t)}
- </span>
- </>
- )}
- {hasCompactLayers && (
- <span className="flex min-w-0 items-center gap-1 truncate">
- <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
- {status.layer_num}/{status.total_layers}
- </span>
- )}
- </div>
- </>
- );
- })()
- ) : (
- /* Expanded: Full status section */
- <>
- <div className="flex items-center gap-2 mb-2">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
- {t('printers.status.title', 'Status')}
- </span>
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
- </div>
- {/* Current Print or Idle Placeholder */}
- {(() => {
- const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
- const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
- const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
- const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
- const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
- return (
- <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
- <button
- onClick={() => setShowSkipObjectsModal(true)}
- disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
- className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
- isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
- ? 'text-bambu-gray hover:text-white hover:bg-white/10'
- : 'text-bambu-gray/30 cursor-not-allowed'
- }`}
- title={
- !hasPermission('printers:control')
- ? t('printers.permission.noControl')
- : !isActivePrint
- ? t('printers.skipObjects.onlyWhilePrinting')
- : (status.printable_objects_count ?? 0) >= 2
- ? t('printers.skipObjects.tooltip')
- : t('printers.skipObjects.requiresMultiple')
- }
- >
- <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {objectsData && objectsData.skipped_count > 0 && (
- <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">
- {objectsData.skipped_count}
- </span>
- )}
- </button>
- <div className="flex items-stretch gap-2">
- <CoverImage
- url={coverUrl}
- printName={printName || undefined}
- className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
- />
- <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
- <div className="flex min-h-[18px] items-center gap-2 pr-8">
- <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
- {plateStatusPill}
- </div>
- <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
- {printName || t('printers.noActiveJob', 'No active job')}
- </p>
- <div className="flex h-3 items-center gap-2 text-sm">
- <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
- <div
- 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`}
- style={{ width: `${progress}%` }}
- />
- </div>
- <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>
- </div>
- <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
- {isActivePrint ? (
- <>
- {status.remaining_time != null && status.remaining_time > 0 && (
- <>
- <span className="flex items-center gap-1">
- <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {formatDuration(status.remaining_time * 60)}
- </span>
- <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
- ETA {formatETA(status.remaining_time, timeFormat, t)}
- </span>
- </>
- )}
- {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
- <span className="flex items-center gap-1">
- <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {status.layer_num}/{status.total_layers}
- </span>
- )}
- {currentPrintUser && (
- <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
- <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {currentPrintUser}
- </span>
- )}
- </>
- ) : lastPrint ? (
- <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
- Last: {lastPrint.print_name || lastPrint.filename}
- {lastPrint.completed_at && (
- <span className="ml-1 text-bambu-gray/60">
- • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
- </span>
- )}
- </p>
- ) : (
- <span>{t('printers.readyToPrint')}</span>
- )}
- </div>
- </div>
- </div>
- <PrinterQueueWidget
- printerId={printer.id}
- printerModel={printer.model}
- loadedFilamentTypes={loadedFilamentTypes}
- loadedFilaments={loadedFilaments}
- loadedVariants={loadedVariants}
- variant="panelExtension"
- />
- </div>
- );
- })()}
- </>
- )}
- {/* Temperatures */}
- {status.temperatures && viewMode === 'expanded' && (() => {
- // Use actual heater states from MQTT stream
- const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
- const bedHeating = status.temperatures.bed_heating || false;
- const chamberHeating = status.temperatures.chamber_heating || false;
- const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
- const availableHeaterKinds: HeaterSensorKind[] = (() => {
- const kinds: HeaterSensorKind[] = ['nozzle'];
- if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
- kinds.push('bed');
- if (status.temperatures.chamber !== undefined) kinds.push('chamber');
- return kinds;
- })();
- // active_extruder: 0=right, 1=left
- const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
- // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
- // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
- const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
- const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
- // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
- const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
- const canUseStatusControls = status.connected && hasPermission('printers:control');
- const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
- 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 ${
- canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
- }`;
- // Chamber fan only exists on enclosed Bambu models. Open-frame
- // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
- // the widget there is at best dead UI and at worst suggests a
- // control that does nothing. Mirrors the enclosure-door badge
- // gate above.
- const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
- // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
- // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
- // show it only when the printer actually reports it (airduct part id 3,
- // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
- // have a built-in chamber fan that's always present, so they keep the
- // existing model-list gate and the "Chamber Fan" label.
- const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
- const chamberFanLabel = isExhaustModel
- ? t('printers.fans.exhaust')
- : t('printers.fans.chamber');
- // Composed rather than either/or so both lists stay live for
- // P2S/X2D: the model must have an enclosure fan at all, AND —
- // where that fan is an add-on kit — actually report it. Written
- // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
- // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
- // which reads as if removing them were safe.
- const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
- const fanItems: {
- key: string;
- label: string;
- value: number;
- Icon: typeof Fan;
- activeClass: string;
- }[] = [
- {
- key: 'part',
- label: t('printers.fans.partCooling'),
- value: status.cooling_fan_speed ?? 0,
- Icon: Fan,
- activeClass: 'text-cyan-600 dark:text-cyan-400',
- },
- // Left auxiliary part cooling fan (optional P2S/X2D accessory).
- // Only reported (non-null) when the firmware lists airduct part
- // id 10, i.e. when the fan is physically installed. Placed
- // before the right-hand auxiliary fan so the two aux badges read
- // left-to-right in the same order as the physical hardware.
- ...(status.left_aux_fan_speed != null
- ? [
- {
- key: 'aux2',
- label: t('printers.fans.leftAuxiliary'),
- value: status.left_aux_fan_speed,
- Icon: Wind,
- activeClass: 'text-indigo-600 dark:text-indigo-400',
- },
- ]
- : []),
- {
- key: 'aux',
- label: t('printers.fans.auxiliary'),
- value: status.big_fan1_speed ?? 0,
- Icon: Wind,
- activeClass: 'text-blue-600 dark:text-blue-400',
- },
- ...(showChamberFan
- ? [
- {
- key: 'chamber',
- label: chamberFanLabel,
- value: status.big_fan2_speed ?? 0,
- Icon: AirVent,
- activeClass: 'text-green-600 dark:text-green-400',
- },
- ]
- : []),
- ];
- return (
- <>
- <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
- {/* Nozzle temp - combined for dual nozzle */}
- <div
- className={statusControlClass}
- title={statusControlTitle}
- onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
- >
- <button
- type="button"
- className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
- title={t('printers.heaterHistory.openLabel', 'View heater history')}
- onClick={(e) => {
- e.stopPropagation();
- setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
- }}
- >
- <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
- </button>
- <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
- {status.temperatures.nozzle_2 !== undefined ? (
- <>
- <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
- <p className="text-[length:var(--pc-t11,11px)] text-white">
- {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
- </p>
- </>
- ) : singleNozzleSlot ? (
- <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
- <div className="cursor-default">
- <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
- <p className="text-[length:var(--pc-t11,11px)] text-white">
- {Math.round(status.temperatures.nozzle || 0)}°C
- </p>
- </div>
- </NozzleSlotHoverCard>
- ) : (
- <>
- <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
- <p className="text-[length:var(--pc-t11,11px)] text-white">
- {Math.round(status.temperatures.nozzle || 0)}°C
- </p>
- </>
- )}
- {statusControlMenu === 'nozzle-temp' && (
- isDualNozzle ? (
- <IndicatorControlPopover
- title="Set Nozzle Temperatures"
- widthClass="w-[300px]"
- popoverWidth={300}
- popoverHeight={260}
- isPending={nozzleTemperatureMutation.isPending}
- onClose={() => setStatusControlMenu(null)}
- >
- <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
- <NozzleTemperatureControlBox
- label="Left Temp"
- current={status.temperatures.nozzle}
- target={status.temperatures.nozzle_target}
- isActive={activeNozzle === 'L'}
- isPending={nozzleTemperatureMutation.isPending}
- onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
- options={buildPresetOptions(nozzleTempPresets, 'C')}
- />
- <NozzleTemperatureControlBox
- label="Right Temp"
- current={status.temperatures.nozzle_2}
- target={status.temperatures.nozzle_2_target}
- isActive={activeNozzle === 'R'}
- isPending={nozzleTemperatureMutation.isPending}
- onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
- options={buildPresetOptions(nozzleTempPresets, 'C')}
- />
- </div>
- </IndicatorControlPopover>
- ) : (
- <IndicatorControlPopover
- title="Set Nozzle Temperature"
- unit="°C"
- customMin={0}
- customMax={320}
- isPending={nozzleTemperatureMutation.isPending}
- options={buildPresetOptions(nozzleTempPresets, 'C')}
- onClose={() => setStatusControlMenu(null)}
- onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
- />
- )
- )}
- </div>
- <div
- className={statusControlClass}
- title={statusControlTitle}
- onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
- >
- <button
- type="button"
- className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
- title={t('printers.heaterHistory.openLabel', 'View heater history')}
- onClick={(e) => {
- e.stopPropagation();
- setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
- }}
- >
- <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
- </button>
- <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
- <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
- <p className="text-[length:var(--pc-t11,11px)] text-white">
- {Math.round(status.temperatures.bed || 0)}°C
- </p>
- {statusControlMenu === 'bed-temp' && (
- <IndicatorControlPopover
- title="Set Bed Temperature"
- unit="°C"
- customMin={0}
- customMax={140}
- isPending={bedTemperatureMutation.isPending}
- options={buildPresetOptions(bedTempPresets, 'C')}
- onClose={() => setStatusControlMenu(null)}
- onSubmit={(target) => bedTemperatureMutation.mutate(target)}
- />
- )}
- </div>
- {status.temperatures.chamber !== undefined && (() => {
- // Sensor-only models (X1C, X1E, P2S) show the chamber reading
- // but can't act on M141, so we keep the card read-only there.
- const hasChamberHeater = status.supports_chamber_heater === true;
- return (
- <div
- className={hasChamberHeater
- ? statusControlClass
- : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
- title={hasChamberHeater ? statusControlTitle : undefined}
- onClick={hasChamberHeater
- ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
- : undefined}
- >
- <button
- type="button"
- className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
- title={t('printers.heaterHistory.openLabel', 'View heater history')}
- onClick={(e) => {
- e.stopPropagation();
- setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
- }}
- >
- <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
- </button>
- <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
- <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
- <p className="text-[length:var(--pc-t11,11px)] text-white">
- {Math.round(status.temperatures.chamber || 0)}°C
- </p>
- {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
- <IndicatorControlPopover
- title="Set Chamber Temperature"
- unit="°C"
- customMin={0}
- customMax={MAX_CHAMBER_TEMP_C}
- isPending={chamberTemperatureMutation.isPending}
- options={buildPresetOptions(chamberTempPresets, 'C')}
- onClose={() => setStatusControlMenu(null)}
- onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
- />
- )}
- </div>
- );
- })()}
- {/* Active nozzle indicator for dual-nozzle printers */}
- {isDualNozzle && (
- <DualNozzleHoverCard
- leftSlot={leftNozzleSlot}
- rightSlot={rightNozzleSlot}
- activeNozzle={activeNozzle}
- filamentInfo={filamentInfo}
- >
- <div
- 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 ${
- canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
- }`}
- title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
- onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
- >
- <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
- <div className="flex items-center gap-2">
- <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
- L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
- </span>
- <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
- <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
- R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
- </span>
- </div>
- <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
- {statusControlMenu === 'nozzle-select' && (
- <IndicatorControlPopover
- title="Set Nozzle Selection"
- widthClass="w-[300px]"
- popoverWidth={300}
- popoverHeight={140}
- isPending={selectExtruderMutation.isPending}
- options={[
- { label: 'Left', value: 1 },
- { label: 'Right', value: 0 },
- ]}
- onClose={() => setStatusControlMenu(null)}
- onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
- />
- )}
- </div>
- </DualNozzleHoverCard>
- )}
- {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
- {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
- <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
- )}
- </div>
- <div className="mt-2 flex items-center gap-1.5">
- {fanItems.map(({ key, label, value, Icon, activeClass }) => {
- const active = value > 0;
- return (
- <div
- key={key}
- 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 ${
- canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
- }`}
- title={canUseStatusControls ? label : statusControlTitle}
- onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
- >
- <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
- <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
- {value}%
- </span>
- {statusControlMenu === `fan-${key}` && (
- <IndicatorControlPopover
- title={`Set ${label} Speed`}
- unit="%"
- customMin={0}
- customMax={100}
- isPending={fanSpeedMutation.isPending}
- options={buildPresetOptions(fanSpeedPresets, '%')}
- onClose={() => setStatusControlMenu(null)}
- onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
- />
- )}
- </div>
- );
- })}
- </div>
- </>
- );
- })()}
- {viewMode === 'expanded' && showClearPlateButton && (
- <button
- type="button"
- onClick={() => clearPlateMutation.mutate()}
- disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
- 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"
- title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
- >
- {clearPlateMutation.isPending ? (
- <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
- ) : (
- <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- )}
- {t('printers.plateStatus.markCleared')}
- </button>
- )}
- {/* Controls */}
- {viewMode === 'expanded' && (() => {
- // Determine print state for control buttons
- const isRunning = status.state === 'RUNNING';
- const isPaused = status.state === 'PAUSE';
- const isPrinting = isRunning || isPaused;
- const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
- const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
- 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';
- const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
- return (
- <div className="mt-3">
- {/* Section Header */}
- <div className="flex items-center gap-2 mb-2">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
- {t('printers.controls')}
- </span>
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
- </div>
- <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
- {/* Left: Secondary controls */}
- <div className="flex flex-wrap items-center gap-2 min-w-0">
- <button
- onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
- disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
- className={`${iconControlClass} ${
- status.chamber_light
- ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
- : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
- }`}
- title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
- >
- <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- {/* Airduct Mode (P2S / X2D / H2*) */}
- {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
- const isHeating = status.airduct_mode === 1;
- const Icon = isHeating ? Flame : Snowflake;
- const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
- 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';
- return (
- <div className="relative">
- <button
- onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
- disabled={!hasPermission('printers:control')}
- className={`${iconControlClass} ${bg}`}
- title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
- >
- <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
- </button>
- {showAirductMenu === printer.id && (
- <>
- <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
- <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]">
- {([
- { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
- { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
- ] as const).map(({ mode, label, modeId }) => (
- <button
- key={mode}
- onClick={() => {
- airductMutation.mutate(mode);
- setShowAirductMenu(null);
- }}
- className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
- status.airduct_mode === modeId
- ? 'text-bambu-green bg-bambu-green/10'
- : 'text-white hover:bg-bambu-dark-tertiary'
- }`}
- >
- {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)]" />}
- {label}
- </button>
- ))}
- </div>
- </>
- )}
- </div>
- );
- })()}
- {/* Movement — compact badge, popover holds XY, Z, and home controls */}
- {(() => {
- const canControl = hasPermission('printers:control');
- const disabled = isPrinting || !canControl;
- const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
- 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';
- const requestZJog = (direction: 1 | -1) => {
- const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
- // The jog never disables the soft endstops (#2579), so it's always
- // safe: the firmware clamps the move at the travel limit, or refuses
- // it if the printer isn't homed. No not-homed bypass to gate.
- bedJogMutation.mutate({ distance: signed });
- };
- const requestXyJog = (x: number, y: number) => {
- xyJogMutation.mutate({ x, y });
- };
- const requestExtruderJog = (distance: number) => {
- extruderJogMutation.mutate(distance);
- };
- return (
- <div className="relative">
- <button
- onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
- disabled={disabled}
- className={`${iconControlClass} ${
- disabled
- ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
- : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
- }`}
- title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
- >
- <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- {showBedJogMenu === printer.id && (
- <>
- <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
- <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">
- <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
- {t('printers.bedJog.title')}
- </div>
- <div className="h-px bg-bambu-dark-tertiary" />
- {/* #2579: Bambu firmware does not enforce soft endstops on
- G-code sent over MQTT, so manual moves can drive past the
- travel limits and cause a collision. Not fixable from our
- side — warn prominently. */}
- <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">
- <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
- <span>{t('printers.bedJog.limitWarning')}</span>
- </div>
- <div className="h-px bg-bambu-dark-tertiary" />
- <div className="flex justify-center px-3 py-2.5">
- <div className="flex items-center justify-center gap-3">
- <div className="grid grid-cols-3 gap-1">
- <div />
- <button
- onClick={() => requestXyJog(0, bedJogStep)}
- disabled={xyJogMutation.isPending}
- className={jogButtonClass}
- aria-label="Move Y forward"
- >
- <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <div />
- <button
- onClick={() => requestXyJog(-bedJogStep, 0)}
- disabled={xyJogMutation.isPending}
- className={jogButtonClass}
- aria-label="Move X left"
- >
- <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <button
- onClick={() => {
- setShowBedJogMenu(null);
- homeAxesMutation.mutate('all');
- }}
- disabled={homeAxesMutation.isPending}
- className={jogButtonClass}
- aria-label={t('printers.bedJog.homeZ')}
- >
- <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <button
- onClick={() => requestXyJog(bedJogStep, 0)}
- disabled={xyJogMutation.isPending}
- className={jogButtonClass}
- aria-label="Move X right"
- >
- <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <div />
- <button
- onClick={() => requestXyJog(0, -bedJogStep)}
- disabled={xyJogMutation.isPending}
- className={jogButtonClass}
- aria-label="Move Y back"
- >
- <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <div />
- </div>
- <div className="flex flex-col items-center gap-1">
- <button
- onClick={() => requestZJog(-1)}
- disabled={bedJogMutation.isPending}
- className={jogButtonClass}
- aria-label={t('printers.bedJog.up')}
- >
- <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
- <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </div>
- <button
- onClick={() => requestZJog(1)}
- disabled={bedJogMutation.isPending}
- className={jogButtonClass}
- aria-label={t('printers.bedJog.down')}
- >
- <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- </div>
- <div className="flex flex-col items-center gap-1">
- <button
- onClick={() => requestExtruderJog(-bedJogStep)}
- disabled={extruderJogMutation.isPending}
- className={jogButtonClass}
- aria-label="Retract filament"
- >
- <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
- <span className="text-sm font-semibold leading-none">E</span>
- </div>
- <button
- onClick={() => requestExtruderJog(bedJogStep)}
- disabled={extruderJogMutation.isPending}
- className={jogButtonClass}
- aria-label="Extrude filament"
- >
- <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- </div>
- </div>
- </div>
- <div className="h-px bg-bambu-dark-tertiary" />
- <div className="px-3 pt-2.5 pb-3">
- <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
- {t('printers.bedJog.step')}
- </div>
- <div className="flex gap-1">
- {[1, 10, 50].map((step) => (
- <button
- key={step}
- onClick={() => setBedJogStep(step)}
- className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
- bedJogStep === step
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
- }`}
- >
- {step}
- </button>
- ))}
- </div>
- </div>
- </div>
- </>
- )}
- </div>
- );
- })()}
- <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
- <button
- onClick={handleTogglePlateDetection}
- disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
- className={`${iconControlClass} rounded-r-none ${
- printer.plate_detection_enabled
- ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
- : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
- }`}
- title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
- >
- {plateDetectionMutation.isPending ? (
- <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
- ) : (
- <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- )}
- </button>
- <button
- onClick={handleOpenPlateManagement}
- disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
- 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 ${
- printer.plate_detection_enabled
- ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
- : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
- }`}
- title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
- >
- {isCheckingPlate ? (
- <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
- ) : (
- <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- )}
- </button>
- </div>
- {/* Print Speed */}
- {(() => (
- <div className="relative">
- <button
- data-testid="speed-control"
- onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
- disabled={!isPrinting || !hasPermission('printers:control')}
- className={`${iconControlClass} ${
- isPrinting
- ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
- : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={isPrinting ? t('printers.speed.title') : undefined}
- >
- <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- {showSpeedMenu === printer.id && (
- <>
- <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
- <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]">
- {([
- { mode: 1, label: t('printers.speed.silent') },
- { mode: 2, label: t('printers.speed.standard') },
- { mode: 3, label: t('printers.speed.sport') },
- { mode: 4, label: t('printers.speed.ludicrous') },
- ] as const).map(({ mode, label }) => (
- <button
- key={mode}
- onClick={() => {
- printSpeedMutation.mutate(mode);
- setShowSpeedMenu(null);
- }}
- className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
- status.speed_level === mode
- ? 'text-bambu-green bg-bambu-green/10'
- : 'text-white hover:bg-bambu-dark-tertiary'
- }`}
- >
- {label}
- </button>
- ))}
- </div>
- </>
- )}
- </div>
- ))()}
- </div>
- {/* Right: Print Control Buttons */}
- <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
- {/* Pause/Resume button */}
- {(() => {
- const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
- return (
- <button
- onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
- disabled={pauseUnavailable}
- className={`
- ${printControlClass}
- ${pauseUnavailable
- ? unavailablePrintActionClass
- : isPaused
- ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
- : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
- }
- `}
- title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
- >
- {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)]" />}
- {isPaused ? t('printers.resume') : t('printers.pause')}
- </button>
- );
- })()}
- {/* Stop button */}
- {(() => {
- const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
- return (
- <button
- onClick={() => setShowStopConfirm(true)}
- disabled={stopUnavailable}
- className={`
- ${printControlClass}
- ${stopUnavailable
- ? unavailablePrintActionClass
- : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
- }
- `}
- title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
- >
- <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- {t('printers.stop')}
- </button>
- );
- })()}
- </div>
- </div>
- </div>
- );
- })()}
- {/* AMS Units - 2-Column Grid Layout */}
- {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
- // Separate regular AMS (4-tray) from HT AMS (1-tray)
- const regularAms = amsData.filter(ams => ams.tray.length > 1);
- const htAms = amsData.filter(ams => ams.tray.length === 1);
- // The external spool can only be hidden while some AMS remains to
- // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
- // filament section, so the toggle is not offered there and a stored
- // preference from a printer that later lost its AMS cannot blank the
- // row either — both read through canHideExternalSpool.
- const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
- const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
- const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
- const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
- // Rounded because 11 * 1.2 is 13.200000000000001 in binary
- // floating point, and that lands verbatim in the DOM.
- const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
- // Deliberately NOT scaled with the body (#1848). These AMS cards
- // already grow to fill the row, so the 3.5rem is a floor they sit
- // well above in practice -- raising it just costs a unit its place
- // on the row. Losing one matters: a wrapped AMS-HT is then alone on
- // its line, and flex-grow stretches its single slot across the whole
- // card. The AMS-HT's own width does scale, below, because its
- // readings sit beside the slot rather than under it.
- const slotMinWidth = '3.5rem';
- const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
- // The AMS-HT holds a single spool, and its slot is the only thing
- // on that row able to grow -- so it swallowed every spare pixel and
- // shoved the temperature and humidity hard against the card's edge.
- // Capping it at roughly two ordinary slots keeps the readings clear
- // of the edge; the cap scales because the text inside the slot does.
- const htSlotStyle: React.CSSProperties = {
- minWidth: slotMinWidth,
- maxWidth: scaledRem(7.25),
- };
- const slotGridStyle = (columns: number): React.CSSProperties => ({
- gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
- });
- // #1762 (comment 2): while a print is running/paused, overlay a small
- // "P1 / P2 / P3" pill on each slot referenced by the active print's
- // mapping. Catches the reporter's scenario — "any X1C" queue job
- // staged to a printer with mismatched filament: the wrong-slot pill
- // is visible the instant printing starts.
- const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
- const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
- ? status.ams_mapping
- : [];
- const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
- const boundedSlotCount = Math.max(1, slotCount);
- const gapCount = Math.max(0, boundedSlotCount - 1);
- const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
- return {
- flex: `1 1 ${minWidth}`,
- minWidth,
- };
- };
- return (
- <div className="mt-3">
- {/* Section Header */}
- <div className="flex items-center gap-2 mb-2">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
- {t('printers.filaments')}
- </span>
- <AmsBackupBadge
- state={status.ams_filament_backup}
- onClick={() => setAmsBackupModalOpen(true)}
- />
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
- {/* Offered only when an AMS is present: on a printer that
- feeds from the external spool alone, hiding it would
- empty the row entirely (#1782). */}
- {canHideExternalSpool && (
- <>
- <ExternalSpoolToggle
- hidden={externalSpoolHidden}
- onClick={toggleExternalSpool}
- />
- <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
- </>
- )}
- </div>
- {/* AMS Content */}
- <div className="flex flex-wrap gap-2">
- {/* Regular AMS units */}
- {regularAms.map((ams) => {
- const mappedExtruderId = amsExtruderMap[String(ams.id)];
- const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
- const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
- const isLeftNozzle = extruderId === 1;
- const isRightNozzle = extruderId === 0;
- return (
- <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
- {/* Header: Label + Stats (no icon) */}
- <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
- <div className="flex min-w-0 flex-1 items-center gap-1.5">
- {/* AMS name — hover to see serial, firmware, and edit friendly name */}
- <AmsNameHoverCard
- ams={ams}
- printerId={printer.id}
- label={getAmsLabel(ams.id, ams.tray.length)}
- amsLabels={amsLabels}
- canEdit={hasPermission('printers:update')}
- onSaved={refetchAmsLabels}
- >
- <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
- {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
- </span>
- </AmsNameHoverCard>
- {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
- <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
- )}
- </div>
- {(ams.humidity != null || ams.temp != null) && (
- <div className="flex shrink-0 items-center gap-1.5">
- {ams.humidity != null && (
- <HumidityIndicator
- humidity={ams.humidity}
- goodThreshold={amsThresholds?.humidityGood}
- fairThreshold={amsThresholds?.humidityFair}
- onClick={() => setAmsHistoryModal({
- amsId: ams.id,
- amsLabel: getAmsLabel(ams.id, ams.tray.length),
- mode: 'humidity',
- })}
- compact
- />
- )}
- {ams.temp != null && (
- <div className="mr-1">
- <TemperatureIndicator
- temp={ams.temp}
- goodThreshold={amsThresholds?.tempGood}
- fairThreshold={amsThresholds?.tempFair}
- onClick={() => setAmsHistoryModal({
- amsId: ams.id,
- amsLabel: getAmsLabel(ams.id, ams.tray.length),
- mode: 'temperature',
- })}
- compact
- />
- </div>
- )}
- {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
- Screen-only models (P1 series) keep the control but can't
- be commanded: it stays disabled and says why (#2533). */}
- {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
- <button
- disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
- onClick={(e) => {
- if (ams.dry_time > 0) {
- stopDryingMutation.mutate(ams.id);
- } else if (dryingPopoverAmsId === ams.id) {
- setDryingPopoverAmsId(null);
- } else {
- const firstTray = ams.tray.find(t => t.tray_type);
- const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
- // Only reachable if a custom preset set dropped PLA itself.
- const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
- const moduleType = ams.module_type as 'n3f' | 'n3s';
- setDryingFilament(filType);
- setDryingTemp(preset[moduleType] || preset.n3f);
- setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
- setDryingRotateTray(false);
- setDryingPopoverModuleType(ams.module_type);
- setDryingPopoverAmsId(ams.id);
- const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
- setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
- }
- }}
- className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
- ams.dry_time > 0
- ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
- : status.drying_screen_only || ams.dry_sf_reason?.length
- ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
- : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
- }`}
- title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t('printers.drying.powerRequired') : t('printers.drying.start')}
- >
- <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- </button>
- )}
- </div>
- )}
- </div>
- {/* Drying status bar */}
- {ams.dry_time > 0 && (
- <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)]">
- <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
- <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
- {/* The temperature is only ever known from the target we
- cached when sending the command — the filament can also
- be read off a uniformly loaded unit, so it can outlive
- the temperature (#2759). */}
- {ams.dry_filament && (
- <span className="text-amber-700/80 dark:text-amber-300/70">
- {ams.dry_target_temp != null
- ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
- : ams.dry_filament}
- </span>
- )}
- <span className="text-amber-700/80 dark:text-amber-300/70">
- {t('printers.drying.timeRemaining', {
- time: ams.dry_time >= 60
- ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
- : `${ams.dry_time}m`
- })}
- </span>
- {/* A cycle on a screen-only model was started at the printer
- and can only be stopped there (#2533). */}
- {!status.drying_screen_only && (
- <button
- onClick={() => stopDryingMutation.mutate(ams.id)}
- disabled={stopDryingMutation.isPending}
- className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
- title={t('printers.drying.stop')}
- >
- <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- </button>
- )}
- </div>
- )}
- {/* Slots grid: 4 columns - always render 4 slots */}
- <div className="grid w-full gap-1" style={slotGridStyle(4)}>
- {[0, 1, 2, 3].map((slotIdx) => {
- // Find tray data for this slot (may be undefined if data incomplete)
- // Use array index if available, as tray.id may not always be set
- const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
- const hasFillLevel = tray?.tray_type && tray.remain >= 0;
- const isEmpty = !tray?.tray_type;
- const emptyKind = getEmptySlotKind(tray);
- // Check if this is the currently loaded tray
- // Global tray ID = ams.id * 4 + slot index (for standard AMS)
- const globalTrayId = ams.id * 4 + slotIdx;
- const isActive = effectiveTrayNow === globalTrayId;
- // Runout guidance (#2587): the slot the paused print now
- // expects filament in, and the slot that ran out.
- const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
- const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
- // Get cloud preset info if available
- const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
- // Get saved slot preset mapping (for user-configured slots)
- const slotPreset = slotPresets?.[globalTrayId];
- // Fill level fallback chain: Spoolman → Inventory → AMS remain
- const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
- const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
- const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
- // Slot-assigned-only spool fill (no tag link required)
- const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
- ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
- : undefined;
- const slotSpoolForFill = slotAssignmentForFill
- ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
- : undefined;
- const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
- ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
- : null;
- const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
- const inventoryFill = (() => {
- const sp = inventoryAssignment?.spool;
- if (sp && sp.label_weight > 0 && sp.weight_used != null) {
- return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
- }
- return null;
- })();
- // If inventory says 0% but AMS reports positive remain, prefer AMS
- // (inventory weight_used may be stale or over-counted — #676)
- const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
- ? null : inventoryFill;
- const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
- const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
- : resolvedInventoryFill !== null ? 'inventory' as const
- : hasFillLevel ? 'ams' as const
- : undefined;
- // Build filament data for hover card
- const filamentData = tray?.tray_type ? {
- vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
- // Spoolman spool name wins over cloud lookup so a slot bound to
- // a Spoolman spool shows that spool's preset name (e.g. "Devil
- // Design PLA") instead of whatever the printer's filament_id
- // resolves to in the cloud catalog (often "Generic PLA" for
- // P-prefix local presets). Spoolman's filament.name is just the
- // material+subtype ("PLA Basic"); prepend the spool's brand so
- // the hover card shows "Devil Design PLA Basic" rather than the
- // vendor-less form. Strip the "@<printer>..." suffix that
- // BambuStudio appends to user-preset names.
- profile: slotPreset?.preset_name || (slotSpoolForFill ? [slotSpoolForFill.brand, slotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || slotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || inventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
- colorName: getColorName(tray.tray_color || ''),
- colorHex: tray.tray_color || null,
- kFactor: formatKValue(tray.k),
- fillLevel: effectiveFill,
- trayUuid: tray.tray_uuid || null,
- tagUid: tray.tag_uid || null,
- fillSource,
- } : null;
- // Check if this specific slot is being refreshed
- const isRefreshing = refreshingSlot?.amsId === ams.id &&
- refreshingSlot?.slotId === slotIdx;
- // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
- const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
- const activePrintSlotLabel = activePrintSlotIdx >= 0
- ? `P${activePrintSlotIdx + 1}`
- : null;
- // Slot visual content (goes inside hover card)
- const slotVisual = (
- <div
- className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
- isExpectedSlot
- ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
- : isRanOutSlot
- ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
- : isActive
- ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
- : ''
- }`}
- >
- {isExpectedSlot && (
- <span
- aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
- title={t('printers.expectedSlot.title')}
- 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"
- >
- ↓
- </span>
- )}
- {activePrintSlotLabel && (
- <span
- aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
- title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
- 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"
- >
- {activePrintSlotLabel}
- </span>
- )}
- {/* Filament color circle with 1-based slot number centered inside */}
- <FilamentSlotCircle
- trayColor={tray?.tray_color}
- trayType={tray?.tray_type}
- isEmpty={isEmpty}
- emptyKind={emptyKind}
- slotNumber={slotIdx + 1}
- />
- <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
- {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
- </div>
- {/* Fill bar */}
- <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
- {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
- <div
- className="h-full rounded-full transition-all"
- style={{
- width: `${effectiveFill}%`,
- backgroundColor: getFillBarColor(effectiveFill),
- }}
- />
- )}
- </div>
- </div>
- );
- // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
- return (
- <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
- {/* Loading overlay during RFID re-read */}
- {isRefreshing && (
- <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
- <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
- </div>
- )}
- {/* Hover card wraps only the visual content */}
- {filamentData ? (
- <FilamentHoverCard
- data={filamentData}
- actions={renderAmsSlotActions({
- amsId: ams.id,
- slotId: slotIdx,
- loadTrayId: ams.id * 4 + slotIdx,
- isRefreshing,
- })}
- spoolman={{
- enabled: spoolmanEnabled,
- // #1457: slot assignment is the user's most explicit action — it must
- // outrank the tag-link, which can be stale when a non-RFID slot's
- // fallback tag is still attached to a previous spool in Spoolman.
- linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
- ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
- spoolmanUrl,
- syncMode: spoolmanSyncMode,
- // Suppress Link button when slot is already occupied by ANY assignment
- // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
- // suppressed for Spoolman; the maintainer screenshot shows the badge
- // still appearing on slots with a local Devil Design PLA assigned.
- onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
- const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
- setLinkSpoolModal({
- tagUid: filamentData.tagUid || linkTag,
- trayUuid: filamentData.trayUuid || '',
- printerId: printer.id,
- amsId: ams.id,
- trayId: slotIdx,
- });
- } : undefined,
- onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
- }}
- inventory={(() => {
- if (spoolmanEnabled) {
- if (spoolmanLoading) return undefined;
- const slotAssignment = slotAssignmentForFill;
- const spoolmanSpool = slotSpoolForFill;
- return {
- assignedSpool: spoolmanSpool ? {
- id: spoolmanSpool.id,
- material: spoolmanSpool.material,
- brand: spoolmanSpool.brand ?? null,
- color_name: spoolmanSpool.color_name ?? null,
- remainingWeightGrams: spoolmanSpool.label_weight
- ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
- : undefined,
- } : null,
- onAssignSpool: () => setAssignSpoolModal({
- printerId: printer.id,
- amsId: ams.id,
- trayId: slotIdx,
- trayInfo: {
- type: tray?.tray_type || filamentData.profile,
- material: tray?.tray_type ?? undefined,
- profile: filamentData.profile,
- color: filamentData.colorHex || '',
- location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
- },
- }),
- onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
- isAssigned: !!slotAssignment || isBambuLabSpool(tray),
- };
- }
- const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
- return {
- assignedSpool: assignment?.spool ? {
- id: assignment.spool.id,
- material: assignment.spool.material,
- brand: assignment.spool.brand,
- color_name: assignment.spool.color_name,
- remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
- } : null,
- onAssignSpool: () => setAssignSpoolModal({
- printerId: printer.id,
- amsId: ams.id,
- trayId: slotIdx,
- trayInfo: {
- type: tray?.tray_type || filamentData.profile,
- material: tray?.tray_type ?? undefined,
- profile: filamentData.profile,
- color: filamentData.colorHex || '',
- location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
- },
- }),
- onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
- isAssigned: !!assignment || isBambuLabSpool(tray),
- };
- })()}
- configureSlot={{
- enabled: hasPermission('printers:control'),
- onConfigure: () => setConfigureSlotModal({
- amsId: ams.id,
- trayId: slotIdx,
- trayCount: ams.tray.length,
- trayType: tray?.tray_type || undefined,
- trayColor: tray?.tray_color || undefined,
- traySubBrands: tray?.tray_sub_brands || undefined,
- trayInfoIdx: tray?.tray_info_idx || undefined,
- extruderId: mappedExtruderId,
- caliIdx: tray?.cali_idx,
- savedPresetId: slotPreset?.preset_id,
- }),
- }}
- >
- {slotVisual}
- </FilamentHoverCard>
- ) : (
- <EmptySlotHoverCard
- kind={emptyKind ?? undefined}
- actions={renderAmsSlotActions({
- amsId: ams.id,
- slotId: slotIdx,
- loadTrayId: ams.id * 4 + slotIdx,
- isRefreshing,
- })}
- configureSlot={{
- enabled: hasPermission('printers:control'),
- onConfigure: () => setConfigureSlotModal({
- amsId: ams.id,
- trayId: slotIdx,
- trayCount: ams.tray.length,
- extruderId: mappedExtruderId,
- }),
- }}
- onAssignSpool={() => setAssignSpoolModal({
- printerId: printer.id,
- amsId: ams.id,
- trayId: slotIdx,
- trayInfo: {
- type: '',
- material: undefined,
- profile: '',
- color: '',
- location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
- },
- })}
- >
- {slotVisual}
- </EmptySlotHoverCard>
- )}
- </div>
- );
- })}
- </div>
- </div>
- );
- })}
- {/* HT AMS units */}
- {htAms.map((ams) => {
- const mappedExtruderId = amsExtruderMap[String(ams.id)];
- const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
- const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
- const isLeftNozzle = extruderId === 1;
- const isRightNozzle = extruderId === 0;
- const tray = ams.tray[0];
- const hasFillLevel = tray?.tray_type && tray.remain >= 0;
- const isEmpty = !tray?.tray_type;
- const emptyKind = getEmptySlotKind(tray);
- // Check if this is the currently loaded tray
- const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
- const isActive = effectiveTrayNow === globalTrayId;
- // Runout guidance (#2587): expected / ran-out slot on this HT unit.
- const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
- const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
- // Get cloud preset info if available
- const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
- // Get saved slot preset mapping (for user-configured slots)
- const slotPreset = slotPresets?.[globalTrayId];
- const htSlotId = tray?.id ?? 0;
- // Fill level fallback chain: Spoolman → Inventory → AMS remain
- const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
- const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
- const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
- const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
- const htInventoryFill = (() => {
- const sp = htInventoryAssignment?.spool;
- if (sp && sp.label_weight > 0 && sp.weight_used != null) {
- return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
- }
- return null;
- })();
- // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
- const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
- ? null : htInventoryFill;
- // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
- const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
- ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
- : undefined;
- const htSlotSpoolForFill = htSlotAssignmentForFill
- ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
- : undefined;
- const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
- ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
- : null;
- const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
- const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
- : htResolvedInventoryFill !== null ? 'inventory' as const
- : hasFillLevel ? 'ams' as const
- : undefined;
- // Build filament data for hover card
- const filamentData = tray?.tray_type ? {
- vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
- profile: slotPreset?.preset_name || (htSlotSpoolForFill ? [htSlotSpoolForFill.brand, htSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || htSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || htInventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
- colorName: getColorName(tray.tray_color || ''),
- colorHex: tray.tray_color || null,
- kFactor: formatKValue(tray.k),
- fillLevel: htEffectiveFill,
- trayUuid: tray.tray_uuid || null,
- tagUid: tray.tag_uid || null,
- fillSource: htFillSource,
- } : null;
- // Check if this specific slot is being refreshed
- const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
- refreshingSlot?.slotId === htSlotId;
- // #1762 (comment 2): active print-slot index for this HT slot.
- const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
- const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
- ? `P${htActivePrintSlotIdx + 1}`
- : null;
- // Slot visual content (goes inside hover card)
- const slotVisual = (
- <div
- className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
- isExpectedSlot
- ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
- : isRanOutSlot
- ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
- : isActive
- ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
- : ''
- }`}
- >
- {isExpectedSlot && (
- <span
- aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
- title={t('printers.expectedSlot.title')}
- 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"
- >
- ↓
- </span>
- )}
- {htActivePrintSlotLabel && (
- <span
- aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
- title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
- 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"
- >
- {htActivePrintSlotLabel}
- </span>
- )}
- {/* Filament color circle with 1-based slot number centered inside */}
- <FilamentSlotCircle
- trayColor={tray?.tray_color}
- trayType={tray?.tray_type}
- isEmpty={isEmpty}
- emptyKind={emptyKind}
- slotNumber={1}
- />
- <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
- {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
- </div>
- {/* Fill bar */}
- <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
- {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
- <div
- className="h-full rounded-full transition-all"
- style={{
- width: `${htEffectiveFill}%`,
- backgroundColor: getFillBarColor(htEffectiveFill),
- }}
- />
- )}
- </div>
- </div>
- );
- // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
- // like regular AMS), so they need more horizontal room than a 1-slot basis.
- // Without this override, the L view squishes HT into a sliver next to the
- // 4-slot AMS neighbors.
- // 11rem holds one slot plus the temperature/humidity
- // column beside it; both grow with the body scale.
- const htCardWidth = scaledRem(11);
- const htCardStyle: React.CSSProperties = {
- flex: `1 1 ${htCardWidth}`,
- minWidth: htCardWidth,
- // An AMS-HT is never wider than a full AMS. Without a
- // ceiling, a unit that wraps onto a line of its own is
- // the only flex item there and grow stretches its single
- // slot across the entire card, leaving the readings
- // stranded at the far edge.
- maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
- };
- return (
- <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
- {/* Row 1: Label + Nozzle + Drying */}
- <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
- {/* AMS name — hover to see serial, firmware, and edit friendly name */}
- <div className="flex min-w-0 flex-1 items-center gap-1.5">
- <AmsNameHoverCard
- ams={ams}
- printerId={printer.id}
- label={getAmsLabel(ams.id, ams.tray.length)}
- amsLabels={amsLabels}
- canEdit={hasPermission('printers:update')}
- onSaved={refetchAmsLabels}
- >
- <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
- {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
- </span>
- </AmsNameHoverCard>
- {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
- <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
- )}
- </div>
- {/* Drying button for HT AMS */}
- {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
- <div className="relative ml-auto">
- <button
- disabled={status.drying_screen_only}
- onClick={(e) => {
- if (ams.dry_time > 0) {
- stopDryingMutation.mutate(ams.id);
- } else if (dryingPopoverAmsId === ams.id) {
- setDryingPopoverAmsId(null);
- } else {
- const firstTray = ams.tray.find(t => t.tray_type);
- const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
- // Only reachable if a custom preset set dropped PLA itself.
- const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
- const moduleType = ams.module_type as 'n3f' | 'n3s';
- setDryingFilament(filType);
- setDryingTemp(preset[moduleType] || preset.n3f);
- setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
- setDryingRotateTray(false);
- setDryingPopoverModuleType(ams.module_type);
- setDryingPopoverAmsId(ams.id);
- const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
- setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
- }
- }}
- className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
- ams.dry_time > 0
- ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
- : status.drying_screen_only
- ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
- : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
- }`}
- title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
- >
- <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- </button>
- </div>
- )}
- </div>
- {/* HT AMS drying status bar */}
- {ams.dry_time > 0 && (
- <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
- <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
- {ams.dry_filament && (
- <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
- {ams.dry_target_temp != null
- ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
- : ams.dry_filament}
- </span>
- )}
- <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
- {ams.dry_time >= 60
- ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
- : `${ams.dry_time}m`}
- </span>
- {!status.drying_screen_only && (
- <button
- onClick={() => stopDryingMutation.mutate(ams.id)}
- disabled={stopDryingMutation.isPending}
- 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"
- title={t('printers.drying.stop')}
- >
- <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
- </button>
- )}
- </div>
- )}
- {/* Row 2: Slot (left) + Stats (right stacked) */}
- <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
- {/* Slot wrapper with loading overlay */}
- <div className="relative group flex-1" style={htSlotStyle}>
- {/* Loading overlay during RFID re-read */}
- {isHtRefreshing && (
- <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
- <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
- </div>
- )}
- {/* Hover card wraps only the visual content */}
- {filamentData ? (
- <FilamentHoverCard
- data={filamentData}
- actions={renderAmsSlotActions({
- amsId: ams.id,
- slotId: htSlotId,
- loadTrayId: ams.id * 4 + htSlotId,
- isRefreshing: isHtRefreshing,
- })}
- spoolman={{
- enabled: spoolmanEnabled,
- // #1457: slot assignment outranks tag-link (see top-level slot block).
- linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
- ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
- spoolmanUrl,
- syncMode: spoolmanSyncMode,
- // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
- onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
- const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
- setLinkSpoolModal({
- tagUid: filamentData.tagUid || linkTag,
- trayUuid: filamentData.trayUuid || '',
- printerId: printer.id,
- amsId: ams.id,
- trayId: htSlotId,
- });
- } : undefined,
- onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
- }}
- inventory={(() => {
- if (spoolmanEnabled) {
- if (spoolmanLoading) return undefined;
- const slotAssignment = htSlotAssignmentForFill;
- const spoolmanSpool = htSlotSpoolForFill;
- return {
- assignedSpool: spoolmanSpool ? {
- id: spoolmanSpool.id,
- material: spoolmanSpool.material,
- brand: spoolmanSpool.brand ?? null,
- color_name: spoolmanSpool.color_name ?? null,
- remainingWeightGrams: spoolmanSpool.label_weight
- ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
- : undefined,
- } : null,
- onAssignSpool: () => setAssignSpoolModal({
- printerId: printer.id,
- amsId: ams.id,
- trayId: htSlotId,
- trayInfo: {
- type: tray?.tray_type || filamentData.profile,
- material: tray?.tray_type ?? undefined,
- profile: filamentData.profile,
- color: filamentData.colorHex || '',
- location: getAmsLabel(ams.id, ams.tray.length),
- },
- }),
- onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
- isAssigned: !!slotAssignment || isBambuLabSpool(tray),
- };
- }
- const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
- return {
- assignedSpool: assignment?.spool ? {
- id: assignment.spool.id,
- material: assignment.spool.material,
- brand: assignment.spool.brand,
- color_name: assignment.spool.color_name,
- remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
- } : null,
- onAssignSpool: () => setAssignSpoolModal({
- printerId: printer.id,
- amsId: ams.id,
- trayId: htSlotId,
- trayInfo: {
- type: tray?.tray_type || filamentData.profile,
- material: tray?.tray_type ?? undefined,
- profile: filamentData.profile,
- color: filamentData.colorHex || '',
- location: getAmsLabel(ams.id, ams.tray.length),
- },
- }),
- onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
- isAssigned: !!assignment || isBambuLabSpool(tray),
- };
- })()}
- configureSlot={{
- enabled: hasPermission('printers:control'),
- onConfigure: () => setConfigureSlotModal({
- amsId: ams.id,
- trayId: htSlotId,
- trayCount: ams.tray.length,
- trayType: tray?.tray_type || undefined,
- trayColor: tray?.tray_color || undefined,
- traySubBrands: tray?.tray_sub_brands || undefined,
- trayInfoIdx: tray?.tray_info_idx || undefined,
- extruderId: mappedExtruderId,
- caliIdx: tray?.cali_idx,
- savedPresetId: slotPreset?.preset_id,
- }),
- }}
- >
- {slotVisual}
- </FilamentHoverCard>
- ) : (
- <EmptySlotHoverCard
- kind={emptyKind ?? undefined}
- actions={renderAmsSlotActions({
- amsId: ams.id,
- slotId: htSlotId,
- loadTrayId: ams.id * 4 + htSlotId,
- isRefreshing: isHtRefreshing,
- })}
- configureSlot={{
- enabled: hasPermission('printers:control'),
- onConfigure: () => setConfigureSlotModal({
- amsId: ams.id,
- trayId: htSlotId,
- trayCount: ams.tray.length,
- extruderId: mappedExtruderId,
- }),
- }}
- onAssignSpool={() => setAssignSpoolModal({
- printerId: printer.id,
- amsId: ams.id,
- trayId: htSlotId,
- trayInfo: {
- type: '',
- material: undefined,
- profile: '',
- color: '',
- location: getAmsLabel(ams.id, ams.tray.length),
- },
- })}
- >
- {slotVisual}
- </EmptySlotHoverCard>
- )}
- </div>
- {/* Stats stacked vertically: Temp on top, Humidity below */}
- {(ams.humidity != null || ams.temp != null) && (
- <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
- {ams.temp != null && (
- <TemperatureIndicator
- temp={ams.temp}
- goodThreshold={amsThresholds?.tempGood}
- fairThreshold={amsThresholds?.tempFair}
- onClick={() => setAmsHistoryModal({
- amsId: ams.id,
- amsLabel: getAmsLabel(ams.id, ams.tray.length),
- mode: 'temperature',
- })}
- compact
- />
- )}
- {ams.humidity != null && (
- <HumidityIndicator
- humidity={ams.humidity}
- goodThreshold={amsThresholds?.humidityGood}
- fairThreshold={amsThresholds?.humidityFair}
- onClick={() => setAmsHistoryModal({
- amsId: ams.id,
- amsLabel: getAmsLabel(ams.id, ams.tray.length),
- mode: 'humidity',
- })}
- compact
- />
- )}
- </div>
- )}
- </div>
- </div>
- );
- })}
- {/* External spool(s) - grouped in one card like regular AMS */}
- {status.vt_tray.length > 0 && showExternalSpool && (
- <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
- <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
- <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
- </div>
- <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
- {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
- const extTrayId = extTray.id ?? 254;
- // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
- // generically — use active_extruder to determine L vs R:
- // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
- const isExtActive = isDualNozzle && effectiveTrayNow === 254
- ? (extTrayId === 254 && status.active_extruder === 1) ||
- (extTrayId === 255 && status.active_extruder === 0)
- : effectiveTrayNow === extTrayId;
- const slotTrayId = extTrayId - 254; // 0 or 1
- const extLabel = isDualNozzle
- ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
- : '';
- const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
- const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
- const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
- const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
- const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
- const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
- const extInventoryFill = (() => {
- const sp = extInventoryAssignment?.spool;
- if (sp && sp.label_weight > 0 && sp.weight_used != null) {
- return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
- }
- return null;
- })();
- const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
- // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
- const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
- ? null : extInventoryFill;
- // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
- const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
- ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
- : undefined;
- const extSlotSpoolForFill = extSlotAssignmentForFill
- ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
- : undefined;
- const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
- ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
- : null;
- const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
- const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
- : extResolvedInventoryFill !== null ? 'inventory' as const
- : extHasFillLevel ? 'ams' as const
- : undefined;
- const extFilamentData = {
- vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
- profile: extSlotPreset?.preset_name || (extSlotSpoolForFill ? [extSlotSpoolForFill.brand, extSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || extSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || extInventoryAssignment?.spool?.slicer_filament_name || extCloudInfo?.name || extTray.tray_sub_brands || extTray.tray_type || 'Unknown',
- colorName: getColorName(extTray.tray_color || ''),
- colorHex: extTray.tray_color || null,
- kFactor: formatKValue(extTray.k),
- fillLevel: extEffectiveFill,
- trayUuid: extTray.tray_uuid || null,
- tagUid: extTray.tag_uid || null,
- fillSource: extFillSource,
- };
- const isEmpty = !extTray.tray_type;
- const emptyKind = getEmptySlotKind(extTray);
- const extSlotContent = (
- <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' : ''}`}>
- {/* Color circle: L/R inside on dual-nozzle external (replaces
- the separate Ext-L/Ext-R caption that made the row taller than
- regular AMS slots), 1-based slot number on single-nozzle. */}
- <FilamentSlotCircle
- trayColor={extTray.tray_color}
- trayType={extTray.tray_type}
- isEmpty={isEmpty}
- emptyKind={emptyKind}
- slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
- />
- <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
- {extTray.tray_type || t('ams.slotEmpty')}
- </div>
- <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
- {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
- <div
- className="h-full rounded-full transition-all"
- style={{
- width: `${extEffectiveFill}%`,
- backgroundColor: getFillBarColor(extEffectiveFill),
- }}
- />
- )}
- </div>
- </div>
- );
- return (
- <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
- {!isEmpty ? (
- <FilamentHoverCard
- data={extFilamentData}
- actions={renderAmsSlotActions({
- amsId: 255,
- slotId: slotTrayId,
- loadTrayId: extTrayId,
- includeRfid: false,
- })}
- spoolman={{
- enabled: spoolmanEnabled,
- // #1457: slot assignment outranks tag-link (see top-level slot block).
- linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
- ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
- spoolmanUrl,
- syncMode: spoolmanSyncMode,
- // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
- onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
- const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
- setLinkSpoolModal({
- tagUid: extFilamentData.tagUid || linkTag,
- trayUuid: extFilamentData.trayUuid || '',
- printerId: printer.id,
- amsId: 255,
- trayId: slotTrayId,
- });
- } : undefined,
- onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
- }}
- inventory={(() => {
- if (spoolmanEnabled) {
- if (spoolmanLoading) return undefined;
- const slotAssignment = extSlotAssignmentForFill;
- const spoolmanSpool = extSlotSpoolForFill;
- return {
- assignedSpool: spoolmanSpool ? {
- id: spoolmanSpool.id,
- material: spoolmanSpool.material,
- brand: spoolmanSpool.brand ?? null,
- color_name: spoolmanSpool.color_name ?? null,
- remainingWeightGrams: spoolmanSpool.label_weight
- ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
- : undefined,
- } : null,
- onAssignSpool: () => setAssignSpoolModal({
- printerId: printer.id,
- amsId: 255,
- trayId: slotTrayId,
- trayInfo: {
- type: extTray.tray_type || extFilamentData.profile,
- material: extTray.tray_type ?? undefined,
- profile: extFilamentData.profile,
- color: extFilamentData.colorHex || '',
- location: extLabel || t('printers.external'),
- },
- }),
- onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
- isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
- };
- }
- const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
- return {
- assignedSpool: assignment?.spool ? {
- id: assignment.spool.id,
- material: assignment.spool.material,
- brand: assignment.spool.brand,
- color_name: assignment.spool.color_name,
- remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
- } : null,
- onAssignSpool: () => setAssignSpoolModal({
- printerId: printer.id,
- amsId: 255,
- trayId: slotTrayId,
- trayInfo: {
- type: extTray.tray_type || extFilamentData.profile,
- material: extTray.tray_type ?? undefined,
- profile: extFilamentData.profile,
- color: extFilamentData.colorHex || '',
- location: extLabel || t('printers.external'),
- },
- }),
- onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
- isAssigned: !!assignment || isBambuLabSpool(extTray),
- };
- })()}
- configureSlot={{
- enabled: hasPermission('printers:control'),
- onConfigure: () => setConfigureSlotModal({
- amsId: 255,
- trayId: slotTrayId,
- trayCount: 1,
- trayType: extTray.tray_type || undefined,
- trayColor: extTray.tray_color || undefined,
- traySubBrands: extTray.tray_sub_brands || undefined,
- trayInfoIdx: extTray.tray_info_idx || undefined,
- extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
- caliIdx: extTray.cali_idx,
- savedPresetId: extSlotPreset?.preset_id,
- }),
- }}
- >
- {extSlotContent}
- </FilamentHoverCard>
- ) : (
- <EmptySlotHoverCard
- kind={emptyKind ?? undefined}
- actions={renderAmsSlotActions({
- amsId: 255,
- slotId: slotTrayId,
- loadTrayId: extTrayId,
- includeRfid: false,
- })}
- configureSlot={{
- enabled: hasPermission('printers:control'),
- onConfigure: () => setConfigureSlotModal({
- amsId: 255,
- trayId: slotTrayId,
- trayCount: 1,
- extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
- }),
- }}
- onAssignSpool={() => setAssignSpoolModal({
- printerId: printer.id,
- amsId: 255,
- trayId: slotTrayId,
- trayInfo: {
- type: '',
- material: undefined,
- profile: '',
- color: '',
- location: `External Slot ${slotTrayId + 1}`,
- },
- })}
- >
- {extSlotContent}
- </EmptySlotHoverCard>
- )}
- </div>
- );
- })}
- </div>
- </div>
- )}
- </div>
- </div>
- );
- })()}
- </>
- )}
- {/* Bottom block (power row + action bar). Wrapped together so the
- power row hugs the action bar at the card bottom instead of
- floating up when there's less filament content above. */}
- {viewMode === 'expanded' && (
- <div className="mt-auto">
- {smartPlug && (
- <div className="pt-3">
- <div className="flex items-center gap-2 mb-2">
- <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
- {t('printers.power', 'Power')}
- </span>
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
- </div>
- <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
- {/* Plug name + current power */}
- <div className="flex items-center gap-2 min-w-0 pl-1">
- <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
- <span className="text-sm text-white truncate">{smartPlug.name}</span>
- <span
- 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"
- title={t('smartPlugs.power')}
- >
- {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
- </span>
- </div>
- {/* Spacer */}
- <div className="flex-1" />
- <div className="flex items-center gap-2">
- {/* Auto-off */}
- <button
- onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
- disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
- title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
- 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 ${
- !hasPermission('smart_plugs:control')
- ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
- : smartPlug.auto_off || smartPlug.auto_off_executed
- ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
- : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
- }`}
- >
- <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- <button
- onClick={() => {
- if (plugStatus?.state === 'ON') {
- setShowPowerOffConfirm(true);
- } else {
- setShowPowerOnConfirm(true);
- }
- }}
- disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
- 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 ${
- !hasPermission('smart_plugs:control')
- ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
- : plugStatus?.state === 'ON'
- ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
- : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
- }`}
- title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
- >
- <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </button>
- </div>
- </div>
- {/* HA entity buttons row */}
- {scriptPlugs && scriptPlugs.length > 0 && (
- <div className="flex items-center gap-2 mt-2">
- <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
- <span className="text-xs text-bambu-gray">HA:</span>
- <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
- <div className="flex flex-wrap gap-1">
- {scriptPlugs.map(script => {
- const isScript = script.ha_entity_id?.startsWith('script.');
- return (
- <button
- key={script.id}
- onClick={() => {
- if (isScript) {
- runScriptMutation.mutate({ id: script.id, action: 'on' });
- } else {
- setHaToggleConfirm(script);
- }
- }}
- disabled={runScriptMutation.isPending}
- title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
- 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"
- >
- <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
- {script.name}
- </button>
- );
- })}
- </div>
- </div>
- )}
- </div>
- )}
- {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
- a printer can have an enclosure door contact without having a plug,
- and nesting it there would hide the row on exactly those setups. */}
- <PrinterHASensorRow printerId={printer.id} />
- {/* Connection Info & Actions */}
- <div className="pt-4">
- <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
- <div className="flex items-center justify-between gap-2">
- {printerActionsMenu}
- <div className="flex items-center justify-end gap-2 flex-wrap">
- {/* Camera Button */}
- <Button
- variant="secondary"
- size="sm"
- onClick={() => {
- if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
- onOpenEmbeddedCamera(printer.id, printer.name);
- } else {
- // Use saved window state or defaults
- const saved = localStorage.getItem('cameraWindowState');
- const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
- const features = [
- `width=${state.width}`,
- `height=${state.height}`,
- state.left !== undefined ? `left=${state.left}` : '',
- state.top !== undefined ? `top=${state.top}` : '',
- // No `noopener`: same-origin popup needs opener so the browser
- // copies sessionStorage (auth token) into the new window.
- 'menubar=no,toolbar=no,location=no,status=no',
- ].filter(Boolean).join(',');
- window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
- }
- }}
- disabled={!status?.connected || !hasPermission('camera:view')}
- title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
- className={footerIconButtonClass}
- >
- <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </Button>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowFileManager(true)}
- disabled={!isConnected || !hasPermission('printers:files')}
- title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
- className={footerIconButtonClass}
- >
- <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- </Button>
- {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
- <Button
- size="sm"
- onClick={() => setShowUploadForPrint(true)}
- disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
- title={
- !hasPermission('library:upload')
- ? t('fileManager.noPermissionUpload')
- : !hasPermission('queue:create')
- ? t('fileManager.noPermissionAddToQueue')
- : t('common.print')
- }
- className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
- >
- <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
- {t('common.print')}
- </Button>
- )}
- </div>
- </div>
- </div>
- </div>
- )}
- </CardContent>
- {/* File Manager Modal */}
- {showFileManager && (
- <FileManagerModal
- printerId={printer.id}
- printerName={printer.name}
- onClose={() => setShowFileManager(false)}
- />
- )}
- {/* Upload for Print Modal */}
- {showUploadForPrint && (
- <FileUploadModal
- folderId={null}
- onClose={() => setShowUploadForPrint(false)}
- onUploadComplete={() => {}}
- autoUpload
- accept=".gcode,.3mf"
- validateFile={(file) => {
- const lower = file.name.toLowerCase();
- if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
- return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
- }
- }}
- onFileUploaded={(uploadedFile) => {
- // Check printer compatibility if sliced_for_model is available in metadata
- const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
- const printerModel = mapModelCode(printer.model);
- if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
- api.deleteLibraryFile(uploadedFile.id).catch(() => {});
- return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
- }
- setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
- }}
- />
- )}
- {/* Print Modal (after upload) */}
- {printAfterUpload && (
- <PrintModal
- mode="create"
- libraryFileId={printAfterUpload.id}
- archiveName={printAfterUpload.filename}
- initialSelectedPrinterIds={[printer.id]}
- onClose={() => setPrintAfterUpload(null)}
- onSuccess={() => setPrintAfterUpload(null)}
- cleanupLibraryAfterDispatch
- />
- )}
- {/* MQTT Debug Modal */}
- {showMQTTDebug && (
- <MQTTDebugModal
- printerId={printer.id}
- printerName={printer.name}
- onClose={() => setShowMQTTDebug(false)}
- />
- )}
- {showDiagnostic && (
- <ConnectionDiagnosticModal
- printerId={printer.id}
- printerName={printer.name}
- onClose={() => setShowDiagnostic(false)}
- />
- )}
- {showPrinterInfo && (
- <PrinterInfoModal
- printer={printer}
- status={status}
- totalPrintHours={maintenanceInfo?.total_print_hours}
- onClose={closePrinterInfo}
- />
- )}
- {/* Plate Check Result Modal */}
- {plateCheckResult && (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
- <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
- <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
- <div className="flex items-center gap-2">
- {plateCheckResult.needs_calibration ? (
- <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
- ) : plateCheckResult.is_empty ? (
- <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
- ) : (
- <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
- )}
- <h2 className="text-lg font-semibold text-white">
- Build Plate Check
- </h2>
- {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
- <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
- {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
- </span>
- )}
- </div>
- <button
- onClick={() => closePlateCheckModal()}
- className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
- >
- <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
- </button>
- </div>
- <div className="p-4 space-y-4">
- {plateCheckResult.needs_calibration ? (
- <>
- <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
- <p className="font-medium text-blue-700 dark:text-blue-400">
- {t('printers.plateDetection.calibrationRequired')}
- </p>
- <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
- </div>
- <div className="text-sm text-bambu-gray space-y-2">
- <p>{t('printers.plateDetection.calibrationDescription')}</p>
- <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
- </div>
- </>
- ) : (
- <>
- <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'}`}>
- <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
- {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
- </p>
- <p className="text-sm text-bambu-gray mt-1">
- {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
- </p>
- </div>
- {plateCheckResult.debug_image_url && (
- <div>
- <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
- <img
- src={plateCheckResult.debug_image_url}
- alt={t('printers.plateDetection.analysisPreview')}
- className="w-full rounded-lg border border-bambu-dark-tertiary"
- />
- <p className="text-xs text-bambu-gray mt-2">
- {t('printers.plateDetection.analysisLegend')}
- </p>
- </div>
- )}
- <p className="text-xs text-bambu-gray">
- {plateCheckResult.message}
- </p>
- </>
- )}
- {/* Saved References Grid */}
- {plateReferences && plateReferences.references.length > 0 && (
- <div className="mt-4">
- <div className="flex items-center gap-2 mb-2">
- <p className="text-sm font-medium text-white shrink-0">
- {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
- </p>
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
- </div>
- <div className="grid grid-cols-5 gap-2">
- {plateReferences.references.map((ref) => (
- <div key={ref.index} className="relative group">
- <img
- src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
- alt={ref.label || `Reference ${ref.index + 1}`}
- className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
- />
- {/* Delete button */}
- <button
- onClick={() => handleDeleteRef(ref.index)}
- className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
- title={t('printers.plateDetection.deleteReference')}
- >
- <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
- </button>
- {/* Label */}
- {editingRefLabel?.index === ref.index ? (
- <input
- type="text"
- value={editingRefLabel.label}
- onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
- onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
- if (e.key === 'Escape') setEditingRefLabel(null);
- }}
- className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
- autoFocus
- placeholder={t('printers.plateDetection.labelPlaceholder')}
- />
- ) : (
- <p
- className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
- onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
- title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
- >
- {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
- </p>
- )}
- {/* Timestamp */}
- <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
- {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
- </p>
- </div>
- ))}
- </div>
- </div>
- )}
- {/* ROI Editor */}
- {!plateCheckResult.needs_calibration && (
- <div className="mt-4">
- <div className="flex items-center justify-between mb-2">
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
- <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
- </div>
- {!editingRoi ? (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
- >
- <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
- {t('common.edit')}
- </Button>
- ) : (
- <div className="flex gap-1">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setEditingRoi(null)}
- disabled={isSavingRoi}
- >
- {t('common.cancel')}
- </Button>
- <Button
- size="sm"
- onClick={handleSaveRoi}
- disabled={isSavingRoi}
- >
- {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
- </Button>
- </div>
- )}
- </div>
- {editingRoi ? (
- <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
- <div className="grid grid-cols-2 gap-3">
- <div>
- <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
- <input
- type="range"
- min="0"
- max="0.9"
- step="0.01"
- value={editingRoi.x}
- onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
- className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
- />
- <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
- </div>
- <div>
- <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
- <input
- type="range"
- min="0"
- max="0.9"
- step="0.01"
- value={editingRoi.y}
- onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
- className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
- />
- <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
- </div>
- <div>
- <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
- <input
- type="range"
- min="0.1"
- max="1"
- step="0.01"
- value={editingRoi.w}
- onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
- className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
- />
- <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
- </div>
- <div>
- <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
- <input
- type="range"
- min="0.1"
- max="1"
- step="0.01"
- value={editingRoi.h}
- onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
- className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
- />
- <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
- </div>
- </div>
- <p className="text-xs text-bambu-gray">
- {t('printers.roi.instruction')}
- </p>
- </div>
- ) : (
- <p className="text-xs text-bambu-gray">
- Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
- W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
- </p>
- )}
- </div>
- )}
- </div>
- <div className="flex justify-end gap-2 p-4">
- {plateCheckResult.needs_calibration ? (
- <>
- <Button variant="ghost" onClick={() => closePlateCheckModal()}>
- {t('common.cancel')}
- </Button>
- <Button
- onClick={() => handleCalibratePlate()}
- disabled={isCalibrating}
- >
- {isCalibrating ? (
- <>
- <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
- Calibrating...
- </>
- ) : (
- 'Calibrate Empty Plate'
- )}
- </Button>
- </>
- ) : (
- <>
- <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
- {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
- </Button>
- <Button onClick={() => closePlateCheckModal()}>
- Close
- </Button>
- </>
- )}
- </div>
- </div>
- </div>
- )}
- {/* Power On Confirmation */}
- {showPowerOnConfirm && smartPlug && (
- <ConfirmModal
- title={t('printers.confirm.powerOnTitle')}
- message={t('printers.confirm.powerOnMessage', { name: printer.name })}
- confirmText={t('printers.confirm.powerOnButton')}
- variant="default"
- onConfirm={() => {
- powerControlMutation.mutate('on');
- setShowPowerOnConfirm(false);
- }}
- onCancel={() => setShowPowerOnConfirm(false)}
- />
- )}
- {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
- disconnects MQTT, which stops progress tracking + completion
- notifications for the in-flight job. Idle / FINISH / FAILED states
- skip this dialog and toggle directly. */}
- {confirmMaintenanceEnter && (
- <ConfirmModal
- title={t('printers.maintenance.confirmMidPrintTitle')}
- message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
- confirmText={t('printers.maintenance.menuEnter')}
- variant="danger"
- onConfirm={() => {
- maintenanceMutation.mutate(false);
- setConfirmMaintenanceEnter(false);
- }}
- onCancel={() => setConfirmMaintenanceEnter(false)}
- />
- )}
- {/* Power Off Confirmation */}
- {showPowerOffConfirm && smartPlug && (
- <ConfirmModal
- title={t('printers.confirm.powerOffTitle')}
- message={
- status?.state === 'RUNNING'
- ? t('printers.confirm.powerOffWarning', { name: printer.name })
- : t('printers.confirm.powerOffMessage', { name: printer.name })
- }
- confirmText={t('printers.confirm.powerOffButton')}
- variant="danger"
- onConfirm={() => {
- powerControlMutation.mutate('off');
- setShowPowerOffConfirm(false);
- }}
- onCancel={() => setShowPowerOffConfirm(false)}
- />
- )}
- {/* HA entity toggle confirmation (Show on Printer Card switches) */}
- {haToggleConfirm && (
- <ConfirmModal
- title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
- message={
- status?.state === 'RUNNING'
- ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
- : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
- }
- confirmText={t('printers.confirm.haToggleButton')}
- variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
- onConfirm={() => {
- runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
- setHaToggleConfirm(null);
- }}
- onCancel={() => setHaToggleConfirm(null)}
- />
- )}
- {/* Stop Print Confirmation */}
- {showStopConfirm && (
- <ConfirmModal
- title={t('printers.confirm.stopTitle')}
- message={t('printers.confirm.stopMessage', { name: printer.name })}
- confirmText={t('printers.confirm.stopButton')}
- variant="danger"
- onConfirm={() => {
- stopPrintMutation.mutate();
- setShowStopConfirm(false);
- }}
- onCancel={() => setShowStopConfirm(false)}
- />
- )}
- {/* Pause Print Confirmation */}
- {showPauseConfirm && (
- <ConfirmModal
- title={t('printers.confirm.pauseTitle')}
- message={t('printers.confirm.pauseMessage', { name: printer.name })}
- confirmText={t('printers.confirm.pauseButton')}
- variant="default"
- onConfirm={() => {
- pausePrintMutation.mutate();
- setShowPauseConfirm(false);
- }}
- onCancel={() => setShowPauseConfirm(false)}
- />
- )}
- {/* Resume Print Confirmation */}
- {showResumeConfirm && (
- <ConfirmModal
- title={t('printers.confirm.resumeTitle')}
- message={t('printers.confirm.resumeMessage', { name: printer.name })}
- confirmText={t('printers.confirm.resumeButton')}
- variant="default"
- onConfirm={() => {
- resumePrintMutation.mutate();
- setShowResumeConfirm(false);
- }}
- onCancel={() => setShowResumeConfirm(false)}
- />
- )}
- {/* Skip Objects Modal */}
- <SkipObjectsModal
- printerId={printer.id}
- isOpen={showSkipObjectsModal}
- onClose={() => setShowSkipObjectsModal(false)}
- />
- {/* HMS Error Modal */}
- {showHMSModal && (
- <HMSErrorModal
- printerName={printer.name}
- errors={status?.hms_errors || []}
- onClose={() => setShowHMSModal(false)}
- printerId={printer.id}
- hasPermission={hasPermission}
- runoutGuidance={runoutGuidance}
- />
- )}
- {/* AI failure detection modal (#1546) */}
- {showAiModal && (
- <AiDetectionModal
- printerName={printer.name}
- detection={aiDetection}
- lastError={aiLastError}
- onClose={() => setShowAiModal(false)}
- />
- )}
- {/* AMS Filament Backup status / control modal (#1762) */}
- {amsBackupModalOpen && status && (
- <AmsBackupModal
- isOpen={amsBackupModalOpen}
- state={status.ams_filament_backup}
- amsUnits={status.ams}
- amsExtruderMap={status.ams_extruder_map}
- isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
- canToggle={hasPermission('printers:control')}
- pending={setAmsBackupMutation.isPending}
- onToggle={(next) => setAmsBackupMutation.mutate(next)}
- onClose={() => setAmsBackupModalOpen(false)}
- />
- )}
- {/* AMS History Modal */}
- {amsHistoryModal && (
- <AMSHistoryModal
- isOpen={!!amsHistoryModal}
- onClose={() => setAmsHistoryModal(null)}
- printerId={printer.id}
- printerName={printer.name}
- amsId={amsHistoryModal.amsId}
- amsLabel={amsHistoryModal.amsLabel}
- initialMode={amsHistoryModal.mode}
- thresholds={amsThresholds}
- />
- )}
- {/* Heater History Modal (nozzle / bed / chamber) */}
- {heaterHistoryModal && (
- <HeaterHistoryModal
- isOpen={!!heaterHistoryModal}
- onClose={() => setHeaterHistoryModal(null)}
- printerId={printer.id}
- printerName={printer.name}
- initialKind={heaterHistoryModal.initialKind}
- availableKinds={heaterHistoryModal.availableKinds}
- />
- )}
- {/* Link Spool Modal */}
- {linkSpoolModal && (
- <LinkSpoolModal
- isOpen={!!linkSpoolModal}
- onClose={() => setLinkSpoolModal(null)}
- tagUid={linkSpoolModal.tagUid}
- trayUuid={linkSpoolModal.trayUuid}
- printerId={linkSpoolModal.printerId}
- amsId={linkSpoolModal.amsId}
- trayId={linkSpoolModal.trayId}
- />
- )}
- {/* Assign Spool Modal */}
- {assignSpoolModal && (
- <AssignSpoolModal
- isOpen={!!assignSpoolModal}
- onClose={() => setAssignSpoolModal(null)}
- printerId={assignSpoolModal.printerId}
- amsId={assignSpoolModal.amsId}
- trayId={assignSpoolModal.trayId}
- trayInfo={assignSpoolModal.trayInfo}
- spoolmanEnabled={!!spoolmanEnabled}
- />
- )}
- {/* Configure AMS Slot Modal */}
- {configureSlotModal && (
- <ConfigureAmsSlotModal
- isOpen={!!configureSlotModal}
- onClose={() => setConfigureSlotModal(null)}
- printerId={printer.id}
- slotInfo={configureSlotModal}
- printerModel={mapModelCode(printer.model) || undefined}
- nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
- onSuccess={() => {
- // Refresh slot presets to show updated profile name
- queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
- // Printer status will update automatically via WebSocket when AMS data changes
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- }}
- />
- )}
- {/* Edit Printer Modal */}
- {showEditModal && (
- <EditPrinterModal
- printer={printer}
- onClose={() => setShowEditModal(false)}
- />
- )}
- {/* Firmware Update Modal */}
- {showFirmwareModal && firmwareInfo && (
- <FirmwareUpdateModal
- printer={printer}
- firmwareInfo={firmwareInfo}
- onClose={() => setShowFirmwareModal(false)}
- />
- )}
- {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
- {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
- const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
- const sliderMin = 35;
- const sliderMax = maxTemp + 10;
- return (
- <>
- {/* Backdrop */}
- <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
- {/* Popover */}
- <div
- className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
- style={{
- top: dryingPopoverPos.top,
- left: dryingPopoverPos.left,
- // Cap to the space between the popover's top and the bottom
- // viewport margin (8px, matching computePopoverPosition's
- // margin). When the popover is taller than that space — short
- // viewport, landscape phone, zoomed-in — the body scrolls and
- // the footer stays pinned, so the Start button is always
- // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
- // Safari's bottom toolbar overlay doesn't clip the footer
- // (#1669, iPhone 17 Safari).
- maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
- }}
- onClick={e => e.stopPropagation()}
- >
- {/* Header */}
- <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
- <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
- <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
- </div>
- <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
- {/* Body */}
- <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
- {/* Filament type select */}
- <div>
- <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
- <ToolbarDropdown
- value={dryingFilament}
- options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
- onChange={fil => {
- setDryingFilament(fil);
- const preset = dryingPresets[fil];
- if (preset) {
- const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
- setDryingTemp(preset[key]);
- setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
- }
- }}
- fullWidth
- />
- </div>
- {/* Temperature */}
- <div>
- <div className="flex items-center justify-between mb-1">
- <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
- <div className="flex items-center gap-1">
- <input
- type="number"
- min={45}
- max={maxTemp}
- value={dryingTemp}
- onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
- 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"
- />
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
- </div>
- </div>
- <input
- type="range"
- min={sliderMin}
- max={sliderMax}
- value={dryingTemp}
- onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
- className="w-full h-1 accent-bambu-green cursor-pointer"
- />
- <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
- <span>45°C</span>
- <span>{maxTemp}°C</span>
- </div>
- </div>
- {/* Duration */}
- <div>
- <div className="flex items-center justify-between mb-1">
- <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
- <div className="flex items-center gap-1">
- <input
- type="number"
- min={1}
- max={24}
- value={dryingDuration}
- onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
- 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"
- />
- <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
- </div>
- </div>
- <input
- type="range"
- min={1}
- max={24}
- value={dryingDuration}
- onChange={e => setDryingDuration(Number(e.target.value))}
- className="w-full h-1 accent-bambu-green cursor-pointer"
- />
- <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
- <span>1h</span>
- <span>24h</span>
- </div>
- </div>
- {/* Rotate tray — disabled when any tray in THIS AMS has its
- filament threaded out into the feed tube. The whole AMS
- rotates as one mechanism (all 4 spools turn together), so a
- single loaded slot locks the entire unit. Bambu per-tray
- `state`: 9 = empty, 10 = spool present but not loaded
- (rotation possible), 11 = loaded into tube (rotation impossible).
- Catches both mid-print (active feed) AND idle-with-threaded-
- filament — the H2D's post-print state leaves filament in the
- tube but tray_now resets to 255, which a tray_now-only check
- would silently miss. */}
- {(() => {
- const targetAms = dryingPopoverAmsId !== null
- ? amsData.find(a => a.id === dryingPopoverAmsId)
- : undefined;
- const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
- tray => tray.state === 11,
- );
- const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
- return (
- <button
- type="button"
- onClick={() => setDryingRotateTray(enabled => !enabled)}
- aria-pressed={rotateChecked}
- disabled={trayLoadedInThisAms}
- title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
- className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
- rotateChecked
- ? 'bg-bambu-green border-bambu-green text-white'
- : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
- }`}
- >
- {t('printers.drying.rotateTray')}
- </button>
- );
- })()}
- </div>
- <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
- {/* Footer */}
- <div className="shrink-0 px-3 pt-2.5 pb-3">
- <button
- onClick={() => {
- if (dryingPopoverAmsId !== null) {
- // Clamp rotateTray off when any tray in this AMS is loaded into
- // the tube — the rotate UI is disabled there, but the state may
- // linger as `true` from a previous AMS, or a print may have
- // started while the popover was open. Without this clamp the
- // Start payload would carry rotate_tray=true and firmware would
- // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
- const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
- const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
- tray => tray.state === 11,
- );
- startDryingMutation.mutate({
- amsId: dryingPopoverAmsId,
- temp: dryingTemp,
- duration: dryingDuration,
- filament: dryingFilament,
- rotateTray: dryingRotateTray && !trayLoadedInThisAms,
- });
- }
- }}
- disabled={startDryingMutation.isPending}
- data-testid="drying-start-confirm"
- 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"
- >
- {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
- </button>
- </div>
- </div>
- </>
- );
- })()}
- </Card>
- );
- }
- export function AddPrinterModal({
- onClose,
- onAdd,
- existingSerials,
- }: {
- onClose: () => void;
- onAdd: (data: PrinterCreate) => void;
- existingSerials: string[];
- }) {
- const { t } = useTranslation();
- const [form, setForm] = useState<PrinterCreate>({
- name: '',
- serial_number: '',
- ip_address: '',
- access_code: '',
- model: '',
- location: '',
- auto_archive: true,
- });
- // Discovery state
- const [discovering, setDiscovering] = useState(false);
- const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
- const [discoveryError, setDiscoveryError] = useState('');
- const [hasScanned, setHasScanned] = useState(false);
- const [isDocker, setIsDocker] = useState(false);
- const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
- const [subnet, setSubnet] = useState('');
- // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
- // text input so users can scan a subnet Bambuddy isn't directly on
- // (printer behind a router on a different L3 segment — SSDP multicast
- // won't cross that boundary, only an active unicast scan will). #1564
- const [customSubnet, setCustomSubnet] = useState('');
- const [useCustomSubnet, setUseCustomSubnet] = useState(false);
- const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
- const [showDiagnostic, setShowDiagnostic] = useState(false);
- // Setup-time pre-flight: run the connection diagnostic on save and warn
- // (not block) when checks fail, so the user doesn't add a printer that
- // immediately shows offline. checkingSave = probe in flight; saveWarning =
- // failed result awaiting an explicit "save anyway".
- const [checkingSave, setCheckingSave] = useState(false);
- const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
- // Fetch discovery info on mount + restore the last custom CIDR the user
- // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
- // time they open this modal).
- useEffect(() => {
- discoveryApi.getInfo().then(info => {
- setIsDocker(info.is_docker);
- if (info.subnets.length > 0) {
- setDetectedSubnets(info.subnets);
- setSubnet(info.subnets[0]);
- }
- }).catch(() => {
- // Ignore errors, assume not Docker
- });
- try {
- const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
- if (saved) setCustomSubnet(saved);
- } catch {
- // localStorage unavailable (private mode, quota); recall is opportunistic
- }
- }, []);
- // Filter out already-added printers
- const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
- const handleAddSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- setCheckingSave(true);
- try {
- const result = await api.diagnoseConnection({
- ip_address: form.ip_address.trim(),
- serial_number: form.serial_number.trim() || undefined,
- access_code: form.access_code || undefined,
- });
- if (result.checks.some((c) => c.status === 'fail')) {
- setSaveWarning(result);
- return;
- }
- } catch {
- // Diagnostic infrastructure failed — never block the save on it.
- } finally {
- setCheckingSave(false);
- }
- onAdd(form);
- };
- const startDiscovery = async () => {
- setDiscoveryError('');
- setDiscovered([]);
- setDiscovering(true);
- setHasScanned(false);
- setScanProgress({ scanned: 0, total: 0 });
- // Native installs fall back to subnet scanning when the user picks
- // "Custom" — SSDP can't reach a printer on a different L3 segment
- // (#1564). Docker mode always uses subnet scan (multicast unavailable).
- const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
- const wantsSubnetScan = isDocker || useCustomSubnet;
- if (wantsSubnetScan && useCustomSubnet) {
- try {
- localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
- } catch {
- // localStorage write best-effort; user just retypes next time
- }
- }
- try {
- if (wantsSubnetScan) {
- await discoveryApi.startSubnetScan(scanCidr);
- // Poll for scan status and results
- const pollInterval = setInterval(async () => {
- try {
- const status = await discoveryApi.getScanStatus();
- setScanProgress({ scanned: status.scanned, total: status.total });
- const printers = await discoveryApi.getDiscoveredPrinters();
- setDiscovered(printers);
- if (!status.running) {
- clearInterval(pollInterval);
- setDiscovering(false);
- setHasScanned(true);
- }
- } catch (e) {
- console.error('Failed to get scan status:', e);
- }
- }, 500);
- } else {
- // Use SSDP discovery for native installs
- await discoveryApi.startDiscovery(10);
- // Poll for discovered printers every second
- const pollInterval = setInterval(async () => {
- try {
- const printers = await discoveryApi.getDiscoveredPrinters();
- setDiscovered(printers);
- } catch (e) {
- console.error('Failed to get discovered printers:', e);
- }
- }, 1000);
- // Stop after 10 seconds
- setTimeout(async () => {
- clearInterval(pollInterval);
- try {
- await discoveryApi.stopDiscovery();
- } catch {
- // Ignore stop errors
- }
- setDiscovering(false);
- setHasScanned(true);
- // Final fetch
- try {
- const printers = await discoveryApi.getDiscoveredPrinters();
- setDiscovered(printers);
- } catch (e) {
- console.error('Failed to get final discovered printers:', e);
- }
- }, 10000);
- }
- } catch (e) {
- console.error('Failed to start discovery:', e);
- setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
- setDiscovering(false);
- setHasScanned(true);
- }
- };
- // Reuse module-level mapModelCode
- const selectPrinter = (printer: DiscoveredPrinter) => {
- // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
- const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
- setForm({
- ...form,
- name: printer.name || '',
- serial_number: serialNumber,
- ip_address: printer.ip_address,
- model: mapModelCode(printer.model),
- });
- // Clear discovery results after selection
- setDiscovered([]);
- };
- // Cleanup discovery on unmount
- useEffect(() => {
- return () => {
- discoveryApi.stopDiscovery().catch(() => {});
- discoveryApi.stopSubnetScan().catch(() => {});
- };
- }, []);
- // Close on Escape key
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape') onClose();
- };
- window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
- }, [onClose]);
- return (
- <>
- <div
- className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
- onClick={onClose}
- >
- <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
- <CardContent>
- <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
- {/* Discovery Section */}
- <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
- {/* Subnet picker — always visible. The dropdown lists detected
- interface subnets and a "Custom..." sentinel that reveals
- a CIDR text input for printers on a different L3 segment
- (router, VLAN, etc.). #1564 */}
- <div className="mb-3">
- <label className="block text-sm text-bambu-gray mb-1">
- {t('printers.discovery.subnetToScan')}
- </label>
- {detectedSubnets.length > 0 ? (
- <select
- 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"
- value={useCustomSubnet ? '__custom__' : subnet}
- onChange={(e) => {
- if (e.target.value === '__custom__') {
- setUseCustomSubnet(true);
- } else {
- setUseCustomSubnet(false);
- setSubnet(e.target.value);
- }
- }}
- disabled={discovering}
- >
- {detectedSubnets.map(s => (
- <option key={s} value={s}>{s}</option>
- ))}
- <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
- </select>
- ) : (
- <input
- type="text"
- 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"
- value={subnet}
- onChange={(e) => setSubnet(e.target.value)}
- placeholder="192.168.1.0/24"
- disabled={discovering}
- />
- )}
- {useCustomSubnet && (
- <input
- type="text"
- aria-label={t('printers.discovery.customSubnetLabel')}
- 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"
- value={customSubnet}
- onChange={(e) => setCustomSubnet(e.target.value)}
- placeholder="10.1.1.0/24"
- disabled={discovering}
- />
- )}
- <p className="mt-1 text-xs text-bambu-gray">
- {isDocker
- ? t('printers.discovery.dockerNote')
- : t('printers.discovery.customSubnetNote')}
- </p>
- </div>
- <Button
- type="button"
- variant="secondary"
- onClick={startDiscovery}
- disabled={discovering}
- className="w-full"
- >
- {discovering ? (
- <>
- <Loader2 className="w-4 h-4 animate-spin" />
- {(isDocker || useCustomSubnet) && scanProgress.total > 0
- ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
- : t('printers.discovery.scanning')}
- </>
- ) : (
- <>
- <Search className="w-4 h-4" />
- {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
- </>
- )}
- </Button>
- {discoveryError && (
- <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
- )}
- {newPrinters.length > 0 && (
- <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
- {newPrinters.map((printer) => (
- <div
- key={printer.serial}
- className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
- onClick={() => selectPrinter(printer)}
- >
- <div className="min-w-0 flex-1">
- <p className="font-medium text-white text-sm truncate">
- {printer.name || printer.serial}
- </p>
- <p className="text-xs text-bambu-gray truncate">
- {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
- {printer.serial.startsWith('unknown-') && (
- <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
- )}
- </p>
- </div>
- <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
- </div>
- ))}
- </div>
- )}
- {discovering && (
- <p className="mt-2 text-sm text-bambu-gray text-center">
- {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
- </p>
- )}
- {hasScanned && !discovering && discovered.length === 0 && (
- <p className="mt-2 text-sm text-bambu-gray text-center">
- {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
- </p>
- )}
- {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
- <p className="mt-2 text-sm text-bambu-gray text-center">
- {t('printers.discovery.allConfigured')}
- </p>
- )}
- </div>
- <form onSubmit={handleAddSubmit} className="space-y-4">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
- <input
- type="text"
- required
- 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"
- value={form.name}
- onChange={(e) => setForm({ ...form, name: e.target.value })}
- placeholder={t('printers.modal.myPrinter')}
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
- <input
- type="text"
- required
- 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])?)*)"
- 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"
- value={form.ip_address}
- onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
- placeholder="192.168.1.100 or printer.local"
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
- <input
- type="text"
- required
- 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"
- value={form.serial_number}
- onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
- placeholder="01P00A000000000"
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
- <input
- type="password"
- required
- 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"
- value={form.access_code}
- onChange={(e) => setForm({ ...form, access_code: e.target.value })}
- placeholder={t('printers.modal.fromPrinterSettings')}
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
- <select
- 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"
- value={form.model || ''}
- onChange={(e) => setForm({ ...form, model: e.target.value })}
- >
- <option value="">{t('printers.modal.selectModel')}</option>
- <optgroup label="A1 Series">
- <option value="A1">A1</option>
- <option value="A1 Mini">A1 Mini</option>
- </optgroup>
- <optgroup label="A2 Series">
- <option value="A2L">A2L</option>
- </optgroup>
- <optgroup label="H2 Series">
- <option value="H2C">H2C</option>
- <option value="H2D">H2D</option>
- <option value="H2D Pro">H2D Pro</option>
- <option value="H2S">H2S</option>
- </optgroup>
- <optgroup label="P Series">
- <option value="P1P">P1P</option>
- <option value="P1S">P1S</option>
- <option value="P2S">P2S</option>
- </optgroup>
- <optgroup label="X1 Series">
- <option value="X1">X1</option>
- <option value="X1C">X1 Carbon</option>
- <option value="X1E">X1E</option>
- </optgroup>
- <optgroup label="X2 Series">
- <option value="X2D">X2D</option>
- </optgroup>
- </select>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
- <input
- type="text"
- 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"
- value={form.location || ''}
- onChange={(e) => setForm({ ...form, location: e.target.value })}
- placeholder={t('printers.modal.locationPlaceholder')}
- />
- <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
- </div>
- <div className="flex items-center gap-2">
- <input
- type="checkbox"
- id="auto_archive"
- checked={form.auto_archive}
- onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
- className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
- />
- <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
- {t('printers.modal.autoArchiveLabel')}
- </label>
- </div>
- <button
- type="button"
- onClick={() => setShowDiagnostic(true)}
- disabled={!form.ip_address.trim()}
- 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"
- >
- <Stethoscope className="w-4 h-4" />
- {t('diagnostic.runButton')}
- </button>
- {saveWarning ? (
- <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">
- <div className="flex items-start gap-2">
- <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
- <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
- </div>
- <DiagnosticChecklist result={saveWarning} />
- <div className="flex gap-3">
- <Button
- type="button"
- variant="secondary"
- onClick={() => setSaveWarning(null)}
- className="flex-1"
- >
- {t('printers.addPreflight.back')}
- </Button>
- <Button type="button" onClick={() => onAdd(form)} className="flex-1">
- {t('printers.addPreflight.saveAnyway')}
- </Button>
- </div>
- </div>
- ) : (
- <div className="flex gap-3 pt-2">
- <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
- {t('common.cancel')}
- </Button>
- <Button type="submit" disabled={checkingSave} className="flex-1">
- {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
- </Button>
- </div>
- )}
- </form>
- </CardContent>
- </Card>
- </div>
- {showDiagnostic && (
- <ConnectionDiagnosticModal
- connection={{
- ip_address: form.ip_address.trim(),
- serial_number: form.serial_number.trim() || undefined,
- access_code: form.access_code || undefined,
- }}
- printerName={form.name || null}
- onClose={() => setShowDiagnostic(false)}
- />
- )}
- </>
- );
- }
- function FirmwareUpdateModal({
- printer,
- firmwareInfo,
- onClose,
- }: {
- printer: Printer;
- firmwareInfo: FirmwareUpdateInfo;
- onClose: () => void;
- }) {
- const { t } = useTranslation();
- const queryClient = useQueryClient();
- const { showToast } = useToast();
- const { hasPermission } = useAuth();
- const canUpdate = hasPermission('firmware:update');
- const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
- const [isUploading, setIsUploading] = useState(false);
- const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
- const [selectedVersion, setSelectedVersion] = useState<string | null>(
- firmwareInfo.update_available ? firmwareInfo.latest_version : null,
- );
- // Prepare check query — runs when a version is selected and user can update
- const { data: prepareInfo, isLoading: isPreparing } = useQuery({
- queryKey: ['firmwarePrepare', printer.id, selectedVersion],
- queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
- staleTime: 30000,
- enabled: !!selectedVersion && canUpdate && !isUploading,
- });
- // Start upload mutation
- const uploadMutation = useMutation({
- mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
- onSuccess: () => {
- setIsUploading(true);
- // Start polling for status
- const interval = setInterval(async () => {
- try {
- const status = await firmwareApi.getUploadStatus(printer.id);
- setUploadStatus(status);
- if (status.status === 'complete' || status.status === 'error') {
- clearInterval(interval);
- setPollInterval(null);
- setIsUploading(false);
- if (status.status === 'complete') {
- showToast(t('printers.firmwareModal.uploadedToast'), 'success');
- queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
- }
- }
- } catch {
- // Ignore errors during polling
- }
- }, 2000);
- setPollInterval(interval);
- },
- onError: (error: Error) => {
- showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
- setIsUploading(false);
- },
- });
- // Cleanup on unmount
- useEffect(() => {
- return () => {
- if (pollInterval) clearInterval(pollInterval);
- };
- }, [pollInterval]);
- const handleStartUpload = () => {
- setUploadStatus(null);
- uploadMutation.mutate();
- };
- return (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
- <Card className="w-full max-w-md mx-4">
- <CardContent>
- <div className="flex items-start gap-3 mb-4">
- <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
- {firmwareInfo.update_available
- ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
- : <CheckCircle className="w-5 h-5 text-status-ok" />}
- </div>
- <div className="flex-1">
- <h3 className="text-lg font-semibold text-white">
- {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
- </h3>
- <p className="text-sm text-bambu-gray mt-1">
- {printer.name}
- </p>
- </div>
- </div>
- {/* Version Info */}
- {(() => {
- const selectedEntry = selectedVersion
- ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
- : null;
- const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
- const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
- const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
- return (
- <div className="bg-bambu-dark rounded-lg p-3 mb-4">
- <div className="flex justify-between items-center text-sm">
- <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
- <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
- {firmwareInfo.current_version || t('common.unknown')}
- </span>
- </div>
- {showSecondLine && (
- <div className="flex justify-between items-center text-sm mt-1">
- <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
- <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
- </div>
- )}
- {displayNotes && (
- <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
- <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
- {t('printers.firmwareModal.releaseNotes')}
- </summary>
- <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
- {displayNotes}
- </div>
- </details>
- )}
- </div>
- );
- })()}
- {/* Available versions list */}
- {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
- <div className="mb-4">
- <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
- <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
- {firmwareInfo.available_versions.map((v) => {
- const isCurrent = firmwareInfo.current_version === v.version;
- const isSelected = selectedVersion === v.version;
- const cmp = firmwareInfo.current_version
- ? compareFwVersions(v.version, firmwareInfo.current_version)
- : 0;
- const relLabel = isCurrent
- ? t('printers.firmwareModal.currentBadge')
- : cmp > 0
- ? t('printers.firmwareModal.newerBadge')
- : t('printers.firmwareModal.olderBadge');
- const relClass = isCurrent
- ? 'text-bambu-gray'
- : cmp > 0
- ? 'text-orange-700 dark:text-orange-400'
- : 'text-blue-700 dark:text-blue-400';
- return (
- <button
- key={v.version}
- type="button"
- disabled={!v.file_available || !canUpdate || isCurrent}
- onClick={() => setSelectedVersion(v.version)}
- className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
- isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
- } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
- >
- <div className="flex items-center gap-2 min-w-0">
- <span className="font-mono text-white">{v.version}</span>
- <span className={`text-xs ${relClass}`}>{relLabel}</span>
- </div>
- <span className={`text-xs px-2 py-0.5 rounded-full ${
- isCurrent
- ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
- : v.file_available
- ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
- : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
- }`}>
- {isCurrent
- ? t('printers.firmwareModal.installed')
- : v.file_available
- ? t('printers.firmwareModal.usable')
- : t('printers.firmwareModal.unavailable')}
- </span>
- </button>
- );
- })}
- </div>
- </div>
- )}
- {/* Status / Progress (only when a version is selected) */}
- {!selectedVersion ? null : isPreparing ? (
- <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
- <Loader2 className="w-4 h-4 animate-spin" />
- {t('printers.firmwareModal.checkingPrereqs')}
- </div>
- ) : prepareInfo && !isUploading && !uploadStatus ? (
- <div className="mb-4">
- {prepareInfo.can_proceed ? (
- <div className="flex items-center gap-2 text-bambu-green text-sm">
- <Box className="w-4 h-4" />
- {t('printers.firmwareModal.sdCardReady')}
- </div>
- ) : (
- <div className="space-y-1">
- {prepareInfo.errors.map((error, i) => (
- <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
- <AlertCircle className="w-4 h-4 flex-shrink-0" />
- {error}
- </div>
- ))}
- </div>
- )}
- </div>
- ) : null}
- {/* Upload Progress */}
- {(isUploading || uploadStatus) && uploadStatus && (
- <div className="mb-4">
- <div className="flex items-center justify-between text-sm mb-1">
- <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
- <span className="text-white">{uploadStatus.progress}%</span>
- </div>
- <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
- <div
- className={`h-2 rounded-full transition-all ${
- uploadStatus.status === 'error' ? 'bg-status-error' :
- uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
- } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
- style={{ width: `${uploadStatus.progress}%` }}
- />
- </div>
- <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
- {uploadStatus.error && (
- <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
- )}
- </div>
- )}
- {/* Success Message */}
- {uploadStatus?.status === 'complete' && (
- <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
- <p className="text-sm text-bambu-green font-medium mb-2">
- {t('printers.firmwareModal.uploadedSuccess')}
- </p>
- <p className="text-xs text-bambu-gray">
- {t('printers.firmwareModal.applyInstructions')}
- </p>
- <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
- <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
- <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
- <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
- <li>{t('printers.firmwareModal.step4')}</li>
- </ol>
- </div>
- )}
- {/* Buttons */}
- <div className="flex gap-2 justify-end">
- <Button variant="secondary" onClick={onClose}>
- {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
- </Button>
- {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
- <Button
- onClick={handleStartUpload}
- disabled={uploadMutation.isPending}
- >
- {uploadMutation.isPending ? (
- <>
- <Loader2 className="w-4 h-4 animate-spin mr-2" />
- {t('printers.firmwareModal.starting')}
- </>
- ) : (
- <>
- <Download className="w-4 h-4 mr-2" />
- {t('printers.firmwareModal.uploadFirmware')}
- </>
- )}
- </Button>
- )}
- </div>
- </CardContent>
- </Card>
- </div>
- );
- }
- function EditPrinterModal({
- printer,
- onClose,
- }: {
- printer: Printer;
- onClose: () => void;
- }) {
- const { t } = useTranslation();
- const queryClient = useQueryClient();
- const { showToast } = useToast();
- const [form, setForm] = useState({
- name: printer.name,
- ip_address: printer.ip_address,
- access_code: '',
- model: printer.model || '',
- location: printer.location || '',
- auto_archive: printer.auto_archive,
- is_active: printer.is_active,
- });
- // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
- // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
- const [checkingSave, setCheckingSave] = useState(false);
- const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
- const updateMutation = useMutation({
- mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['printers'] });
- queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
- onClose();
- },
- onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
- });
- // Close on Escape key
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape') onClose();
- };
- window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
- }, [onClose]);
- const doSave = () => {
- const data: Partial<PrinterCreate> = {
- name: form.name,
- ip_address: form.ip_address,
- model: form.model || undefined,
- location: form.location || undefined,
- auto_archive: form.auto_archive,
- is_active: form.is_active,
- };
- // Only include access_code if it was changed
- if (form.access_code) {
- data.access_code = form.access_code;
- }
- updateMutation.mutate(data);
- };
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- setCheckingSave(true);
- try {
- const result = await api.diagnoseConnection({
- ip_address: form.ip_address.trim(),
- serial_number: printer.serial_number,
- access_code: form.access_code || undefined,
- });
- if (result.checks.some((c) => c.status === 'fail')) {
- setSaveWarning(result);
- return;
- }
- } catch {
- // Diagnostic infrastructure failed — never block the save on it.
- } finally {
- setCheckingSave(false);
- }
- doSave();
- };
- return (
- <div
- className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
- onClick={onClose}
- >
- <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
- <CardContent>
- <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
- <form onSubmit={handleSubmit} className="space-y-4">
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
- <input
- type="text"
- required
- 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"
- value={form.name}
- onChange={(e) => setForm({ ...form, name: e.target.value })}
- placeholder={t('printers.modal.myPrinter')}
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
- <input
- type="text"
- required
- 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])?)*)"
- 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"
- value={form.ip_address}
- onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
- placeholder="192.168.1.100 or printer.local"
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
- <input
- type="text"
- disabled
- className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
- value={printer.serial_number}
- />
- <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
- <input
- type="password"
- 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"
- value={form.access_code}
- onChange={(e) => setForm({ ...form, access_code: e.target.value })}
- placeholder={t('printers.accessCodePlaceholder')}
- />
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
- <select
- 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"
- value={form.model}
- onChange={(e) => setForm({ ...form, model: e.target.value })}
- >
- <option value="">{t('printers.modal.selectModel')}</option>
- <optgroup label="A1 Series">
- <option value="A1">A1</option>
- <option value="A1 Mini">A1 Mini</option>
- </optgroup>
- <optgroup label="A2 Series">
- <option value="A2L">A2L</option>
- </optgroup>
- <optgroup label="H2 Series">
- <option value="H2C">H2C</option>
- <option value="H2D">H2D</option>
- <option value="H2D Pro">H2D Pro</option>
- <option value="H2S">H2S</option>
- </optgroup>
- <optgroup label="P Series">
- <option value="P1P">P1P</option>
- <option value="P1S">P1S</option>
- <option value="P2S">P2S</option>
- </optgroup>
- <optgroup label="X1 Series">
- <option value="X1">X1</option>
- <option value="X1C">X1 Carbon</option>
- <option value="X1E">X1E</option>
- </optgroup>
- <optgroup label="X2 Series">
- <option value="X2D">X2D</option>
- </optgroup>
- </select>
- </div>
- <div>
- <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
- <input
- type="text"
- 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"
- value={form.location}
- onChange={(e) => setForm({ ...form, location: e.target.value })}
- placeholder={t('printers.modal.locationPlaceholder')}
- />
- <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
- </div>
- <div className="flex items-center gap-2">
- <input
- type="checkbox"
- id="edit_auto_archive"
- checked={form.auto_archive}
- onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
- className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
- />
- <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
- {t('printers.modal.autoArchiveLabel')}
- </label>
- </div>
- {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
- is_active because the user-facing concept is "is this printer
- in maintenance" not "is it active". */}
- <div>
- <div className="flex items-center gap-2">
- <input
- type="checkbox"
- id="edit_maintenance_mode"
- checked={!form.is_active}
- onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
- className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
- />
- <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
- <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
- {t('printers.maintenance.editFieldLabel')}
- </label>
- </div>
- <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
- {t('printers.maintenance.editFieldHelp')}
- </p>
- </div>
- {saveWarning ? (
- <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">
- <div className="flex items-start gap-2">
- <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
- <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
- </div>
- <DiagnosticChecklist result={saveWarning} />
- <div className="flex gap-3">
- <Button
- type="button"
- variant="secondary"
- onClick={() => setSaveWarning(null)}
- className="flex-1"
- >
- {t('printers.addPreflight.back')}
- </Button>
- <Button
- type="button"
- onClick={doSave}
- className="flex-1"
- disabled={updateMutation.isPending}
- >
- {t('printers.addPreflight.saveAnyway')}
- </Button>
- </div>
- </div>
- ) : (
- <div className="flex gap-3 pt-4">
- <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
- {t('common.cancel')}
- </Button>
- <Button
- type="submit"
- className="flex-1"
- disabled={updateMutation.isPending || checkingSave}
- >
- {checkingSave
- ? t('printers.addPreflight.checking')
- : updateMutation.isPending
- ? t('common.saving')
- : t('printers.modal.saveChanges')}
- </Button>
- </div>
- )}
- </form>
- </CardContent>
- </Card>
- </div>
- );
- }
- // Component to check if a printer is offline (for power dropdown)
- function usePrinterOfflineStatus(printerId: number) {
- const { data: status } = useQuery({
- queryKey: ['printerStatus', printerId],
- queryFn: () => api.getPrinterStatus(printerId),
- refetchInterval: 30000,
- });
- return !status?.connected;
- }
- // Power dropdown item for an offline printer
- function PowerDropdownItem({
- printer,
- plug,
- onPowerOn,
- isPowering,
- }: {
- printer: Printer;
- plug: { id: number; name: string };
- onPowerOn: (plugId: number) => void;
- isPowering: boolean;
- }) {
- const isOffline = usePrinterOfflineStatus(printer.id);
- // Fetch plug status
- const { data: plugStatus } = useQuery({
- queryKey: ['smartPlugStatus', plug.id],
- queryFn: () => api.getSmartPlugStatus(plug.id),
- refetchInterval: 10000,
- });
- // Only show if printer is offline
- if (!isOffline) {
- return null;
- }
- return (
- <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
- <div className="flex items-center gap-2 min-w-0">
- <span className="text-sm text-white truncate">{printer.name}</span>
- {plugStatus && (
- <span
- className={`text-xs px-1.5 py-0.5 rounded ${
- plugStatus.state === 'ON'
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
- }`}
- >
- {plugStatus.state || '?'}
- </span>
- )}
- </div>
- <button
- onClick={() => onPowerOn(plug.id)}
- disabled={isPowering || plugStatus?.state === 'ON'}
- className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
- plugStatus?.state === 'ON'
- ? 'bg-bambu-green/20 text-bambu-green cursor-default'
- : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
- }`}
- >
- <Power className="w-3 h-3" />
- {isPowering ? '...' : 'On'}
- </button>
- </div>
- );
- }
- export function PrintersPage() {
- const { t } = useTranslation();
- const { resolvedMode, darkAccent, lightAccent } = useTheme();
- const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
- const accentButtonClass = {
- green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
- teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
- blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
- orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
- purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
- red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
- }[activeAccent];
- const [showAddModal, setShowAddModal] = useState(false);
- const [hideDisconnected, setHideDisconnected] = useState(() => {
- return localStorage.getItem('hideDisconnectedPrinters') === 'true';
- });
- const [showPowerDropdown, setShowPowerDropdown] = useState(false);
- const [poweringOn, setPoweringOn] = useState<number | null>(null);
- const [sortBy, setSortBy] = useState<SortOption>(() => {
- return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
- });
- const [sortAsc, setSortAsc] = useState<boolean>(() => {
- return localStorage.getItem('printerSortAsc') !== 'false';
- });
- // Card size: 1=small, 2=medium, 3=large, 4=xl
- const [cardSize, setCardSize] = useState<number>(() => {
- const saved = localStorage.getItem('printerCardSize');
- return saved ? parseInt(saved, 10) : 2; // Default to medium
- });
- // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
- const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
- return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
- });
- // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
- // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
- const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
- const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
- return Number.isFinite(saved) && saved > 0 ? saved : 4;
- });
- const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
- const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
- return Number.isFinite(saved) && saved > 0 ? saved : 8;
- });
- // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
- // 'full' adds progress, layer, and time-left on printing/paused tiles.
- // Defaulting to 'full' because the cards already show this info — users who
- // pick cam-wall view still want to glance the same details without flipping.
- const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
- const saved = localStorage.getItem('camWallStatusMode');
- return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
- });
- // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
- const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
- const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
- const scrollPrinterIntoView = useCallback((printerId: number) => {
- requestAnimationFrame(() => {
- requestAnimationFrame(() => {
- const card = document.getElementById(`printer-card-${printerId}`);
- if (!card) return;
- const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
- const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
- window.scrollTo({
- top: Math.max(0, top),
- behavior: 'smooth',
- });
- });
- });
- }, []);
- const openCompactCard = useCallback((printerId: number) => {
- setCompactDrilldownPrinterId(printerId);
- setCardSize(2);
- localStorage.setItem('printerCardSize', '2');
- scrollPrinterIntoView(printerId);
- }, [scrollPrinterIntoView]);
- const returnToCompactCards = useCallback(() => {
- const printerId = compactDrilldownPrinterId;
- setCompactDrilldownPrinterId(null);
- setCardSize(1);
- localStorage.setItem('printerCardSize', '1');
- if (printerId != null) {
- scrollPrinterIntoView(printerId);
- }
- }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
- const [search, setSearch] = useState('');
- // Both filters persist like every other preference on this page (#2833).
- // `search` deliberately does not: a box that silently refills itself on
- // return is more surprising than a dropdown that remembers.
- const [statusFilter, setStatusFilter] = useState<string>(() => {
- // Validated on read: a value the dropdown no longer offers would filter
- // every printer out, and nothing would explain why.
- const saved = localStorage.getItem('printerStatusFilter');
- return isKnownStatusFilter(saved) ? (saved as string) : 'all';
- });
- const [locationFilter, setLocationFilter] = useState<string>(
- () => localStorage.getItem('printerLocationFilter') || 'all'
- );
- const [statusCacheVersion, setStatusCacheVersion] = useState(0);
- const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
- try {
- const saved = localStorage.getItem('printerCollapsedSections');
- return saved ? JSON.parse(saved) : {};
- } catch { return {}; }
- });
- const queryClient = useQueryClient();
- const { showToast } = useToast();
- const { hasPermission } = useAuth();
- // Embedded camera viewer state - supports multiple simultaneous viewers
- // Persisted to localStorage so cameras reopen after navigation
- const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
- // Initialize from localStorage if camera_view_mode is embedded
- const saved = localStorage.getItem('openEmbeddedCameras');
- if (saved) {
- try {
- const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
- return new Map(cameras.map(c => [c.id, c]));
- } catch {
- return new Map();
- }
- }
- return new Map();
- });
- // Persist open cameras to localStorage when they change
- useEffect(() => {
- const cameras = Array.from(embeddedCameraPrinters.values());
- if (cameras.length > 0) {
- localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
- } else {
- localStorage.removeItem('openEmbeddedCameras');
- }
- }, [embeddedCameraPrinters]);
- const { data: printers, isLoading } = useQuery({
- queryKey: ['printers'],
- queryFn: api.getPrinters,
- });
- // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
- // so users with printers:read but no settings:read still get the values needed
- // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
- const { data: settings } = useQuery({
- queryKey: ['ui-preferences'],
- queryFn: api.getUiPreferences,
- });
- // Parse user-configured temperature/fan presets once, with defensive fallback
- // to built-in defaults on parse failure (validators on the backend already
- // reject malformed writes, so this is just forward-compat).
- const effectiveNozzleTempPresets = useMemo(
- () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
- [settings?.nozzle_temp_presets],
- );
- const effectiveBedTempPresets = useMemo(
- () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
- [settings?.bed_temp_presets],
- );
- const effectiveChamberTempPresets = useMemo(
- () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
- [settings?.chamber_temp_presets],
- );
- const effectiveFanSpeedPresets = useMemo(
- () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
- [settings?.fan_speed_presets],
- );
- // Compute drying presets: user-configured (from settings) merged over built-in defaults
- const effectiveDryingPresets = useMemo(() => {
- if (settings?.drying_presets) {
- try {
- const userPresets = JSON.parse(settings.drying_presets);
- if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
- return { ...DRYING_PRESETS, ...userPresets };
- }
- } catch { /* ignore parse errors, use defaults */ }
- }
- return DRYING_PRESETS;
- }, [settings?.drying_presets]);
- // Close embedded cameras if mode changes to 'window'
- useEffect(() => {
- if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
- setEmbeddedCameraPrinters(new Map());
- }
- }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
- // Fetch all smart plugs to know which printers have them
- const { data: smartPlugs } = useQuery({
- queryKey: ['smart-plugs'],
- queryFn: api.getSmartPlugs,
- });
- // Fetch maintenance overview for all printers to show badges
- const { data: maintenanceOverview } = useQuery({
- queryKey: ['maintenanceOverview'],
- queryFn: api.getMaintenanceOverview,
- staleTime: 60 * 1000, // 1 minute
- });
- // Live AI failure detection state for the card badges (#1546). Matches the
- // 10s refetch of the Failure Detection settings panel.
- const { data: obicoPrinterStatus } = useQuery({
- queryKey: ['obico-printer-status'],
- queryFn: api.getObicoPrinterStatus,
- refetchInterval: 10000,
- });
- // Badge visibility: detection enabled AND this printer in the monitored set
- // (monitored_printers null = all). Live per-print state is passed separately.
- const isAiMonitored = useCallback(
- (printerId: number) =>
- obicoPrinterStatus?.enabled === true &&
- (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
- [obicoPrinterStatus],
- );
- // Fetch Spoolman status to enable link spool feature
- const { data: spoolmanStatus } = useQuery({
- queryKey: ['spoolman-status'],
- queryFn: api.getSpoolmanStatus,
- staleTime: 60 * 1000, // 1 minute
- });
- const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
- // Fetch Spoolman settings to get sync mode
- const { data: spoolmanSettings } = useQuery({
- queryKey: ['spoolman-settings'],
- queryFn: api.getSpoolmanSettings,
- enabled: !!spoolmanEnabled,
- staleTime: 60 * 1000, // 1 minute
- });
- const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
- // Fetch unlinked spools to know if link button should be enabled
- const { data: unlinkedSpools } = useQuery({
- queryKey: ['unlinked-spools'],
- queryFn: api.getUnlinkedSpools,
- enabled: !!spoolmanEnabled,
- staleTime: 30 * 1000, // 30 seconds
- });
- const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
- // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
- const { data: linkedSpoolsData } = useQuery({
- queryKey: ['linked-spools'],
- queryFn: api.getLinkedSpools,
- enabled: !!spoolmanEnabled,
- staleTime: 30 * 1000, // 30 seconds
- });
- const linkedSpools = linkedSpoolsData?.linked;
- // Fetch spool assignments for inventory feature
- const { data: spoolAssignments } = useQuery({
- queryKey: ['spool-assignments'],
- queryFn: () => api.getAssignments(),
- enabled: hasPermission('inventory:view_assignments'),
- staleTime: 30 * 1000,
- });
- const unassignMutation = useMutation({
- mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
- api.unassignSpool(printerId, amsId, trayId),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
- },
- });
- const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
- queryKey: ['spoolman-inventory-spools'],
- queryFn: () => api.getSpoolmanInventorySpools(false),
- enabled: !!spoolmanEnabled,
- staleTime: 30 * 1000,
- });
- const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
- queryKey: ['spoolman-slot-assignments'],
- queryFn: () => api.getSpoolmanSlotAssignments(),
- enabled: !!spoolmanEnabled,
- staleTime: 30 * 1000,
- });
- const unassignSpoolmanMutation = useMutation({
- mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
- queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
- },
- });
- // Helper to find assignment for a specific slot
- const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
- return spoolAssignments?.find(
- (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
- );
- };
- // Create a map of printer_id -> maintenance info for quick lookup
- const maintenanceByPrinter = maintenanceOverview?.reduce(
- (acc, overview) => {
- acc[overview.printer_id] = {
- due_count: overview.due_count,
- warning_count: overview.warning_count,
- total_print_hours: overview.total_print_hours,
- };
- return acc;
- },
- {} as Record<number, PrinterMaintenanceInfo>
- ) || {};
- // Create a map of printer_id -> smart plug
- const smartPlugByPrinter = smartPlugs?.reduce(
- (acc, plug) => {
- if (plug.printer_id) {
- acc[plug.printer_id] = plug;
- }
- return acc;
- },
- {} as Record<number, typeof smartPlugs[0]>
- ) || {};
- const addMutation = useMutation({
- mutationFn: api.createPrinter,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['printers'] });
- queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
- setShowAddModal(false);
- },
- onError: (error: Error) => {
- // Localized message when the backend returns a stable error code;
- // the raw message is an English fallback for non-UI clients.
- if (error instanceof ApiError && error.code === 'printer_connection_failed') {
- showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
- return;
- }
- showToast(error.message || t('printers.toast.failedToAdd'), 'error');
- },
- });
- const powerOnMutation = useMutation({
- mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
- setPoweringOn(null);
- },
- onError: () => {
- setPoweringOn(null);
- },
- });
- // Bulk selection state
- const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
- const [isSelectionMode, setIsSelectionMode] = useState(false);
- const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
- const [bulkActionPending, setBulkActionPending] = useState(false);
- const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
- const toggleSelect = useCallback((id: number) => {
- setSelectedPrinterIds(prev => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
- }, []);
- const clearSelection = useCallback(() => {
- setSelectedPrinterIds(new Set());
- setIsSelectionMode(false);
- }, []);
- // Escape key exits selection mode
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape' && selectionMode) {
- clearSelection();
- }
- };
- window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
- }, [selectionMode, clearSelection]);
- const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
- setBulkActionPending(true);
- const ids = Array.from(selectedPrinterIds);
- // Filter to only applicable printers based on cached state
- const applicableIds = ids.filter(id => {
- const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
- if (!status?.connected) return false;
- switch (action) {
- case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
- case 'pause': return status.state === 'RUNNING';
- case 'resume': return status.state === 'PAUSE';
- case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
- case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
- default: return false;
- }
- });
- if (applicableIds.length === 0) {
- showToast(t('printers.bulk.noneApplicable'), 'error');
- setBulkActionPending(false);
- setBulkConfirmAction(null);
- return;
- }
- const apiCall = {
- stop: api.stopPrint,
- pause: api.pausePrint,
- resume: api.resumePrint,
- clearPlate: api.clearPlate,
- clearHMS: api.clearHMSErrors,
- }[action];
- const results = await Promise.allSettled(
- applicableIds.map(id => apiCall(id))
- );
- const succeeded = results.filter(r => r.status === 'fulfilled').length;
- const failed = results.filter(r => r.status === 'rejected').length;
- if (failed === 0) {
- showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
- } else {
- showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
- }
- // Invalidate status queries for affected printers
- applicableIds.forEach(id => {
- queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
- });
- setBulkActionPending(false);
- setBulkConfirmAction(null);
- }, [selectedPrinterIds, queryClient, showToast, t]);
- const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
- // Actions that need confirmation
- if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
- setBulkConfirmAction(action);
- } else {
- executeBulkAction(action);
- }
- }, [executeBulkAction]);
- const toggleHideDisconnected = () => {
- const newValue = !hideDisconnected;
- setHideDisconnected(newValue);
- localStorage.setItem('hideDisconnectedPrinters', String(newValue));
- };
- const handleSortChange = (newSort: SortOption) => {
- setSortBy(newSort);
- localStorage.setItem('printerSortBy', newSort);
- };
- const handleStatusFilterChange = (value: string) => {
- setStatusFilter(value);
- localStorage.setItem('printerStatusFilter', value);
- };
- const handleLocationFilterChange = (value: string) => {
- setLocationFilter(value);
- localStorage.setItem('printerLocationFilter', value);
- };
- const toggleSortDirection = () => {
- const newAsc = !sortAsc;
- setSortAsc(newAsc);
- localStorage.setItem('printerSortAsc', String(newAsc));
- };
- // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
- const getGridClasses = () => {
- switch (cardSize) {
- 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
- case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
- case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
- case 4: return 'grid-cols-1'; // XL: single column, full width
- default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
- }
- };
- const cardSizeLabels = ['S', 'M', 'L', 'XL'];
- // Increment version counter whenever a printer status cache entry is updated so
- // filteredPrinters re-computes reactively on WebSocket-driven status changes.
- useEffect(() => {
- const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
- if (
- event.type === 'updated' &&
- Array.isArray(event.query.queryKey) &&
- event.query.queryKey[0] === 'printerStatus'
- ) {
- setStatusCacheVersion(v => v + 1);
- }
- });
- return unsubscribe;
- }, [queryClient]);
- // Filter printers by search term, status, and location
- const filteredPrinters = useMemo(() => {
- if (!printers) return [];
- let result = printers;
- // Text search
- if (search.trim()) {
- const q = search.trim().toLowerCase();
- result = result.filter(p =>
- p.name.toLowerCase().includes(q) ||
- (p.model || '').toLowerCase().includes(q) ||
- (p.location || '').toLowerCase().includes(q) ||
- (p.serial_number || '').toLowerCase().includes(q)
- );
- }
- // Location filter
- if (locationFilter !== 'all') {
- result = result.filter(p => (p.location || '') === locationFilter);
- }
- // Status filter
- if (statusFilter !== 'all') {
- result = result.filter(p => {
- const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
- if (!status?.connected) return statusFilter === 'offline';
- const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
- switch (statusFilter) {
- case 'printing': return status.state === 'RUNNING';
- case 'paused': return status.state === 'PAUSE';
- case 'finished': return status.state === 'FINISH';
- case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
- case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
- case 'offline': return false; // Connected printers are never offline
- default: return true;
- }
- });
- }
- return result;
- // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
- }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
- // Derive unique locations for the location filter dropdown
- const availableLocations = useMemo(() => {
- if (!printers) return [];
- return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
- }, [printers]);
- // A saved location can outlive what it matched -- renamed, cleared, or the
- // only printer that had it deleted. The dropdown is rendered only while some
- // printer has a location, so a stale one would hide every printer *and* the
- // control to undo it, leaving an empty page and no way back (#2833).
- // Deliberately waits for `printers`: it is undefined while the query is in
- // flight, and acting on the empty list that produces would throw the saved
- // filter away every time the page loads.
- useEffect(() => {
- if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
- setLocationFilter('all');
- localStorage.setItem('printerLocationFilter', 'all');
- }, [printers, availableLocations, locationFilter]);
- // Sort printers based on selected option
- const sortedPrinters = useMemo(() => {
- const sorted = [...filteredPrinters];
- switch (sortBy) {
- case 'name':
- sorted.sort((a, b) => a.name.localeCompare(b.name));
- break;
- case 'model':
- sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
- break;
- case 'location':
- // Sort by location, with ungrouped printers last
- sorted.sort((a, b) => {
- const locA = a.location || '';
- const locB = b.location || '';
- if (!locA && locB) return 1;
- if (locA && !locB) return -1;
- return locA.localeCompare(locB) || a.name.localeCompare(b.name);
- });
- break;
- case 'status':
- // Sort by status: HMS errors > printing > idle > offline
- sorted.sort((a, b) => {
- const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
- const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
- const getPriority = (s: typeof statusA) => {
- if (!s?.connected) return 3; // offline
- const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
- if (hmsErrors.length > 0) return 0; // HMS errors - top priority
- if (s.state === 'RUNNING') return 1; // printing
- return 2; // idle
- };
- return getPriority(statusA) - getPriority(statusB);
- });
- break;
- case 'eta':
- sorted.sort((a, b) => {
- const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
- const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
- const tier = (s: typeof statusA) => {
- if (!s?.connected) return 3; // offline last
- if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
- if (s.state === 'RUNNING') return 1; // printing without ETA
- return 2; // idle
- };
- const ta = tier(statusA);
- const tb = tier(statusB);
- if (ta !== tb) return ta - tb;
- if (ta === 0) {
- const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
- if (diff !== 0) return diff;
- }
- return a.name.localeCompare(b.name);
- });
- break;
- }
- // Apply ascending/descending
- if (!sortAsc) {
- sorted.reverse();
- }
- return sorted;
- }, [filteredPrinters, sortBy, sortAsc, queryClient]);
- const selectAll = useCallback(() => {
- setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
- setIsSelectionMode(true);
- }, [sortedPrinters]);
- const selectByState = useCallback((state: PrinterState) => {
- setSelectedPrinterIds(prev => {
- const next = new Set(prev);
- sortedPrinters.forEach(p => {
- const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
- if (classifyPrinterStatus(status) === state) next.add(p.id);
- });
- return next;
- });
- setIsSelectionMode(true);
- }, [sortedPrinters, queryClient]);
- const selectByLocation = useCallback((location: string) => {
- setSelectedPrinterIds(prev => {
- const next = new Set(prev);
- sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
- return next;
- });
- setIsSelectionMode(true);
- }, [sortedPrinters]);
- const selectByModel = useCallback((model: string) => {
- setSelectedPrinterIds(prev => {
- const next = new Set(prev);
- sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
- return next;
- });
- setIsSelectionMode(true);
- }, [sortedPrinters]);
- const toggleSectionCollapse = useCallback((key: string) => {
- setCollapsedSections(prev => {
- const next = { ...prev, [key]: !prev[key] };
- try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
- return next;
- });
- }, []);
- // Group printers when sorted by location, status, or model
- const groupedPrinters = useMemo(() => {
- if (sortBy === 'name' || sortBy === 'eta') return null;
- const groups: Record<string, typeof sortedPrinters> = {};
- if (sortBy === 'location') {
- sortedPrinters.forEach(printer => {
- const location = printer.location || 'Ungrouped';
- if (!groups[location]) groups[location] = [];
- groups[location].push(printer);
- });
- } else if (sortBy === 'model') {
- sortedPrinters.forEach(printer => {
- const model = printer.model || 'Unknown';
- if (!groups[model]) groups[model] = [];
- groups[model].push(printer);
- });
- } else if (sortBy === 'status') {
- sortedPrinters.forEach(printer => {
- const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
- const group = classifyPrinterStatus(status);
- if (!groups[group]) groups[group] = [];
- groups[group].push(printer);
- });
- }
- return groups;
- // 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
- }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
- const toolbarRef = useRef<HTMLDivElement>(null);
- const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
- const expandedToolbarWidthRef = useRef(0);
- const [compactToolbar, setCompactToolbar] = useState(false);
- const measureToolbar = useCallback(() => {
- const toolbar = toolbarRef.current;
- if (!toolbar) return;
- const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
- if (measuredControlsWidth) {
- expandedToolbarWidthRef.current = measuredControlsWidth;
- }
- const searchMinimumWidth = 220;
- const gapWidth = 8;
- const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
- setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
- }, []);
- const smartPlugCount = Object.keys(smartPlugByPrinter).length;
- useLayoutEffect(() => {
- measureToolbar();
- const toolbar = toolbarRef.current;
- if (!toolbar) return;
- if (typeof ResizeObserver === 'undefined') {
- window.addEventListener('resize', measureToolbar);
- return () => window.removeEventListener('resize', measureToolbar);
- }
- const resizeObserver = new ResizeObserver(() => measureToolbar());
- resizeObserver.observe(toolbar);
- window.addEventListener('resize', measureToolbar);
- return () => {
- resizeObserver.disconnect();
- window.removeEventListener('resize', measureToolbar);
- };
- }, [
- measureToolbar,
- printers?.length,
- availableLocations.length,
- hideDisconnected,
- smartPlugCount,
- ]);
- const renderFilterControls = (inMenu = false) => (
- <>
- {/* Status filter */}
- {printers && printers.length > 0 && (
- <ToolbarDropdown
- value={statusFilter}
- onChange={handleStatusFilterChange}
- fullWidth={inMenu}
- options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
- />
- )}
- {/* Location filter — only shown when at least one printer has a location */}
- {printers && printers.length > 0 && availableLocations.length > 0 && (
- <ToolbarDropdown
- value={locationFilter}
- onChange={handleLocationFilterChange}
- fullWidth={inMenu}
- options={[
- { value: 'all', label: t('printers.filter.allLocations') },
- ...availableLocations.map(loc => ({ value: loc, label: loc })),
- ]}
- />
- )}
- <button
- type="button"
- onClick={toggleHideDisconnected}
- aria-pressed={hideDisconnected}
- className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
- hideDisconnected
- ? 'bg-bambu-green border-bambu-green text-white'
- : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
- }`}
- >
- {t('printers.hideOffline')}
- </button>
- </>
- );
- const renderViewControls = (inMenu = false) => (
- <>
- {/* Sort dropdown */}
- <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
- <ToolbarDropdown<SortOption>
- value={sortBy}
- onChange={handleSortChange}
- fullWidth={inMenu}
- options={[
- { value: 'name', label: t('printers.sort.name') },
- { value: 'status', label: t('printers.sort.status') },
- { value: 'model', label: t('printers.sort.model') },
- { value: 'location', label: t('printers.sort.location') },
- { value: 'eta', label: t('printers.sort.eta') },
- ]}
- />
- <button
- onClick={toggleSortDirection}
- 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"
- title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
- >
- {sortAsc ? (
- <ArrowUp className="w-4 h-4 text-white" />
- ) : (
- <ArrowDown className="w-4 h-4 text-white" />
- )}
- </button>
- </div>
- {/* Page view toggle: Cards / Cam Wall */}
- <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
- <button
- type="button"
- onClick={() => {
- setPageView('cards');
- localStorage.setItem('printerPageView', 'cards');
- }}
- className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
- pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
- }`}
- title={t('printers.pageView.cards')}
- aria-pressed={pageView === 'cards'}
- >
- <LayoutGrid className="w-3.5 h-3.5" />
- {inMenu && <span>{t('printers.pageView.cards')}</span>}
- </button>
- <button
- type="button"
- onClick={() => {
- setPageView('camwall');
- localStorage.setItem('printerPageView', 'camwall');
- }}
- className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
- pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
- }`}
- title={t('printers.pageView.camWall')}
- aria-pressed={pageView === 'camwall'}
- disabled={!hasPermission('camera:view')}
- >
- <MonitorPlay className="w-3.5 h-3.5" />
- {inMenu && <span>{t('printers.pageView.camWall')}</span>}
- </button>
- </div>
- {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
- view, and the page a kiosk token points at. Only offered once the wall
- is the active view, so it doesn't compete with the toggle above. */}
- {pageView === 'camwall' && hasPermission('camera:view') && (
- <RouterLink
- to="/camwall"
- 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' : ''}`}
- title={t('printers.pageView.openCamWallPage')}
- >
- <ExternalLink className="w-3.5 h-3.5" />
- {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
- </RouterLink>
- )}
- {/* Card size selector */}
- <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' : ''}`}>
- {cardSizeLabels.map((label, index) => {
- const size = index + 1;
- const isSelected = cardSize === size;
- return (
- <button
- key={label}
- onClick={() => {
- setCompactDrilldownPrinterId(null);
- setCardSize(size);
- localStorage.setItem('printerCardSize', String(size));
- }}
- className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
- index === 0 ? 'rounded-l-lg' : ''
- } ${
- index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
- } ${
- isSelected
- ? 'bg-bambu-green text-white'
- : 'text-white hover:bg-bambu-dark-tertiary'
- }`}
- title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
- >
- {label}
- </button>
- );
- })}
- </div>
- </>
- );
- const renderActionControls = (inMenu = false) => (
- <>
- {/* Bulk select toggle */}
- <button
- onClick={() => {
- if (selectionMode) clearSelection();
- else setIsSelectionMode(true);
- }}
- 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' : ''} ${
- selectionMode
- ? 'bg-bambu-green border-bambu-green text-white'
- : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
- }`}
- title={t('printers.bulk.select')}
- disabled={!hasPermission('printers:control')}
- >
- <CheckSquare className="w-4 h-4" />
- {inMenu && <span>{t('printers.bulk.select')}</span>}
- </button>
- {/* Power dropdown for offline printers with smart plugs */}
- {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
- <div className={`relative ${inMenu ? 'w-full' : ''}`}>
- <button
- onClick={() => setShowPowerDropdown(!showPowerDropdown)}
- className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
- inMenu
- ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
- : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
- }`}
- >
- <span className="flex items-center gap-1.5">
- <Power className="w-4 h-4" />
- {t('printers.powerOn')}
- </span>
- <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
- </button>
- {showPowerDropdown && (
- <>
- {/* Backdrop to close dropdown */}
- <div
- className="fixed inset-0 z-10"
- onClick={() => setShowPowerDropdown(false)}
- />
- <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">
- <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">
- {t('printers.offlinePrintersWithPlugs')}
- </div>
- {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
- <PowerDropdownItem
- key={printer.id}
- printer={printer}
- plug={smartPlugByPrinter[printer.id]}
- onPowerOn={(plugId) => {
- setPoweringOn(plugId);
- powerOnMutation.mutate(plugId);
- }}
- isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
- />
- ))}
- {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
- <div className="px-3 py-2 text-sm text-bambu-gray">
- No printers with smart plugs
- </div>
- )}
- </div>
- </>
- )}
- </div>
- )}
- <Button
- onClick={() => setShowAddModal(true)}
- disabled={!hasPermission('printers:create')}
- title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
- className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
- >
- <Plus className="w-4 h-4" />
- {t('printers.addPrinter')}
- </Button>
- </>
- );
- return (
- <div className="p-4 md:p-8">
- <div className="space-y-3 mb-6">
- <div>
- <h1 className="text-2xl font-bold text-white flex items-center gap-3">
- <PrinterIcon className="w-7 h-7 text-bambu-green" />
- {t('printers.title')}
- </h1>
- <StatusSummaryBar printers={printers} />
- </div>
- <div ref={toolbarRef} className="relative flex items-center gap-2">
- {/* Only show search bar when printers exist */}
- {printers && printers.length > 0 && (
- <div className="relative min-w-0 flex-1">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
- <input
- type="search"
- name="printer-search"
- autoComplete="off"
- data-1p-ignore
- data-lpignore="true"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder={t('printers.search')}
- aria-label={t('printers.search')}
- 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"
- />
- {search && (
- <button
- type="button"
- aria-label={t('common.clear')}
- onClick={() => setSearch('')}
- className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
- >
- <X className="w-4 h-4" />
- </button>
- )}
- </div>
- )}
- <div
- ref={expandedToolbarControlsRef}
- aria-hidden={compactToolbar}
- inert={compactToolbar}
- 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`}
- >
- <div className="h-6 w-px bg-bambu-dark-tertiary" />
- <div className="flex items-center gap-2">{renderFilterControls()}</div>
- <div className="h-6 w-px bg-bambu-dark-tertiary" />
- <div className="flex items-center gap-2">{renderViewControls()}</div>
- <div className="h-6 w-px bg-bambu-dark-tertiary" />
- <div className="flex items-center gap-2">{renderActionControls()}</div>
- </div>
- {compactToolbar && (
- <div className="ml-auto flex items-center justify-end gap-1">
- <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
- <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
- </ToolbarMenu>
- <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
- <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
- </ToolbarMenu>
- <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
- <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
- </ToolbarMenu>
- </div>
- )}
- </div>
- </div>
- {isLoading ? (
- <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
- ) : printers?.length === 0 ? (
- <Card>
- <CardContent className="text-center py-12">
- <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
- <Button
- onClick={() => setShowAddModal(true)}
- disabled={!hasPermission('printers:create')}
- title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
- >
- <Plus className="w-4 h-4" />
- {t('printers.addPrinter')}
- </Button>
- </CardContent>
- </Card>
- ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
- <Card>
- <CardContent className="text-center py-12">
- <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
- </CardContent>
- </Card>
- ) : pageView === 'camwall' ? (
- <CameraWall
- printers={sortedPrinters}
- maxLive={camWallMaxLive}
- snapshotIntervalSec={camWallSnapshotSec}
- onTileClick={(id, name) => {
- const cameraMode = settings?.camera_view_mode || 'window';
- if (cameraMode === 'embedded') {
- setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
- } else {
- const saved = localStorage.getItem('cameraWindowState');
- const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
- const features = [
- `width=${state.width}`,
- `height=${state.height}`,
- state.left !== undefined ? `left=${state.left}` : '',
- state.top !== undefined ? `top=${state.top}` : '',
- 'menubar=no,toolbar=no,location=no,status=no',
- ].filter(Boolean).join(',');
- window.open(`/camera/${id}`, `camera-${id}`, features);
- }
- }}
- statusMode={camWallStatusMode}
- onChangeMaxLive={(next) => {
- setCamWallMaxLive(next);
- localStorage.setItem('camWallMaxLive', String(next));
- }}
- onChangeSnapshotIntervalSec={(next) => {
- setCamWallSnapshotSec(next);
- localStorage.setItem('camWallSnapshotSec', String(next));
- }}
- onChangeStatusMode={(next) => {
- setCamWallStatusMode(next);
- localStorage.setItem('camWallStatusMode', next);
- }}
- />
- ) : groupedPrinters ? (
- /* Grouped view (location, status, or model) */
- <div className="space-y-6">
- {(() => {
- const keys = sortBy === 'status'
- ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
- : Object.keys(groupedPrinters);
- // For status grouping, asc/desc flips the fixed priority order
- // (asc = error→offline, desc = offline→error). This matches the
- // sort-toggle behaviour for other groupings.
- return (sortAsc ? keys : [...keys].reverse());
- })().map((groupKey) => {
- const groupPrinters = groupedPrinters[groupKey];
- const collapseKey = `${sortBy}:${groupKey}`;
- const isOpen = !collapsedSections[collapseKey];
- const dot = sortBy === 'status'
- ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
- : 'bg-bambu-green';
- const label = sortBy === 'status'
- ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
- : groupKey;
- return (
- <Collapsible
- key={groupKey}
- open={isOpen}
- onToggle={() => toggleSectionCollapse(collapseKey)}
- summaryClassName="py-1"
- summary={
- <h2 className="text-lg font-semibold text-white flex items-center gap-2">
- <span className={`w-2 h-2 rounded-full ${dot}`} />
- {label}
- <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
- {selectionMode && (
- <button
- onClick={(e) => {
- e.stopPropagation();
- if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
- else if (sortBy === 'status') selectByState(groupKey as PrinterState);
- else if (sortBy === 'model') selectByModel(groupKey);
- }}
- className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
- >
- {t('printers.bulk.selectAll')}
- </button>
- )}
- </h2>
- }
- >
- <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
- {groupPrinters.map((printer) => (
- <PrinterCard
- key={printer.id}
- printer={printer}
- hideIfDisconnected={hideDisconnected}
- maintenanceInfo={maintenanceByPrinter[printer.id]}
- viewMode={viewMode}
- cardSize={cardSize}
- amsThresholds={settings ? {
- humidityGood: Number(settings.ams_humidity_good) || 40,
- humidityFair: Number(settings.ams_humidity_fair) || 60,
- tempGood: Number(settings.ams_temp_good) || 28,
- tempFair: Number(settings.ams_temp_fair) || 35,
- } : undefined}
- spoolmanEnabled={spoolmanEnabled}
- hasUnlinkedSpools={hasUnlinkedSpools}
- linkedSpools={linkedSpools}
- spoolmanUrl={spoolmanStatus?.url}
- spoolmanSyncMode={spoolmanSyncMode}
- onGetAssignment={getAssignment}
- onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
- spoolmanSpools={spoolmanSpools}
- spoolmanSlotAssignments={spoolmanSlotAssignments}
- spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
- onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
- timeFormat={settings?.time_format || 'system'}
- cameraViewMode={settings?.camera_view_mode || 'window'}
- onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
- checkPrinterFirmware={settings?.check_printer_firmware !== false}
- dryingPresets={effectiveDryingPresets}
- nozzleTempPresets={effectiveNozzleTempPresets}
- bedTempPresets={effectiveBedTempPresets}
- chamberTempPresets={effectiveChamberTempPresets}
- fanSpeedPresets={effectiveFanSpeedPresets}
- requirePlateClear={settings?.require_plate_clear === true}
- selectionMode={selectionMode}
- isSelected={selectedPrinterIds.has(printer.id)}
- onToggleSelect={toggleSelect}
- onOpenCompactCard={openCompactCard}
- aiDetectionEnabled={isAiMonitored(printer.id)}
- aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
- aiLastError={obicoPrinterStatus?.last_error ?? null}
- />
- ))}
- </div>
- </Collapsible>
- );
- })}
- </div>
- ) : (
- /* Regular grid view */
- <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
- {sortedPrinters.map((printer) => (
- <PrinterCard
- key={printer.id}
- printer={printer}
- hideIfDisconnected={hideDisconnected}
- maintenanceInfo={maintenanceByPrinter[printer.id]}
- viewMode={viewMode}
- cardSize={cardSize}
- spoolmanEnabled={spoolmanEnabled}
- hasUnlinkedSpools={hasUnlinkedSpools}
- linkedSpools={linkedSpools}
- spoolmanUrl={spoolmanStatus?.url}
- spoolmanSyncMode={spoolmanSyncMode}
- onGetAssignment={getAssignment}
- onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
- spoolmanSpools={spoolmanSpools}
- spoolmanSlotAssignments={spoolmanSlotAssignments}
- spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
- onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
- amsThresholds={settings ? {
- humidityGood: Number(settings.ams_humidity_good) || 40,
- humidityFair: Number(settings.ams_humidity_fair) || 60,
- tempGood: Number(settings.ams_temp_good) || 28,
- tempFair: Number(settings.ams_temp_fair) || 35,
- } : undefined}
- timeFormat={settings?.time_format || 'system'}
- cameraViewMode={settings?.camera_view_mode || 'window'}
- onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
- checkPrinterFirmware={settings?.check_printer_firmware !== false}
- dryingPresets={effectiveDryingPresets}
- nozzleTempPresets={effectiveNozzleTempPresets}
- bedTempPresets={effectiveBedTempPresets}
- chamberTempPresets={effectiveChamberTempPresets}
- fanSpeedPresets={effectiveFanSpeedPresets}
- requirePlateClear={settings?.require_plate_clear === true}
- selectionMode={selectionMode}
- isSelected={selectedPrinterIds.has(printer.id)}
- onToggleSelect={toggleSelect}
- onOpenCompactCard={openCompactCard}
- aiDetectionEnabled={isAiMonitored(printer.id)}
- aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
- aiLastError={obicoPrinterStatus?.last_error ?? null}
- />
- ))}
- </div>
- )}
- {cardSize === 2 && compactDrilldownPrinterId != null && (
- <button
- type="button"
- onClick={returnToCompactCards}
- 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}`}
- title={t('common.back', 'Back')}
- >
- <ArrowLeft className="w-4 h-4" />
- {t('common.back', 'Back')}
- </button>
- )}
- {showAddModal && (
- <AddPrinterModal
- onClose={() => setShowAddModal(false)}
- onAdd={(data) => addMutation.mutate(data)}
- existingSerials={printers?.map(p => p.serial_number) || []}
- />
- )}
- {/* Bulk selection toolbar */}
- {selectionMode && printers && (
- <BulkPrinterToolbar
- selectedIds={selectedPrinterIds}
- printers={printers}
- onClose={clearSelection}
- onSelectAll={selectAll}
- onSelectByLocation={selectByLocation}
- onSelectByState={selectByState}
- onAction={handleBulkAction}
- actionPending={bulkActionPending}
- />
- )}
- {/* Bulk action confirmation modals */}
- {bulkConfirmAction === 'stop' && (
- <ConfirmModal
- title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
- message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
- confirmText={t('printers.bulk.confirm.stopButton')}
- variant="danger"
- isLoading={bulkActionPending}
- onConfirm={() => executeBulkAction('stop')}
- onCancel={() => setBulkConfirmAction(null)}
- />
- )}
- {bulkConfirmAction === 'pause' && (
- <ConfirmModal
- title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
- message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
- confirmText={t('printers.bulk.confirm.pauseButton')}
- isLoading={bulkActionPending}
- onConfirm={() => executeBulkAction('pause')}
- onCancel={() => setBulkConfirmAction(null)}
- />
- )}
- {bulkConfirmAction === 'clearPlate' && (
- <ConfirmModal
- title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
- message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
- confirmText={t('printers.bulk.confirm.clearPlateButton')}
- isLoading={bulkActionPending}
- onConfirm={() => executeBulkAction('clearPlate')}
- onCancel={() => setBulkConfirmAction(null)}
- />
- )}
- {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
- {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
- <EmbeddedCameraViewer
- key={camera.id}
- printerId={camera.id}
- printerName={camera.name}
- viewerIndex={index}
- onClose={() => setEmbeddedCameraPrinters(prev => {
- const next = new Map(prev);
- next.delete(camera.id);
- return next;
- })}
- />
- ))}
- </div>
- );
- }
|